예제 #1
0
	/**
	 * 普通ajax请求
	 * @param request
	 * @param response
	 */
	public void generalAjax(SimplEntity entity, HttpServletRequest request,HttpServletResponse response){
		AjaxResponseBean ajaxResponseBean=new AjaxResponseBean();
		ajaxResponseBean.setStatus("success");
		ObjectMapper objectMapper = new ObjectMapper();
		/***
		 * 当表单是通过ajax(jquery)提交的
		 * 提交上来的表单编码是 UTF-8 (默认)
		 * 服务器做出响应时需要将 response的编码设置成通request请求一样
		 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL
		 * 
		 */		
		response.setCharacterEncoding(request.getCharacterEncoding());
		System.out.println(request.getCharacterEncoding());
		try {
			ajaxResponseBean.setData(objectMapper.writeValueAsString(entity));
			System.out.println(ajaxResponseBean.getData());
			write(response, ajaxResponseBean);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 /** This method is not adapted used in SAML_SP case. */
 void reLogginUserIfRequired(
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     AuthorizationRequestData rdo,
     StringBuffer url) {
   final String userId = httpRequest.getParameter(PARAM_LOGIN_USER_ID);
   if (!ADMStringUtils.isBlank(userId)) {
     // user login data was just provided by the login dialog
     try {
       ServiceAccess serviceAccess = ServiceAccess.getServiceAcccessFor(httpRequest.getSession());
       IdentityService identityService = serviceAccess.getService(IdentityService.class);
       rdo.setUserId(userId);
       rdo.setPassword(httpRequest.getParameter(PARAM_LOGIN_PASSWORD));
       VOUser voUser = readTechnicalUserFromDb(identityService, rdo);
       serviceAccess.login(voUser, rdo.getPassword(), httpRequest, httpResponse);
       httpRequest
           .getSession()
           .setAttribute(Constants.SESS_ATTR_USER, identityService.getCurrentUserDetails());
     } catch (Exception e2) {
       httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN);
       // open marketplace login dialog again and fill in
       // userId
       appendParam(
           url,
           Constants.REQ_PARAM_AUTO_OPEN_MP_LOGIN_DIALOG,
           Boolean.TRUE.toString(),
           httpRequest.getCharacterEncoding());
       appendParam(url, Constants.REQ_PARAM_USER_ID, userId, httpRequest.getCharacterEncoding());
     }
   }
 }
예제 #3
0
    @Override
    public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext)
        throws IOException {
      wrappedRequest = true;
      // if we set the chracter encoding AFTER we do wrap request, we will get
      // a failing test
      assertNotNull(request.getCharacterEncoding());
      assertEquals("UTF-16_DUMMY", request.getCharacterEncoding());

      return request;
    }
예제 #4
0
 public void serviceAction(
     HttpServletRequest request,
     HttpServletResponse response,
     ServletContext context,
     ActionMapping mapping)
     throws ServletException {
   serviceRequest = true;
   // if we set the chracter encoding AFTER we do wrap request, we will get
   // a failing test
   assertNotNull(request.getCharacterEncoding());
   assertEquals("UTF-16_DUMMY", request.getCharacterEncoding());
 }
예제 #5
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (ServletFileUpload.isMultipartContent(request)) {
      UploadTools uploadTools = new UploadTools();
      String path = request.getSession().getServletContext().getRealPath("/") + "/";
      ServletFileUpload upload = uploadTools.initUpload(path);
      String image = null, introduce = null, strategy = null;
      try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
          FileItem item = iter.next();

          if ("introduce".equals(item.getFieldName())) {
            introduce = item.getString(request.getCharacterEncoding());
          } else if ("strategy".equals(item.getFieldName())) {
            strategy = item.getString(request.getCharacterEncoding());
          } else {
            image = uploadTools.uploadFile(path, item);
            System.out.println(image);
          }
        }
      } catch (FileUploadException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

      HttpSession session = request.getSession(true);
      Object cityName = session.getAttribute("searchcity");
      // System.out.println(cityName);
      // Object image1 = session.getAttribute("image");

      DBTools dbtools = new DBTools();
      String sql =
          "update city set c_introduce='"
              + introduce
              + "',c_path='"
              + image
              + "',c_strategy='"
              + strategy
              + "' where c_name='"
              + cityName
              + "';";

      int count = dbtools.update(sql);
      if (count > 0) {
        response.sendRedirect("success.jsp");
      }
    }
  }
