Ejemplo n.º 1
1
 private Map<String, Object> query(HttpServletRequest req) {
   final Map<String, Object> map = new HashMap<>();
   for (Map.Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
     map.put(entry.getKey(), entry.getValue());
   }
   return map;
 }
Ejemplo n.º 2
0
 @RequestMapping(value = "/productos", params = "term", produces = "application/json")
 public @ResponseBody List<LabelValueBean> productos(
     HttpServletRequest request, @RequestParam("term") String filtro) {
   for (String nombre : request.getParameterMap().keySet()) {
     log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
   }
   Map<String, Object> params = new HashMap<>();
   params.put("almacen", request.getSession().getAttribute("almacenId"));
   params.put("filtro", filtro);
   params = productoDao.lista(params);
   List<LabelValueBean> valores = new ArrayList<>();
   List<Producto> productos = (List<Producto>) params.get("productos");
   for (Producto producto : productos) {
     StringBuilder sb = new StringBuilder();
     sb.append(producto.getSku());
     sb.append(" | ");
     sb.append(producto.getNombre());
     sb.append(" | ");
     sb.append(producto.getDescripcion());
     sb.append(" | ");
     sb.append(producto.getExistencia()).append(" ").append(producto.getUnidadMedida());
     sb.append(" | ");
     sb.append(producto.getPrecioUnitario());
     valores.add(new LabelValueBean(producto.getId(), sb.toString()));
   }
   return valores;
 }
Ejemplo n.º 3
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);
    }
  }
Ejemplo n.º 4
0
 /**
  * Parse XML document from HTTP-Post request.
  *
  * @param request HTTP-Post request
  * @return XML document
  * @throws OwsExceptionReport If an error occurs
  */
 public static XmlObject parseXmlSosRequest(final HttpServletRequest request)
     throws OwsExceptionReport {
   XmlObject doc;
   try {
     if (request.getParameterMap().isEmpty()) {
       final String requestContent =
           StringHelper.convertStreamToString(
               HTTPUtils.getInputStream(request), request.getCharacterEncoding());
       doc = parseXmlString(requestContent);
     } else {
       doc =
           XmlObject.Factory.parse(
               SosHelper.parseHttpPostBodyWithParameter(
                   request.getParameterNames(), request.getParameterMap()));
     }
   } catch (final XmlException xmle) {
     throw new NoApplicableCodeException()
         .causedBy(xmle)
         .withMessage(
             "An xml error occured when parsing the request! Message: %s", xmle.getMessage());
   } catch (final IOException ioe) {
     throw new NoApplicableCodeException()
         .causedBy(ioe)
         .withMessage("Error while reading request! Message: %s", ioe.getMessage());
   }
   // validateDocument(doc);
   return doc;
 }
Ejemplo n.º 5
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    PrintWriter pw = resp.getWriter();

    applicationCache.persistLogs();

    if (req.getParameterMap().containsKey("max")) {
      int max = Integer.parseInt(req.getParameter("max"));
      List<Log> logs = loggerExpense.findAll(max);
      pw.println("Found " + logs.size() + " logs...:<br />");
      for (Log log : logs) {
        pw.println(log.toString());
      }

    } else if (req.getParameterMap().containsKey("type")) {
      int type = Integer.parseInt(req.getParameter("type"));
      List<Log> logs = loggerExpense.findByType(type);
      pw.println("Found " + logs.size() + " logs...:");
      for (Log log : logs) {
        pw.println(log.toString());
      }
    } else {
      List<Log> logs = loggerExpense.findAll(-1);
      pw.println("Found " + logs.size() + " logs...:");
      for (Log log : logs) {
        pw.println(log.toString());
      }
    }
  }
