org.glowroot.local.ui.QueryStrings Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.local.ui;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import org.glowroot.shaded.google.common.base.CaseFormat;
import org.glowroot.shaded.google.common.cache.CacheBuilder;
import org.glowroot.shaded.google.common.cache.CacheLoader;
import org.glowroot.shaded.google.common.cache.LoadingCache;
import org.glowroot.shaded.google.common.collect.Lists;
import org.glowroot.shaded.google.common.collect.Maps;
import org.glowroot.shaded.netty.handler.codec.http.QueryStringDecoder;
import org.glowroot.common.Reflections;
import static org.glowroot.shaded.google.common.base.Preconditions.checkNotNull;
class QueryStrings {
private static LoadingCache, Map> settersCache =
CacheBuilder.newBuilder().build(new CacheLoader, Map>() {
@Override
public Map load(Class> key) throws Exception {
return loadSetters(key);
}
});
private QueryStrings() {}
static T decode(String queryString, Class clazz) throws Exception {
Method builderMethod = Reflections.getDeclaredMethod(clazz, "builder");
Object builder = Reflections.invokeStatic(builderMethod);
checkNotNull(builder);
Class> immutableBuilderClass = builder.getClass();
Map setters = settersCache.getUnchecked(immutableBuilderClass);
QueryStringDecoder decoder = new QueryStringDecoder('?' + queryString);
for (Entry> entry : decoder.parameters().entrySet()) {
String key = entry.getKey();
key = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
// special rule for "-mbean" so that it will convert to "...MBean"
key = key.replace("Mbean", "MBean");
Method setter = setters.get(key);
checkNotNull(setter, "Unexpected attribute: %s", key);
Type valueType = setter.getGenericParameterTypes()[0];
Object value;
if (valueType instanceof ParameterizedType) {
// only generic iterable supported
valueType = ((ParameterizedType) valueType).getActualTypeArguments()[0];
List