下面列出了怎么用org.springframework.util.LinkedCaseInsensitiveMap的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testCaseInsensitiveResultsMap() throws Exception {
given(this.callableStatement.execute()).willReturn(false);
given(this.callableStatement.getUpdateCount()).willReturn(-1);
given(this.callableStatement.getObject(1)).willReturn("X");
assertTrue("default should have been NOT case insensitive",
!this.template.isResultsMapCaseInsensitive());
this.template.setResultsMapCaseInsensitive(true);
assertTrue("now it should have been set to case insensitive",
this.template.isResultsMapCaseInsensitive());
Map<String, Object> out = this.template.call(
conn -> conn.prepareCall("my query"), Collections.singletonList(new SqlOutParameter("a", 12)));
assertThat(out, instanceOf(LinkedCaseInsensitiveMap.class));
assertNotNull("we should have gotten the result with upper case", out.get("A"));
assertNotNull("we should have gotten the result with lower case", out.get("a"));
verify(this.callableStatement).close();
verify(this.connection).close();
}
@Test
public void testCaseInsensitiveResultsMap() throws Exception {
given(this.callableStatement.execute()).willReturn(false);
given(this.callableStatement.getUpdateCount()).willReturn(-1);
given(this.callableStatement.getObject(1)).willReturn("X");
assertTrue("default should have been NOT case insensitive",
!this.template.isResultsMapCaseInsensitive());
this.template.setResultsMapCaseInsensitive(true);
assertTrue("now it should have been set to case insensitive",
this.template.isResultsMapCaseInsensitive());
Map<String, Object> out = this.template.call(
conn -> conn.prepareCall("my query"), Collections.singletonList(new SqlOutParameter("a", 12)));
assertThat(out, instanceOf(LinkedCaseInsensitiveMap.class));
assertNotNull("we should have gotten the result with upper case", out.get("A"));
assertNotNull("we should have gotten the result with lower case", out.get("a"));
verify(this.callableStatement).close();
verify(this.connection).close();
}
/**
* Private constructor that can create read-only {@code HttpHeader} instances.
*/
private HttpHeaders(Map<String, List<String>> headers, boolean readOnly) {
Assert.notNull(headers, "'headers' must not be null");
if (readOnly) {
Map<String, List<String>> map =
new LinkedCaseInsensitiveMap<List<String>>(headers.size(), Locale.ENGLISH);
for (Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = Collections.unmodifiableList(entry.getValue());
map.put(entry.getKey(), values);
}
this.headers = Collections.unmodifiableMap(map);
}
else {
this.headers = headers;
}
}
/**
* Private constructor that can create read-only {@code HttpHeader} instances.
*/
private HttpHeaders(Map<String, List<String>> headers, boolean readOnly) {
Assert.notNull(headers, "'headers' must not be null");
if (readOnly) {
Map<String, List<String>> map =
new LinkedCaseInsensitiveMap<List<String>>(headers.size(), Locale.ENGLISH);
for (Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = Collections.unmodifiableList(entry.getValue());
map.put(entry.getKey(), values);
}
this.headers = Collections.unmodifiableMap(map);
}
else {
this.headers = headers;
}
}
@Nullable
/* for testing */ static LinkedCaseInsensitiveMap<String> splitIntoCaseInsensitiveMap(
String[] pairs) {
if (ObjectUtils.isEmpty(pairs)) {
return null;
}
LinkedCaseInsensitiveMap<String> result = new LinkedCaseInsensitiveMap<>();
for (String element : pairs) {
String[] splittedElement = StringUtils.split(element, "=");
if (splittedElement == null) {
continue;
}
result.put(splittedElement[0].trim(), splittedElement[1].trim());
}
return result;
}
@SuppressWarnings("unchecked")
@Path("/storedproc")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String callStoredProcedure(@QueryParam("numA") int numA, @QueryParam("numB") int numB) {
Map<String, Object> args = new HashMap<>();
args.put("num1", numA);
args.put("num2", numB);
Map<String, List<LinkedCaseInsensitiveMap>> results = producerTemplate
.requestBodyAndHeaders("sql-stored:ADD_NUMS(INTEGER ${headers.num1},INTEGER ${headers.num2})", null, args,
Map.class);
return results.get("#result-set-1").get(0).get("PUBLIC.ADD_NUMS(?1, ?2)").toString();
}
private static Map<String, String> initParameters(Extension extension) {
List<Extension.Parameter> parameters = extension.getParameters();
Map<String, String> result = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ENGLISH);
for (Extension.Parameter parameter : parameters) {
result.put(parameter.getName(), parameter.getValue());
}
return result;
}
/**
* Create a WebSocketExtension with the given name and parameters.
* @param name the name of the extension
* @param parameters the parameters
*/
public WebSocketExtension(String name, @Nullable Map<String, String> parameters) {
Assert.hasLength(name, "Extension name must not be empty");
this.name = name;
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ENGLISH);
map.putAll(parameters);
this.parameters = Collections.unmodifiableMap(map);
}
else {
this.parameters = Collections.emptyMap();
}
}
private static Map<String, List<String>> initHeaders(HttpServletRequest request) {
Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<>(Locale.ENGLISH);
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!FORWARDED_HEADER_NAMES.contains(name)) {
headers.put(name, Collections.list(request.getHeaders(name)));
}
}
return headers;
}
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
MediaType contentType = headers.getContentType();
if (contentType == null) {
String requestContentType = request.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String encoding = request.getCharacterEncoding();
if (StringUtils.hasLength(encoding)) {
Charset charset = Charset.forName(encoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charset.toString());
headers.setContentType(
new MediaType(contentType.getType(), contentType.getSubtype(),
params));
}
}
if (headers.getContentLength() == -1) {
int contentLength = request.getContentLength();
if (contentLength != -1) {
headers.setContentLength(contentLength);
}
}
return headers;
}
@Parameterized.Parameters(name = "headers [{0}]")
public static Object[][] arguments() {
return new Object[][] {
{CollectionUtils.toMultiValueMap(
new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH))},
{new NettyHeadersAdapter(new DefaultHttpHeaders())},
{new TomcatHeadersAdapter(new MimeHeaders())},
{new UndertowHeadersAdapter(new HeaderMap())},
{new JettyHeadersAdapter(new HttpFields())}
};
}
private static Map<String, String> initParameters(Extension extension) {
List<Extension.Parameter> parameters = extension.getParameters();
Map<String, String> result = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ENGLISH);
for (Extension.Parameter parameter : parameters) {
result.put(parameter.getName(), parameter.getValue());
}
return result;
}
/**
* Create a WebSocketExtension with the given name and parameters.
* @param name the name of the extension
* @param parameters the parameters
*/
public WebSocketExtension(String name, @Nullable Map<String, String> parameters) {
Assert.hasLength(name, "Extension name must not be empty");
this.name = name;
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ENGLISH);
map.putAll(parameters);
this.parameters = Collections.unmodifiableMap(map);
}
else {
this.parameters = Collections.emptyMap();
}
}
private static Map<String, List<String>> initHeaders(HttpServletRequest request) {
Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<>(Locale.ENGLISH);
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!FORWARDED_HEADER_NAMES.contains(name)) {
headers.put(name, Collections.list(request.getHeaders(name)));
}
}
return headers;
}
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
MediaType contentType = headers.getContentType();
if (contentType == null) {
String requestContentType = request.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String encoding = request.getCharacterEncoding();
if (StringUtils.hasLength(encoding)) {
Charset charset = Charset.forName(encoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charset.toString());
headers.setContentType(
new MediaType(contentType.getType(), contentType.getSubtype(),
params));
}
}
if (headers.getContentLength() == -1) {
int contentLength = request.getContentLength();
if (contentLength != -1) {
headers.setContentLength(contentLength);
}
}
return headers;
}
@Parameterized.Parameters(name = "headers [{0}]")
public static Object[][] arguments() {
return new Object[][] {
{CollectionUtils.toMultiValueMap(
new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH))},
{new NettyHeadersAdapter(new DefaultHttpHeaders())},
{new TomcatHeadersAdapter(new MimeHeaders())},
{new UndertowHeadersAdapter(new HeaderMap())},
{new JettyHeadersAdapter(new HttpFields())}
};
}
/***
* 转换菜单的关系,变为树
*
* @param projectControllerMenuMap
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
private static <M extends IMenu<M>> List<M> genControllerMenuRelations(Class<M> menuClass,
List<M> allControllerMenus) throws IllegalArgumentException, IllegalAccessException {
Map<String, M> simpleNameMap = new LinkedCaseInsensitiveMap<M>(allControllerMenus.size());
CollectionUtil.toMap(simpleNameMap, allControllerMenus, M::getControllerName);
List<String> simpleControllerNames = new ArrayList<String>(simpleNameMap.keySet());
for (String simpleControllerName : simpleControllerNames) {
String currentMenuName = simpleControllerName;
int lastIdx = currentMenuName.lastIndexOf(StringUtil.UNDERLINE);
while (lastIdx > 0) {
M currentMenu = simpleNameMap.get(currentMenuName);
String menuParentControllerName = currentMenuName.substring(0, lastIdx);
M menuParent = simpleNameMap.get(menuParentControllerName);
if (menuParent == null) {
String menuName = StringUtil.trimLeftFormRightTo(menuParentControllerName, StringUtil.UNDERLINE);
MenuType menuType = getMenuTypeByControllerName(menuParentControllerName, true);
menuParent = IMenu.createMenu(menuClass, menuParentControllerName, null, null, menuName, null, menuType, VisitCheckType.NONE);
simpleNameMap.put(menuParentControllerName, menuParent);
}
menuParent.addChild(currentMenu);
currentMenuName = menuParentControllerName;
lastIdx = currentMenuName.lastIndexOf(StringUtil.UNDERLINE);
}
}
ArrayList<M> result = new ArrayList<M>();
for (M m : allControllerMenus) {
if (m.getParent() == null) {
result.add(m);
}
}
return result;
}
private static Map<String, List<String>> initHeaders(HttpServletRequest request) {
Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<List<String>>(Locale.ENGLISH);
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!FORWARDED_HEADER_NAMES.contains(name)) {
headers.put(name, Collections.list(request.getHeaders(name)));
}
}
return headers;
}
@Test
public void testCaseInsensitiveResultsMap() throws Exception {
given(this.callableStatement.execute()).willReturn(false);
given(this.callableStatement.getUpdateCount()).willReturn(-1);
given(this.callableStatement.getObject(1)).willReturn("X");
assertTrue("default should have been NOT case insensitive",
!this.template.isResultsMapCaseInsensitive());
this.template.setResultsMapCaseInsensitive(true);
assertTrue("now it should have been set to case insensitive",
this.template.isResultsMapCaseInsensitive());
List<SqlParameter> params = new ArrayList<SqlParameter>();
params.add(new SqlOutParameter("a", 12));
Map<String, Object> out = this.template.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection conn)
throws SQLException {
return conn.prepareCall("my query");
}
}, params);
assertThat(out, instanceOf(LinkedCaseInsensitiveMap.class));
assertNotNull("we should have gotten the result with upper case", out.get("A"));
assertNotNull("we should have gotten the result with lower case", out.get("a"));
verify(this.callableStatement).close();
verify(this.connection).close();
}
private static Map<String, String> initParameters(Extension extension) {
List<Extension.Parameter> parameters = extension.getParameters();
Map<String, String> result = new LinkedCaseInsensitiveMap<String>(parameters.size(), Locale.ENGLISH);
for (Extension.Parameter parameter : parameters) {
result.put(parameter.getName(), parameter.getValue());
}
return result;
}
/**
* Create a WebSocketExtension with the given name and parameters.
* @param name the name of the extension
* @param parameters the parameters
*/
public WebSocketExtension(String name, Map<String, String> parameters) {
Assert.hasLength(name, "extension name must not be empty");
this.name = name;
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> m = new LinkedCaseInsensitiveMap<String>(parameters.size(), Locale.ENGLISH);
m.putAll(parameters);
this.parameters = Collections.unmodifiableMap(m);
}
else {
this.parameters = Collections.emptyMap();
}
}
static Forwarded parse(String value) {
String[] pairs = StringUtils.tokenizeToStringArray(value, ";");
LinkedCaseInsensitiveMap<String> result = splitIntoCaseInsensitiveMap(pairs);
if (result == null) {
return null;
}
Forwarded forwarded = new Forwarded(result);
return forwarded;
}
/**
* Create a Map instance to be used as results map.
* <p>If "isResultsMapCaseInsensitive" has been set to true,
* a linked case-insensitive Map will be created.
* @return the results Map instance
* @see #setResultsMapCaseInsensitive
*/
protected Map<String, Object> createResultsMap() {
if (isResultsMapCaseInsensitive()) {
return new LinkedCaseInsensitiveMap<Object>();
}
else {
return new LinkedHashMap<String, Object>();
}
}
@Test
public void testCaseInsensitiveResultsMap() throws Exception {
given(this.callableStatement.execute()).willReturn(false);
given(this.callableStatement.getUpdateCount()).willReturn(-1);
given(this.callableStatement.getObject(1)).willReturn("X");
assertTrue("default should have been NOT case insensitive",
!this.template.isResultsMapCaseInsensitive());
this.template.setResultsMapCaseInsensitive(true);
assertTrue("now it should have been set to case insensitive",
this.template.isResultsMapCaseInsensitive());
List<SqlParameter> params = new ArrayList<SqlParameter>();
params.add(new SqlOutParameter("a", 12));
Map<String, Object> out = this.template.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection conn)
throws SQLException {
return conn.prepareCall("my query");
}
}, params);
assertThat(out, instanceOf(LinkedCaseInsensitiveMap.class));
assertNotNull("we should have gotten the result with upper case", out.get("A"));
assertNotNull("we should have gotten the result with lower case", out.get("a"));
verify(this.callableStatement).close();
verify(this.connection).close();
}
@Test
public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(1, linkedHashMap.size());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(2, linkedHashMap.get("aBc").intValue());
assertEquals(2, linkedHashMap.get("ABc").intValue());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 3);
linkedHashMap.remove("aBC");
assertEquals(0, linkedHashMap.size());
}
@Override
public HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders();
for (Enumeration<?> names = this.servletRequest.getHeaderNames(); names.hasMoreElements();) {
String headerName = (String) names.nextElement();
for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName);
headerValues.hasMoreElements();) {
String headerValue = (String) headerValues.nextElement();
this.headers.add(headerName, headerValue);
}
}
// HttpServletRequest exposes some headers as properties:
// we should include those if not already present
try {
MediaType contentType = this.headers.getContentType();
if (contentType == null) {
String requestContentType = this.servletRequest.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
this.headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String requestEncoding = this.servletRequest.getCharacterEncoding();
if (StringUtils.hasLength(requestEncoding)) {
Charset charSet = Charset.forName(requestEncoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charSet.toString());
MediaType mediaType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
this.headers.setContentType(mediaType);
}
}
}
catch (InvalidMediaTypeException ex) {
// Ignore: simply not exposing an invalid content type in HttpHeaders...
}
if (this.headers.getContentLength() < 0) {
int requestContentLength = this.servletRequest.getContentLength();
if (requestContentLength != -1) {
this.headers.setContentLength(requestContentLength);
}
}
}
return this.headers;
}
@Test
public void testMapWithTypes() {
Map map = (Map) this.beanFactory.getBean("mapWithTypes");
assertTrue(map instanceof LinkedCaseInsensitiveMap);
assertEquals(this.beanFactory.getBean("testBean"), map.get("bean"));
}
@Override
public HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders();
for (Enumeration<?> names = this.servletRequest.getHeaderNames(); names.hasMoreElements();) {
String headerName = (String) names.nextElement();
for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName);
headerValues.hasMoreElements();) {
String headerValue = (String) headerValues.nextElement();
this.headers.add(headerName, headerValue);
}
}
// HttpServletRequest exposes some headers as properties:
// we should include those if not already present
try {
MediaType contentType = this.headers.getContentType();
if (contentType == null) {
String requestContentType = this.servletRequest.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
this.headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String requestEncoding = this.servletRequest.getCharacterEncoding();
if (StringUtils.hasLength(requestEncoding)) {
Charset charSet = Charset.forName(requestEncoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charSet.toString());
MediaType mediaType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
this.headers.setContentType(mediaType);
}
}
}
catch (InvalidMediaTypeException ex) {
// Ignore: simply not exposing an invalid content type in HttpHeaders...
}
if (this.headers.getContentLength() < 0) {
int requestContentLength = this.servletRequest.getContentLength();
if (requestContentLength != -1) {
this.headers.setContentLength(requestContentLength);
}
}
}
return this.headers;
}