Ejemplo n.º 6
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    BookService service = BasicFactory.getFactory().getService(BookService.class);

    try {
      // 1.封裝數據、校驗數據
      /*if(request.getParameter("title") == null || "".equals(request.getParameter("title"))){
      	throw new RuntimeException("小冊標題為空!!");
      }*/

      Book book = new Book();
      BeanUtils.populate(book, request.getParameterMap());
      Map<String, String[]> map = request.getParameterMap();

      // 2.調用Service增加Book
      service.addBook(book);

      // 3.重定向回個人頁面
      response.getWriter().write("新增成功,3秒後回到個人頁面!!");
      response.setHeader("Refresh", "3;url=/index.jsp");

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 7
0
  public String getURL() {
    // all this trickier with maps is to reduce the number of objects created
    Map<String, Object> fullParams = null;

    if (params != null) {
      fullParams = new HashMap<String, Object>();
    }

    if (page == null) {
      // No particular page requested, so go to "same page"
      // Add query params to parameters
      if (fullParams != null) {
        fullParams.putAll(request.getParameterMap());
      } else {
        fullParams = request.getParameterMap();
      }
    }

    // added parameters override, just like in URLTag
    if (params != null) {
      fullParams.putAll(params);
    }

    return urlHelper.buildUrl(page, request, response, fullParams);
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    logger.debug("Request URL: " + request.getRequestURI());
    logger.debug("Request Path Info: " + request.getPathInfo());
    logger.debug("Request Param: " + request.getQueryString());

    RestRequest restRequest = null;
    try {
      String url = request.getPathInfo();
      if (request.getQueryString() != null) url += "?" + request.getQueryString();
      restRequest = new RestRequest(url, HttpMethod.POST.name());
    } catch (ServletException e) {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("Invalid URL!");
      return;
    }

    String serviceId = restRequest.getId();
    String format = restRequest.getFormat();

    for (String s : request.getParameterMap().keySet())
      logger.debug(s + " --- " + request.getParameterMap().get(s).toString());
    logger.debug("Id: " + serviceId);
    logger.debug("Format: " + format);

    // request.setCharacterEncoding(CharEncoding.ISO_8859_1);
    logger.info("Content-Type: " + request.getContentType());

    String formData = null;
    String inputLang = "";
    if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_XML))
      inputLang = SerializationLang.XML;
    if (request.getContentType().startsWith(MimeType.TEXT_XML)) inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_XML))
      inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_N3))
      inputLang = SerializationLang.N3;
    if (request.getContentType().startsWith(MimeType.APPLICATION_FORM_URLENCODED)) {
      inputLang = SerializationLang.N3; // default for html forms
      formData = request.getParameter("rdf");
      logger.debug(formData);
    } else {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("The content type is neither rdf+xml nor rdf+n3");
      return;
    }

    InputStream in = request.getInputStream();

    if (formData != null) {
      in = new ByteArrayInputStream(formData.getBytes());
    }

    new PostRequestManager(serviceId, in, inputLang, format, response).HandleRequest();

    response.flushBuffer();
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    User user = requestContext.getCurrentUser();

    Errata errata = requestContext.lookupErratum();
    DataResult dr = ErrataManager.systemsAffected(user, errata.getId(), null);

    RhnSet set = RhnSetDecl.SYSTEMS_AFFECTED.get(user);
    RhnListSetHelper helper = new RhnListSetHelper(request);

    // if its not submitted
    // ==> this is the first visit to this page
    // clear the 'dirty set'
    if (!requestContext.isSubmitted()) {
      set.clear();
      RhnSetManager.store(set);
    }

    if (request.getParameter(DISPATCH) != null) {
      helper.updateSet(set, LIST_NAME);
      if (!set.isEmpty()) {
        // Send to AffectedSystemsAction to handle submit
        return strutsDelegate.forwardParams(
            mapping.findForward("confirm"), request.getParameterMap());
      }
      RhnHelper.handleEmptySelection(request);
    }

    if (ListTagHelper.getListAction(LIST_NAME, request) != null) {
      helper.execute(set, LIST_NAME, dr);
    }

    // if I have a previous set selections populate data using it
    if (!set.isEmpty()) {
      helper.syncSelections(set, dr);
      ListTagHelper.setSelectedAmount(LIST_NAME, set.size(), request);
    }

    TagHelper.bindElaboratorTo("systemAffectedList", dr.getElaborator(), request);
    ListTagHelper.bindSetDeclTo(LIST_NAME, RhnSetDecl.SYSTEMS_AFFECTED, request);

    request.setAttribute(RequestContext.PAGE_LIST, dr);
    request.setAttribute("set", set);
    request.setAttribute("errata", errata);
    request.setAttribute(
        ListTagHelper.PARENT_URL,
        request.getRequestURI() + "?" + RequestContext.ERRATA_ID + "=" + errata.getId());

    return strutsDelegate.forwardParams(
        mapping.findForward(RhnHelper.DEFAULT_FORWARD), request.getParameterMap());
  }
  /**
   * Handles the refresh call by checking the request parameters and delegating out to helper
   * methods.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public ModelAndView refresh(UifFormBase form) {
    HttpServletRequest request = form.getRequest();

    if (request.getParameterMap().containsKey(UifParameters.MESSAGE_TO_DISPLAY)) {
      String messageToDisplay = request.getParameter(UifParameters.MESSAGE_TO_DISPLAY);

      if (StringUtils.isNotBlank(messageToDisplay)) {
        GlobalVariables.getMessageMap()
            .putErrorForSectionId(KRADConstants.GLOBAL_ERRORS, messageToDisplay);
      }
    }

    if (request.getParameterMap().containsKey(UifParameters.REFRESH_STATUS)) {
      String refreshStatus = request.getParameter(UifParameters.REFRESH_STATUS);

      // if the return URL reported an error, do not continue with the refresh call
      if (UifConstants.RefreshStatus.ERROR.equals(refreshStatus)) {
        return getModelAndViewService().getModelAndView(form);
      }
    }

    String refreshCallerType = "";
    if (request.getParameterMap().containsKey(KRADConstants.REFRESH_CALLER_TYPE)) {
      refreshCallerType = request.getParameter(KRADConstants.REFRESH_CALLER_TYPE);
    }

    if (StringUtils.equals(refreshCallerType, UifConstants.RefreshCallerTypes.MULTI_VALUE_LOOKUP)) {
      processMultiValueReturn(form, request);
    }

    if (request.getParameterMap().containsKey(KRADConstants.REFERENCES_TO_REFRESH)) {
      final String referencesToRefresh = request.getParameter(KRADConstants.REFERENCES_TO_REFRESH);

      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              ViewLifecycle.getHelper().refreshReferences(referencesToRefresh);
            }
          };

      ViewLifecycle.encapsulateLifecycle(
          form.getView(), form, form.getViewPostMetadata(), null, request, runnable);
    }

    if (request.getParameterMap().containsKey(UifParameters.QUICKFINDER_ID)) {
      String quickfinderId = request.getParameter(UifParameters.QUICKFINDER_ID);

      setFocusJumpFromQuickfinder(form, quickfinderId);

      invokeQuickfinderCallback(form, request, quickfinderId);
    }

    return getModelAndViewService().getModelAndView(form);
  }
Ejemplo n.º 11
0
  @Transactional
  @RequestMapping(value = "/graba", method = RequestMethod.POST)
  public String graba(
      HttpServletRequest request,
      HttpServletResponse response,
      @Valid AlumnoPaquete alumnoPaquete,
      BindingResult bindingResult,
      Errors errors,
      Model modelo,
      RedirectAttributes redirectAttributes) {
    for (String matricula : request.getParameterMap().keySet()) {
      log.debug("Param: {} : {}", matricula, request.getParameterMap().get(matricula));
    }
    if (bindingResult.hasErrors()) {
      log.debug("Hubo algun error en la forma, regresando");
      Map<String, Object> params = new HashMap<>();
      params.put("empresa", request.getSession().getAttribute("empresaId"));
      return Constantes.PATH_ALUMNOPAQUETE_NUEVO;
    }

    try {
      AlumnoPaquete tmp = null;
      Usuario usuario = ambiente.obtieneUsuario();

      if (alumnoPaquete.getId() != null) {
        tmp = alumnoPaqueteManager.obtiene(alumnoPaquete.getId());
        tmp.setPaquete(paqueteDao.obtiene(alumnoPaquete.getPaquete().getId()));
        tmp.setMatricula(alumnoPaquete.getMatricula());
        tmp.setStatus(alumnoPaquete.getStatus());
        alumnoPaqueteManager.graba(tmp, usuario);
        redirectAttributes.addFlashAttribute(
            Constantes.CONTAINSKEY_MESSAGE, "alumnoPaquete.actualizado.message");
        redirectAttributes.addFlashAttribute(
            Constantes.CONTAINSKEY_MESSAGE_ATTRS, new String[] {alumnoPaquete.getMatricula()});
      } else {
        alumnoPaquete.setPaquete(paqueteDao.obtiene(alumnoPaquete.getPaquete().getId()));
        alumnoPaqueteManager.graba(alumnoPaquete, usuario);
        redirectAttributes.addFlashAttribute(
            Constantes.CONTAINSKEY_MESSAGE, "alumnoPaquete.creado.message");
        redirectAttributes.addFlashAttribute(
            Constantes.CONTAINSKEY_MESSAGE_ATTRS, new String[] {alumnoPaquete.getMatricula()});
      }

    } catch (ConstraintViolationException e) {
      log.error("No se pudo crear el tipo de Beca", e);
      return Constantes.PATH_ALUMNOPAQUETE_NUEVO;
    }

    return "redirect:/" + Constantes.PATH_ALUMNOPAQUETE_LISTA + "/";
  }
Ejemplo n.º 12
0
  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);
      }
    }
  }
Ejemplo n.º 13
0
  /**
   * 使用模板渲染
   *
   * @param template 模板名稱
   * @param dataModel 模板參數
   */
  public <T> void render(String template, Map<String, T> dataModel) {
    try {
      if (dataModel == null) dataModel = new HashMap<String, T>();

      dataModel.put("contextPath", (T) getContextPath(request));
      // 模板中传入session值
      HttpSession session = request.getSession();
      String[] sessionName = session.getValueNames();
      for (String name : sessionName) {
        dataModel.put(name, (T) request.getSession().getAttribute(name));
      }
      // 模板中传入request值
      Map paramMap = request.getParameterMap();
      for (Iterator itor = paramMap.keySet().iterator(); itor.hasNext(); ) {
        Object key = itor.next();
        Object object = paramMap.get(key);
        if (key instanceof String && object != null) {

          if (object.getClass().isArray()) {
            Object[] sValue = (Object[]) object;
            String value = sValue[0].toString();
            if (value.trim().isEmpty()) continue;
            dataModel.put(key.toString(), (T) value);
          }
        }
      }
      String result = FreeMarkerTool.getSingleton().getTemplateResult(template, dataModel);
      response.getWriter().write(result);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }
  @Override
  public void doFilter(
      ServletRequest servletRqst, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    // First look for a session token in the header or as a parameter
    HttpServletRequest req = (HttpServletRequest) servletRqst;
    String sessionToken = req.getHeader(AuthorizationConstants.SESSION_TOKEN_PARAM);
    if (sessionToken == null) {
      // Check for a session token as a parameter
      sessionToken = req.getParameter(AuthorizationConstants.SESSION_TOKEN_PARAM);
    }

    // Determine the caller's identity
    String username = null;

    // A session token maps to a specific user
    if (sessionToken != null) {
      try {
        String userId = authenticationService.revalidate(sessionToken);
        username = authenticationService.getUsername(userId);
      } catch (Exception xee) {
        String reason = "The session token is invalid.";
        reject(req, (HttpServletResponse) servletResponse, reason);
        log.warn("invalid session token", xee);
        return;
      }

      // If there is no session token, then check for a HMAC signature
    } else if (isSigned(req)) {
      username = req.getHeader(AuthorizationConstants.USER_ID_HEADER);
      try {
        String secretKey = authenticationService.getSecretKey(username);
        matchHMACSHA1Signature(req, secretKey);
      } catch (UnauthorizedException e) {
        reject(req, (HttpServletResponse) servletResponse, e.getMessage());
        log.warn("Invalid HMAC signature", e);
        return;
      } catch (NotFoundException e) {
        reject(req, (HttpServletResponse) servletResponse, e.getMessage());
        log.warn("Invalid HMAC signature", e);
        return;
      }
    }
    if (username == null && !allowAnonymous) {
      String reason = "The session token provided was missing, invalid or expired.";
      reject(req, (HttpServletResponse) servletResponse, reason);
      log.warn("Anonymous not allowed");
      return;
    }
    if (username == null) {
      username = AuthorizationConstants.ANONYMOUS_USER_ID;
    }

    // Pass along, including the user ID
    @SuppressWarnings("unchecked")
    Map<String, String[]> modParams = new HashMap<String, String[]>(req.getParameterMap());
    modParams.put(AuthorizationConstants.USER_ID_PARAM, new String[] {username});
    HttpServletRequest modRqst = new ModParamHttpServletRequest(req, modParams);
    filterChain.doFilter(modRqst, servletResponse);
  }
  @Override
  @SuppressWarnings("unchecked")
  public ActionForward refresh(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    ActionForward forward = super.refresh(mapping, form, request, response);

    String prefix =
        getSpecialReviewService().getProtocolSaveLocationPrefix(request.getParameterMap());
    InstitutionalProposalForm proposalForm = (InstitutionalProposalForm) form;

    InstitutionalProposalSpecialReview proposalSpecialReview = null;
    if (StringUtils.startsWith(prefix, "specialReviewHelper.newSpecialReview")) {
      proposalSpecialReview = proposalForm.getSpecialReviewHelper().getNewSpecialReview();
    } else {
      int index = getSpecialReviewService().getProtocolIndex(prefix);
      if (index != -1) {
        proposalSpecialReview =
            proposalForm
                .getInstitutionalProposalDocument()
                .getInstitutionalProposal()
                .getSpecialReviews()
                .get(index);
      }
    }

    proposalForm.getSpecialReviewHelper().prepareProtocolLinkViewFields(proposalSpecialReview);

    return forward;
  }
  void doDelete(final HttpServletRequest req, final HttpServletResponse resp) {
    try {
      // Parse out the required API versions.
      final AcceptAPIVersion acceptVersion = parseAcceptAPIVersion(req);

      // Prepare response.
      prepareResponse(req, resp);

      // Validate request.
      preprocessRequest(req);
      rejectIfNoneMatch(req);

      final Map<String, String[]> parameters = req.getParameterMap();
      final DeleteRequest request =
          Requests.newDeleteRequest(getResourceName(req)).setRevision(getIfMatch(req));
      for (final Map.Entry<String, String[]> p : parameters.entrySet()) {
        final String name = p.getKey();
        final String[] values = p.getValue();
        if (parseCommonParameter(name, values, request)) {
          continue;
        } else {
          request.setAdditionalParameter(name, asSingleValue(name, values));
        }
      }
      doRequest(req, resp, acceptVersion, request);
    } catch (final Exception e) {
      fail(req, resp, e);
    }
  }
Ejemplo n.º 17
0
 private Object getParameters(HttpServletRequest request, String prefix, boolean isCheckBox) {
   Map<String, String[]> primalParameters = request.getParameterMap();
   if (primalParameters == null) {
     return null;
   }
   Map<String, Object> result = new HashMap<String, Object>();
   String key;
   String[] value;
   String prefix_ = null;
   if (prefix != null) {
     prefix_ = prefix + "[";
   }
   for (Entry<String, String[]> primalPE : primalParameters.entrySet()) {
     key = primalPE.getKey();
     if (prefix == null || key.startsWith(prefix_)) {
       value = primalPE.getValue();
       if (!getParametersSetResultMap(result, key, value, isCheckBox)) {
         return null;
       }
     }
   }
   if (prefix != null) {
     return result.get(prefix);
   }
   return result;
 }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      String asyncTaskClass = getParameter(request, TaskQueueAsyncTaskScheduler.TASK_QUEUE);

      // event details
      String eventClassAsString = getParameter(request, TaskQueueAsyncTaskScheduler.EVENT);
      String eventAsJson = getParameter(request, TaskQueueAsyncTaskScheduler.EVENT_AS_JSON);

      // if event is passed then it should be dispatched to it's handler
      if (!Strings.isNullOrEmpty(eventClassAsString) && !Strings.isNullOrEmpty(eventAsJson)) {

        eventDispatcher.dispatchAsyncEvent(eventClassAsString, eventAsJson);

        // if asyncTask is provided it should be executed
      } else if (!Strings.isNullOrEmpty(asyncTaskClass)) {

        Map<String, String[]> params = Maps.newHashMap(request.getParameterMap());

        // todo do not pass map here;
        taskDispatcher.dispatchAsyncTask(params, asyncTaskClass);
      }

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 19
0
  private void recuperaParams(HttpServletRequest request, ActionForm form) {
    LoteForm loteForm = (LoteForm) form;
    Map<Integer, LoteProdutoForm> perfumes = new HashMap<Integer, LoteProdutoForm>();

    for (String p : loteForm.getPerfume()) {
      Integer idPerfume = Integer.valueOf(p);
      LoteProdutoForm loteProduto = new LoteProdutoForm();
      loteProduto.setIdPerfume(idPerfume);
      perfumes.put(idPerfume, loteProduto);
    }

    for (Object key : request.getParameterMap().keySet()) {
      String keyStr = (String) key;
      if (keyStr.contains("quantidade")) {
        String qtd[] = keyStr.split(";");
        Integer idPerfume = Integer.valueOf(qtd[1]);
        LoteProdutoForm perf = perfumes.get(idPerfume);
        perf.setQuantidade(Integer.valueOf(request.getParameter(keyStr)));
      }

      if (keyStr.contains("preco")) {
        String prec[] = keyStr.split(";");
        Integer idPerfume = Integer.valueOf(prec[1]);
        LoteProdutoForm perf = perfumes.get(idPerfume);
        String value = request.getParameter(keyStr).replace(",", ".");
        perf.setPreco(Double.valueOf(value));
      }
    }
    loteForm.setLoteProdutoForm(perfumes.values());
  }
Ejemplo n.º 20
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      String[] values = map.get("vector");
      if (values != null) param = values[0];
    }

    String bar = doSomething(param);

    String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='******'";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.PreparedStatement statement =
          connection.prepareStatement(
              sql,
              java.sql.ResultSet.TYPE_FORWARD_ONLY,
              java.sql.ResultSet.CONCUR_READ_ONLY,
              java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT);
      statement.setString(1, "foo");
      statement.execute();
      org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response);
    } catch (java.sql.SQLException e) {
      if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        response.getWriter().println("Error processing request.");
        return;
      } else throw new ServletException(e);
    }
  } // end doPost