예제 #6
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (request.getCharacterEncoding() == null) request.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    JSONObject ret = new JSONObject();

    PrintWriter out = response.getWriter();
    Enumeration<String> enumTest = request.getParameterNames();
    HashMap<String, Object> requestMap = new HashMap<String, Object>();
    while (enumTest.hasMoreElements()) {
      String tmp = enumTest.nextElement().toString();
      requestMap.put(tmp, request.getParameter(tmp));
    }
    try {
      Kayttaja kayttaja =
          new Kayttaja(SecurityContextHolder.getContext().getAuthentication().getName());
      int orgId = Integer.parseInt(requestMap.get("org_id").toString());
      String lang = requestMap.get("lang").toString();
      if (lang == null || lang == "") lang = "fi";

      org = new Organisation(lang);
      MapData md = new MapData(lang);
      ret = md.getExtentByType(MapData.TYPE_ORGANISATIONS, orgId);
      ret.put("success", true);
      out.println(ret.toString());

    } catch (Exception e) {
      log.error(ExceptionUtils.getStackTrace(e));
      out.println("{'success':'false', 'msg': 'Tapahtui odottamaton virhe sovelluksessa.'}");
    }
  }
예제 #7
0
파일: StringUtil.java 프로젝트: ikms/ikms
 // 返回指定表单名的数组
 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;
   // }
 }
  /**
   * Reads user profile from ldap.
   *
   * @param context the current request context (contains the active user)
   * @param request HTTP request.
   * @return user the user whose profile was read
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   * @throws SQLException if a database communication exception occurs
   * @throws CredentialsDeniedException
   * @throws UnsupportedEncodingException
   */
  protected User readUserProfile(RequestContext context, HttpServletRequest request)
      throws Exception {

    IdentityAdapter idAdapter = context.newIdentityAdapter();
    User user = new User();
    String[] parts = request.getRequestURI().toString().split("/");
    String sEncoding = request.getCharacterEncoding();
    if ((sEncoding == null) || (sEncoding.trim().length() == 0)) {
      sEncoding = "UTF-8";
    }

    if (parts.length > 0) {
      String userIdentifier = Val.chkStr(URLDecoder.decode(parts[5].trim(), "UTF-8"));
      if (userIdentifier.endsWith(userDIT)) {
        user.setDistinguishedName(userIdentifier);
        DistinguishedNameCredential dnCredential = new DistinguishedNameCredential();
        dnCredential.setDistinguishedName(userIdentifier);
        user.setCredentials(dnCredential);
      } else if (userIdentifier.length() > 0) {
        user.setCredentials(new UsernameCredential(userIdentifier));
      }
      ((LdapIdentityAdapter) idAdapter).populateUser(context, user);
      return user;
    } else {
      throw new Exception("error");
    }
  }
