yakworks.spring.params.QueryParamsUtil.groovy Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2024 Yak.Works - Licensed under the Apache License, Version 2.0 (the "License")
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*/
package yakworks.spring.params
import java.nio.charset.StandardCharsets
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.util.MultiValueMap
import org.springframework.web.util.UriComponentsBuilder
@CompileStatic
@Slf4j
class QueryParamsUtil {
/**
* Parses name=xyz&size=123 query string into a map
* Uses springs UriComponentsBuilder
* @param queryString the query params string to parse
* @return Map the map version of the parsed string
*/
static Map parseQueryString(String queryString) {
if(!queryString) return [:]
MultiValueMap queryParams = UriComponentsBuilder.fromUriString('?'+queryString).build().getQueryParams()
return toArrayMap(queryParams)
}
// private static Map toSingleValueMap(Map paramsMap) {
// Map svMap = [:] as Map
// //just gets first value
// paramsMap.each { k,v ->
// svMap[k] = v[0]
// }
// return svMap;
// }
// convert to what stock request.getParameterMap would return. decode each value
private static Map toArrayMap(MultiValueMap mvMap) {
Map decodedMap = [:] as Map
//decode each one now
mvMap.each { String k, List v ->
List decodedVals = v ? v.collect{ decode(it) } : []
decodedMap[decode(k)] = decodedVals as String[]
}
return decodedMap
}
static String decode(String s) {
if(!s) return ""
URLDecoder.decode(s, StandardCharsets.UTF_8)
}
static String encode(String s) {
if(!s) return ""
URLEncoder.encode(s, StandardCharsets.UTF_8)
}
}