Ejemplo n.º 21
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    @SuppressWarnings("unchecked")
    Map<String, String[]> params = req.getParameterMap();

    HttpSession session = req.getSession(true);
    session.setAttribute(LANG, "en"); // Defaults to English //$NON-NLS-1$

    if (params.containsKey("lang")) { // $NON-NLS-1$
      String lang = params.get("lang")[0]; // $NON-NLS-1$
      Messages.setLang(lang);
      if (this.availableLanguages.contains(lang)) {
        session.setAttribute(LANG, lang);
        resp.getWriter()
            .print(
                Messages.getString("localeservlet.lang_set_to")
                    + lang
                    + "'"); //$NON-NLS-1$ //$NON-NLS-2$
      } else {
        resp.sendError(
            HttpServletResponse.SC_BAD_REQUEST,
            Messages.getString("localeservlet.lang_not_available")); // $NON-NLS-1$
      }
    } else {
      resp.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          Messages.getString("localeservlet.not_lang_parameter") // $NON-NLS-1$
              + this.availableLanguages.toString());
    }
  }
Ejemplo n.º 22
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      param = map.get("foo")[0];
    }

    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
Ejemplo n.º 23
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      param = map.get("foo")[0];
    }

    String bar;
    String guess = "ABC";
    char switchTarget = guess.charAt(2);

    // Simple case statement that assigns param to bar on conditions 'A' or 'C'
    switch (switchTarget) {
      case 'A':
        bar = param;
        break;
      case 'B':
        bar = "bobs_your_uncle";
        break;
      case 'C':
      case 'D':
        bar = param;
        break;
      default:
        bar = "bobs_your_uncle";
        break;
    }

    new java.io.File(bar, "/Test.txt");
  }