예제 #9
0
	/**
	 * easyUiForm 表单
	 * @param request
	 * @param response
	 */
	public void easyUiFormGet(SimplEntity entity ,HttpServletRequest request, HttpServletResponse response){
		//System.out.println("cerator");
		AjaxResponseBean ajaxResponseBean=new AjaxResponseBean();
		ajaxResponseBean.setStatus("success");
		ObjectMapper objectMapper = new ObjectMapper();
		/***
		 * 当表单是通过ajax(jquery)提交的
		 * 提交上来的表单编码是 UTF-8 (默认)
		 * 服务器做出响应时需要将 response的编码设置成通request请求一样
		 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL
		 * 而easyuifrom 是对于jquery的一个封装 所有一样要使用  而它提交的表单
		 * request.getCharacterEncoding() 是为 :NULL
		 * 所以设置response.setCharacterEncoding("utf-8");
		 */	
		response.setCharacterEncoding("gbk");
		System.out.println(request.getCharacterEncoding());
		try {
			ajaxResponseBean.setData(objectMapper.writeValueAsString(entity));
			System.out.println(ajaxResponseBean.getData());
			write(response, ajaxResponseBean);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
예제 #10
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;
 }
예제 #11
0
  /**
   * Creates the target URL by checking if the redirect string is a URI template first, expanding it
   * with the given model, and then optionally appending simple type model attributes as query
   * String parameters.
   */
  protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request)
      throws UnsupportedEncodingException {

    // Prepare target URL.
    StringBuilder targetUrl = new StringBuilder();
    if (this.contextRelative && getUrl().startsWith("/")) {
      // Do not apply context path to relative URLs.
      targetUrl.append(request.getContextPath());
    }
    targetUrl.append(getUrl());

    String enc = this.encodingScheme;
    if (enc == null) {
      enc = request.getCharacterEncoding();
    }
    if (enc == null) {
      enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
    }

    if (StringUtils.hasText(targetUrl)) {
      Map<String, String> variables = getCurrentRequestUriVariables(request);
      targetUrl = replaceUriTemplateVariables(targetUrl.toString(), model, variables, enc);
    }

    if (this.exposeModelAttributes) {
      appendQueryProperties(targetUrl, model, enc);
    }

    return targetUrl.toString();
  }
 /**
  * Determine the encoding for the given request. Can be overridden in subclasses.
  *
  * <p>The default implementation checks the request encoding, falling back to the default encoding
  * specified for this resolver.
  *
  * @param request current HTTP request
  * @return the encoding for the request (never <code>null</code>)
  * @see javax.servlet.ServletRequest#getCharacterEncoding()
  * @see #setDefaultEncoding
  */
 protected String determineEncoding(HttpServletRequest request) {
   String enc = request.getCharacterEncoding();
   if (enc == null) {
     enc = getDefaultEncoding();
   }
   return enc;
 }
예제 #13
0
  /**
   * http://example.com:8080/over/there?name=ferret#nose \__/ \______________/\_________/
   * \_________/ \__/ | | | | | scheme authority path query fragment
   *
   * <p>OR
   *
   * <p>[scheme:][//authority][path][?query][#fragment]
   *
   * @param request
   * @param response
   * @return
   * @throws ServletException
   * @throws IOException
   */
  Action dispatch(HttpServletRequest request) throws ServletException, IOException {
    String path = request.getRequestURI();
    String ctxP = request.getContextPath();

    if (ctxP.length() > 0) {
      path = path.substring(ctxP.length());
    }

    // set default character encoding to "utf-8" if encoding is not set:
    if (request.getCharacterEncoding() == null) {
      request.setCharacterEncoding("UTF-8");
    }

    String reqMethod = request.getMethod().toUpperCase();
    ActionConfig actionConfig = null;
    String[] urlArgs = null;

    /* 寻找处理请求的程序(方法) */
    for (UrlMatcher m : this.matchersMap.get(reqMethod)) {
      urlArgs = m.getUrlParameters(path);
      if (urlArgs != null) {
        actionConfig = urlMapMap.get(reqMethod).get(m);
        break;
      }
    }

    if (actionConfig != null) {
      return new Action(actionConfig, urlArgs, path);
    }

    return null;
  }
  @Test
  public void withIncompleteInitialization() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    given(request.getCharacterEncoding()).willReturn(null);
    given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
    given(
            request.getAttribute(
                CharacterEncodingFilter.class.getName()
                    + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX))
        .willReturn(null);

    MockHttpServletResponse response = new MockHttpServletResponse();

    FilterChain filterChain = mock(FilterChain.class);

    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding(ENCODING);
    filter.doFilter(request, response, filterChain);

    verify(request).setCharacterEncoding(ENCODING);
    verify(request)
        .setAttribute(
            CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX,
            Boolean.TRUE);
    verify(request)
        .removeAttribute(
            CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
    verify(filterChain).doFilter(request, response);
  }
예제 #15
0
 private Map<String, List<String>> getQueryParamMap() {
   if (queryParamLocal != null) return queryParamLocal;
   //
   HttpServletRequest httpRequest = getRequest();
   String queryString = httpRequest.getQueryString();
   if (StringUtils.isBlank(queryString)) return null;
   //
   queryParamLocal = new HashMap<String, List<String>>();
   String[] params = queryString.split("&");
   for (String pData : params) {
     String oriData = null;
     String encoding = httpRequest.getCharacterEncoding();
     try {
       oriData = URLDecoder.decode(pData, encoding);
     } catch (Exception e) {
       Hasor.logWarn("use ‘%s’ decode ‘%s’ error.", encoding, pData);
       continue;
     }
     String[] kv = oriData.split("=");
     if (kv.length < 2) continue;
     String k = kv[0].trim().toUpperCase();
     String v = kv[1];
     //
     List<String> pArray = queryParamLocal.get(k);
     pArray = pArray == null ? new ArrayList<String>() : pArray;
     if (pArray.contains(v) == false) pArray.add(v);
     queryParamLocal.put(k, pArray);
   }
   return queryParamLocal;
 }
예제 #16
0
  protected WMSTileFuser(TileLayerDispatcher tld, StorageBroker sb, HttpServletRequest servReq)
      throws GeoWebCacheException {
    this.sb = sb;

    String[] keys = {
      "layers", "format", "srs", "bbox", "width", "height", "transparent", "bgcolor"
    };

    Map<String, String> values =
        ServletUtils.selectedStringsFromMap(
            servReq.getParameterMap(), servReq.getCharacterEncoding(), keys);

    // TODO Parameter filters?

    String layerName = values.get("layers");
    layer = tld.getTileLayer(layerName);

    List<MimeType> ml = layer.getMimeTypes();
    Iterator<MimeType> iter = ml.iterator();
    while (iter.hasNext()) {
      MimeType mt = iter.next();
      if (mt.getInternalName().equalsIgnoreCase("png")) {
        this.srcFormat = (ImageMime) mt;
      }
    }

    gridSubset = layer.getGridSubsetForSRS(SRS.getSRS(values.get("srs")));

    outputFormat = (ImageMime) ImageMime.createFromFormat(values.get("format"));

    reqBounds = new BoundingBox(values.get("bbox"));

    reqWidth = Integer.valueOf(values.get("width"));

    reqHeight = Integer.valueOf(values.get("height"));

    // if(values[6] != null) {
    // this.reqTransparent = Boolean.valueOf(values[6]);
    // }

    // if(values[7] != null) {
    // this.reqBgColor = values[7];
    // }

    fullParameters =
        layer.getModifiableParameters(servReq.getParameterMap(), servReq.getCharacterEncoding());
  }
예제 #17
0
  /**
   * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as
   * was sent in the given {@link HttpServletRequest}.
   *
   * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard
   *     POST request
   * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent
   *     via the {@link PostMethod}
   */
  private void handleContentPost(
      PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
      throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (; ; ) {
      String line = reader.readLine();
      if (line == null) {
        break;
      }
      content.append(line);
    }

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

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

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

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

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace(
        "POST Content Type: {} Encoding: {} Content: {}",
        new Object[] {contentType, encoding, postContent});
    StringRequestEntity entity;
    try {
      entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
  }
예제 #18
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (request.getCharacterEncoding() == null) request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    String strLang = "";
    Translate translate = new Translate();

    Kayttaja kayttaja;
    /*System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");*/
    PrintWriter out = response.getWriter();
    Enumeration<String> enumTest = request.getParameterNames();
    HashMap<String, Object> requestMap = new HashMap<String, Object>();
    while (enumTest.hasMoreElements()) {
      String tmp = enumTest.nextElement().toString();
      requestMap.put(tmp, request.getParameter(tmp));
    }
    JSONObject ret = new JSONObject();
    try {
      kayttaja = new Kayttaja(SecurityContextHolder.getContext().getAuthentication().getName());
      // System.out.println(kayttaja.getKayttajaNimi());
      strLang = requestMap.get("lang").toString();
      String textValue = requestMap.get("textValue").toString();
      int textId = -1;
      if (requestMap.containsKey("textId")) {
        textId = Integer.parseInt(requestMap.get("textId").toString());
      }
      if (strLang == null || strLang == "") strLang = "fi";
      JSONObject t = translate.getUITranslations(strLang);
      Translate transObj = new Translate();
      System.out.println(requestMap);
      if (kayttaja.isSupervisor()) {
        if (textId == -1) {
          String textLabel = requestMap.get("textLabel").toString();
          textId = transObj.createTranslation(textValue, textLabel, strLang);
        }
        if (textId == -1) {
          ret.put("success", false);
          ret.put("msg", t.getString("save_not_success"));
        } else {
          transObj.setTranslationText(textId, textValue, strLang);
          ret.put("success", true);
          ret.put("msg", t.getString("save_success"));
        }
      } else {
        ret.put("success", false);
        ret.put("msg", t.getString("insufficient_rights"));
      }
      out.println(ret.toString());
    } catch (Exception e) {
      log.error(org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e));
      out.println("{'success':'false', 'msg': 'Tapahtui odottamaton virhe sovelluksessa.'}");
    }
  }