Ejemplo n.º 24
0
  public static Map getRequestMap(HttpServletRequest request) {
    Map properties = request.getParameterMap();
    // 返回值Map
    Map returnMap = new HashMap();
    Iterator entries = properties.entrySet().iterator();
    Map.Entry entry;
    String name = "";
    String value = "";
    while (entries.hasNext()) {
      entry = (Map.Entry) entries.next();
      name = (String) entry.getKey();
      Object valueObj = entry.getValue();
      if (null == valueObj) {
        value = "";
      } else if (valueObj instanceof String[]) {
        String[] values = (String[]) valueObj;
        for (int i = 0; i < values.length; i++) {
          value = values[i] + ",";
        }
        value = value.substring(0, value.length() - 1);
      } else {
        value = valueObj.toString();
      }

      returnMap.put(name, value);
    }
    return returnMap;
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");

    Map<String, String[]> parametersMap = req.getParameterMap();
    ServletContext context = req.getSession().getServletContext();

    List<JavaWorldNews> yourList = (List<JavaWorldNews>) context.getAttribute("javaNews");

    Boolean archiveFlag = false;

    if ((Boolean) req.getSession().getAttribute("javaWorldIndexFlag") == false) {
      archiveFlag = true;
    }
    req.getSession().setAttribute("javaWorldAchiveFlag", archiveFlag);

    for (JavaWorldNews list : yourList) {
      JavaWorldNewsArchive javaWorldNewsArchive =
          new JavaWorldNewsArchive(list.getTitle(), list.getDescription(), list.getLink());
      JavaWorldArchiveJpaDao javaWorldArchiveJpaDao = new JavaWorldArchiveJpaDao();
      if (javaWorldArchiveJpaDao.create(javaWorldNewsArchive).equals("duplicate")) {
        break;
      }
    }

    res.sendRedirect("JavaWorldNewsController");
  }
Ejemplo n.º 26
0
 /**
  * 获取请求的路径
  *
  * @param request request对象
  * @param hasParam 是否包含参数列表
  * @return
  */
 public static String getUri(HttpServletRequest request, boolean hasParam) {
   StringBuffer buffer = new StringBuffer();
   StringBuffer loginPath = request.getRequestURL();
   String path = request.getContextPath();
   String basePath =
       request.getScheme()
           + "://"
           + request.getServerName()
           + ":"
           + request.getServerPort()
           + path
           + "/";
   String userPath = loginPath.substring(basePath.length(), loginPath.length());
   buffer.append(userPath);
   if (hasParam) {
     Map<String, String[]> map = request.getParameterMap();
     int index = 0;
     for (String key : map.keySet()) {
       if (index == 0) buffer.append("?");
       else buffer.append("&");
       index++;
       String[] paravalue = map.get(key);
       buffer.append(key + "=" + paravalue[0]);
     }
   }
   return buffer.toString();
 }
Ejemplo n.º 27
0
 public static Map<String, String> copyParameterMap(HttpServletRequest httpServletRequest) {
   Map<String, String> ret = new HashMap<String, String>();
   for (Object key : httpServletRequest.getParameterMap().keySet()) {
     ret.put((String) key, httpServletRequest.getParameter((String) key));
   }
   return ret;
 }
  /*
   * This controller method is for demonstration purposes only. It contains a call to
   * catalogService.findActiveProductsByCategory, which may return a large list. A
   * more performant solution would be to utilize data paging techniques.
   */
  protected boolean addProductsToModel(
      HttpServletRequest request, ModelMap model, CatalogSort catalogSort) {
    boolean productFound = false;

    String productId = request.getParameter("productId");
    Product product = null;
    try {
      product = catalogService.findProductById(new Long(productId));
    } catch (Exception e) {
      // If product is not found, return all values in category
    }

    if (product != null && product.isActive()) {
      productFound = validateProductAndAddToModel(product, model);
      addRatingSummaryToModel(productId, model);
    } else {
      Category currentCategory = (Category) model.get("currentCategory");
      List<Product> productList =
          catalogService.findActiveProductsByCategory(currentCategory, SystemTime.asDate());
      SearchFilterUtil.filterProducts(
          productList, request.getParameterMap(), new String[] {"manufacturer", "sku.salePrice"});

      if ((catalogSort != null) && (catalogSort.getSort() != null)) {
        populateProducts(productList, currentCategory);
        model.addAttribute("displayProducts", sortProducts(catalogSort, productList));
      } else {
        catalogSort = new CatalogSort();
        catalogSort.setSort("featured");
        populateProducts(productList, currentCategory);
        model.addAttribute("displayProducts", sortProducts(catalogSort, productList));
      }
    }

    return productFound;
  }