예제 #19
0
 /**
  * @param request wrapped request
  * @param encoding character encoding to apply to request parameters
  * @throws IllegalArgumentException when the encoding isn't supported
  */
 public DecodedRequest(HttpServletRequest request, String encoding) {
   super(request);
   mEncoding = checkEncoding(encoding);
   String original = request.getCharacterEncoding();
   if (original == null) {
     original = "iso-8859-1";
   }
   mOriginalEncoding = original;
 }
예제 #20
0
  /**
   * Converts this parameter map into a query String. Note that this will flatten nested keys
   * separating them with the . character and URL encode the result
   *
   * @return A query String starting with the ? character
   */
  public String toQueryString() {

    String encoding = request.getCharacterEncoding();
    try {
      return WebUtils.toQueryString(this, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ControllerExecutionException(
          "Unable to convert parameter map [" + this + "] to a query string: " + e.getMessage(), e);
    }
  }
예제 #21
0
 public void preRequest(HttpServletRequest request, HttpServletResponse response) {
   // need to set the encoding of characters manually
   if (request.getCharacterEncoding() == null) {
     try {
       request.setCharacterEncoding("UTF-8");
     } catch (UnsupportedEncodingException e) {
       throw new RuntimeException(e);
     }
   }
 }
예제 #22
0
 String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
   String enc = httpServletRequest.getCharacterEncoding();
   if (enc == null) {
     enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
   }
   try {
     pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
   } catch (UnsupportedEncodingException uee) {
   }
   return pathSegment;
 }
예제 #23
0
 /**
  * If setting character encoding is enabled for this filter, and there isn't already a character
  * encoding on the request, then set the encoding.
  */
 protected void handleCharacterEncoding(HttpServletRequest req, HttpServletResponse resp)
     throws UnsupportedEncodingException {
   if (m_characterEncodingEnabled
       && req.getCharacterEncoding() == null
       && m_characterEncoding != null
       && m_characterEncoding.length() > 0
       && req.getAttribute(ATTR_CHARACTER_ENCODING_DONE) == null) {
     req.setAttribute(ATTR_CHARACTER_ENCODING_DONE, ATTR_CHARACTER_ENCODING_DONE);
     req.setCharacterEncoding(m_characterEncoding);
   }
 }
예제 #24
0
	/**
	 * Determine the encoding for the given request.
	 * Can be overridden in subclasses.
	 * <p>The default implementation checks the request encoding,
	 * falling back to the default encoding specified for this resolver.
	 * @param request current HTTP request
	 * @return the encoding for the request (never <code>null</code>)
	 * @see javax.servlet.ServletRequest#getCharacterEncoding
	 * @see #setDefaultEncoding
	 */
	protected String[] determineEncoding(HttpServletRequest request) {
//		String encoding = request.getCharacterEncoding();
//		if (encoding == null) {
//			encoding = getDefaultEncoding();
//		}
//		return encoding;
		String encoding = request.getCharacterEncoding();
		
		return new String[]{this.getDefaultEncoding(),encoding};
		
	}
예제 #25
0
  private void request(HttpServletRequest request) {
    System.out.println(request.getCharacterEncoding());
    System.out.println(request.getContentType());
    System.out.println(request.getProtocol());

    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
      Object o = e.nextElement();
      System.out.println(o + ":" + request.getHeader((String) o));
    }
  }
예제 #26
0
 private void applyEncoding(HttpServletRequest request, String encoding) {
   try {
     if (!encoding.equals(request.getCharacterEncoding())) {
       // if the encoding is already correctly set and the parameters have been already read
       // do not try to set encoding because it is useless and will cause an error
       request.setCharacterEncoding(encoding);
     }
   } catch (Exception e) {
     LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
   }
 }
예제 #27
0
  public ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response)
      throws ServiceException {
    String layerId = super.getLayersParameter(request);

    String encoding = request.getCharacterEncoding();

    Map<String, String[]> params = request.getParameterMap();
    String strFormat = ServletUtils.stringFromMap(params, encoding, "format");
    String strZoom = ServletUtils.stringFromMap(params, encoding, "zoom");
    String strX = ServletUtils.stringFromMap(params, encoding, "x");
    String strY = ServletUtils.stringFromMap(params, encoding, "y");
    String strCached = ServletUtils.stringFromMap(params, encoding, "cached");
    String strMetaTiled = ServletUtils.stringFromMap(params, encoding, "metatiled");

    long[] gridLoc =
        GMapsConverter.convert(
            Integer.parseInt(strZoom), Integer.parseInt(strX), Integer.parseInt(strY));

    MimeType mimeType = null;
    try {
      if (strFormat == null) {
        strFormat = "image/png";
      }
      mimeType = MimeType.createFromFormat(strFormat);
    } catch (MimeException me) {
      throw new ServiceException("Unable to determine requested format, " + strFormat);
    }

    ConveyorTile ret =
        new ConveyorTile(
            sb,
            layerId,
            gsb.WORLD_EPSG3857.getName(),
            gridLoc,
            mimeType,
            null,
            null,
            request,
            response);

    if (strCached != null && !Boolean.parseBoolean(strCached)) {
      ret.setRequestHandler(ConveyorTile.RequestHandler.SERVICE);

      if (strMetaTiled != null && !Boolean.parseBoolean(strMetaTiled)) {
        ret.setHint("not_cached,not_metatiled");
      } else {
        ret.setHint("not_cached");
      }
    }

    return ret;
  }
예제 #28
0
  private void doTest(
      final Map<String, ?> map,
      final String url,
      final boolean contextRelative,
      final boolean exposeModelAttributes,
      String expectedUrlForEncoding)
      throws Exception {

    class TestRedirectView extends RedirectView {

      public boolean queryPropertiesCalled = false;

      /** Test whether this callback method is called with correct args */
      @Override
      protected Map<String, Object> queryProperties(Map<String, Object> model) {
        // They may not be the same model instance, but they're still equal
        assertTrue("Map and model must be equal.", map.equals(model));
        this.queryPropertiesCalled = true;
        return super.queryProperties(model);
      }
    }

    TestRedirectView rv = new TestRedirectView();
    rv.setUrl(url);
    rv.setContextRelative(contextRelative);
    rv.setExposeModelAttributes(exposeModelAttributes);

    HttpServletRequest request = mock(HttpServletRequest.class, "request");
    if (exposeModelAttributes) {
      given(request.getCharacterEncoding()).willReturn(WebUtils.DEFAULT_CHARACTER_ENCODING);
    }
    if (contextRelative) {
      expectedUrlForEncoding = "/context" + expectedUrlForEncoding;
      given(request.getContextPath()).willReturn("/context");
    }

    given(request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE))
        .willReturn(new FlashMap());

    FlashMapManager flashMapManager = new SessionFlashMapManager();
    given(request.getAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE))
        .willReturn(flashMapManager);

    HttpServletResponse response = mock(HttpServletResponse.class, "response");
    given(response.encodeRedirectURL(expectedUrlForEncoding)).willReturn(expectedUrlForEncoding);
    response.sendRedirect(expectedUrlForEncoding);

    rv.render(map, request, response);
    if (exposeModelAttributes) {
      assertTrue("queryProperties() should have been called.", rv.queryPropertiesCalled);
    }
  }
예제 #29
0
  @Override
  public String execute() throws Exception {

    HttpServletRequest request = ServletActionContext.getRequest();

    System.out.println(request.getCharacterEncoding());

    this.setList(musicPlayerService.searchMusic("E:\\music"));

    System.out.println(this.getList());

    return "success";
  }
 private void processUpload(HttpServletRequest request, String saveDir)
     throws FileUploadException, UnsupportedEncodingException {
   for (FileItem item : parseRequest(request, saveDir)) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("Found item " + item.getFieldName());
     }
     if (item.isFormField()) {
       processNormalFormField(item, request.getCharacterEncoding());
     } else {
       processFileField(item);
     }
   }
 }