Ejemplo n.º 29
0
  /**
   * Returns true if the parameter string prior to the "sig" parameter match the "sig" parameter
   * when combined with the key and hashed. For post requests, the parameter order is not guaranteed
   * and so is assumed to be sorted alphabetically by key.
   *
   * @param req
   * @param secret
   * @return
   */
  public static boolean isAuthenticatedRequest(HttpServletRequest req, String secret) {
    String query, sig = getStringParameter(req, "sig"), method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
      query = req.getQueryString();

      if (StringUtils.isBlank(query) || StringUtils.isBlank(sig)) return false;

      query = query.replace("&sig=" + sig, EMPTY);
    } else if (method.equalsIgnoreCase("POST")) {
      TreeMap<String, String[]> params = new TreeMap(req.getParameterMap());
      params.remove("sig"); // remove the signature

      StringBuilder buf = new StringBuilder();
      for (Map.Entry<String, String[]> entry : params.entrySet()) {
        if (buf.length() > 0) buf.append("&");

        buf.append(entry.getKey());
        buf.append('=');
        buf.append(entry.getValue()[0]);
      }
      query = buf.toString();
    } else // We're not supporting auth on non GET or POST requests
    return false;

    return signQueryString(query, secret).equals(sig);
  }
 private ServletRequest prepareServletRequest(
     Object target, NativeWebRequest request, MethodParameter parameter) {
   String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
   HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
   MultipartRequest multipartRequest =
       WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
   MockHttpServletRequest mockRequest = null;
   if (multipartRequest != null) {
     MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
     for (MultipartFile file : multipartRequest.getFileMap().values()) {
       mockMultipartRequest.addFile(
           new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file));
     }
     mockRequest = mockMultipartRequest;
   } else {
     mockRequest = new MockHttpServletRequest();
   }
   for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
     String parameterName = entry.getKey();
     String value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
     Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
     String parameterName = entry.getKey();
     String[] value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   return mockRequest;
 }