下面列出了com.fasterxml.jackson.annotation.JsonAnySetter#com.google.common.base.CaseFormat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static MutableCapabilities getDeviceProperties(MutableCapabilities desiredCapabilities) {
if (!ConfigurationUtils.isDevice(desiredCapabilities))
return desiredCapabilities;
DeviceResult device = null;
try {
device = getHttpClient().deviceInfo(desiredCapabilities.getCapability("deviceName").toString(), false);
} catch (HttpClientException e) {
e.printStackTrace();
}
for (DeviceParameter parameter : DeviceParameter.values()) {
String paramValue = device.getResponseValue(parameter);
String capName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, parameter.toString().toLowerCase());
if (!StringUtils.isEmpty(paramValue))
desiredCapabilities.setCapability(capName, paramValue);
}
return desiredCapabilities;
}
/**
* Gets the bind mapper name.
*
* @param context the context
* @param typeName the type name
* @return the bind mapper name
*/
public String getBindMapperName(BindTypeContext context, TypeName typeName) {
Converter<String, String> format = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
TypeName bindMapperName=TypeUtility.mergeTypeNameWithSuffix(typeName,BindTypeBuilder.SUFFIX);
String simpleName=format.convert(TypeUtility.simpleName(bindMapperName));
if (!alreadyGeneratedMethods.contains(simpleName))
{
alreadyGeneratedMethods.add(simpleName);
if (bindMapperName.equals(beanTypeName))
{
context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)
.addJavadoc("$T", bindMapperName)
.initializer("this")
.build());
} else {
context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)
.addJavadoc("$T", bindMapperName)
.initializer("$T.mapperFor($T.class)", BinderUtils.class, typeName)
.build());
}
}
return simpleName;
}
/**
* 返回枚举类的说明
*
* @param clazz 枚举类类对象
* @return
*/
static String getInfo(Class<? extends BaseEnum> clazz) {
BaseEnum[] enums = clazz.getEnumConstants();
LinkedHashMap<String, JSONObject> json = new LinkedHashMap<>(enums.length);
for (BaseEnum e : enums) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", new DeletedQuotationAware(e.getValue()));
jsonObject.put("desc", new DeletedQuotationAware(e.getDesc()));
json.put(e.toString(), jsonObject);
}
String enumJson = JSON.toJSONString(json, true);
enumJson = enumJson.replaceAll("\"", "");
enumJson= enumJson.replaceAll("\t"," ");
enumJson = enumJson.replaceAll("\n","<br>");
String prefix = " <br> export const <br> " + CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, clazz.getSimpleName() + " = <br> ");
return prefix + "" + enumJson + " <br>";
}
@SuppressWarnings("unchecked")
@JsonAnySetter
public Object set(String name, Object value) {
if (value instanceof Map) {
value = new DynaBean((Map<String, Object>) value);
} else if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
List<DynaBean> list = new ArrayList<DynaBean>();
if (! collection.isEmpty() && collection.iterator().next() instanceof Map) {
for (Object val : collection) {
list.add(new DynaBean((Map<String, Object>)val));
}
value = list;
}
}
return super.put(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name), value);
}
public void filterOrderItems(List<OrderItem> orderItems) {
if (CollectionUtils.isEmpty(orderItems)) {
return;
}
// 如果集合不为空,则按照PropertyColumnUtil映射
if (MapUtils.isNotEmpty(map)) {
orderItems.forEach(item -> {
item.setColumn(this.getMappingColumn(item.getColumn()));
});
} else if (underLineMode) {
// 如果开启下划线模式,自动转换成下划线
orderItems.forEach(item -> {
String column = item.getColumn();
if (StringUtils.isNotBlank(column)) {
// 驼峰转换成下划线
item.setColumn(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, column));
}
});
}
}
@ParameterizedTest
@MethodSource("data")
void overridesPreviousNaming(
final String source,
final CaseFormat targetFormat,
final String target) {
final MockTracer tracer = new MockTracer();
final Tracer unit = new ProxyTracer(tracer)
.with(Naming.DEFAULT)
.with(new Rename(targetFormat));
unit.buildSpan(source)
.start().finish();
final MockSpan span = getOnlyElement(tracer.finishedSpans());
assertEquals(target, span.operationName());
}
@ParameterizedTest
@MethodSource("data")
void renamesOperationOnSet(
final String source,
final CaseFormat targetFormat,
final String target) {
final MockTracer tracer = new MockTracer();
final Tracer unit = new ProxyTracer(tracer)
.with(new Rename(targetFormat));
unit.buildSpan("test")
.start()
.setOperationName(source)
.finish();
final MockSpan span = getOnlyElement(tracer.finishedSpans());
assertEquals(target, span.operationName());
}
private String buildWhere(final String tableName, final Collection<String> tableFields, final Condition condition) {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append(" WHERE 1=1");
if (null != condition.getFields() && !condition.getFields().isEmpty()) {
for (Map.Entry<String, Object> entry : condition.getFields().entrySet()) {
String lowerUnderscore = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
if (null != entry.getValue() && tableFields.contains(lowerUnderscore)) {
sqlBuilder.append(" AND ").append(lowerUnderscore).append("=?");
}
}
}
if (null != condition.getStartTime()) {
sqlBuilder.append(" AND ").append(getTableTimeField(tableName)).append(">=?");
}
if (null != condition.getEndTime()) {
sqlBuilder.append(" AND ").append(getTableTimeField(tableName)).append("<=?");
}
return sqlBuilder.toString();
}
private void setBindValue(final PreparedStatement preparedStatement, final Collection<String> tableFields, final Condition condition) throws SQLException {
int index = 1;
if (null != condition.getFields() && !condition.getFields().isEmpty()) {
for (Map.Entry<String, Object> entry : condition.getFields().entrySet()) {
String lowerUnderscore = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
if (null != entry.getValue() && tableFields.contains(lowerUnderscore)) {
preparedStatement.setString(index++, String.valueOf(entry.getValue()));
}
}
}
if (null != condition.getStartTime()) {
preparedStatement.setTimestamp(index++, new Timestamp(condition.getStartTime().getTime()));
}
if (null != condition.getEndTime()) {
preparedStatement.setTimestamp(index, new Timestamp(condition.getEndTime().getTime()));
}
}
/**
* 判断str是哪种命名格式的,不能保证一定判断对,慎用
*
* @param str
* @return
*/
public static CaseFormat determineFormat(String str) {
Preconditions.checkNotNull(str);
String[] split = str.split("_");
List<String> splitedStrings = Arrays.stream(split).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
if (splitedStrings.size() == 1) {
//camel
if (CharUtils.isAsciiAlphaUpper(splitedStrings.get(0).charAt(0))) {
return CaseFormat.UPPER_CAMEL;
} else {
return CaseFormat.LOWER_CAMEL;
}
} else if (splitedStrings.size() > 1) {
//underscore
if (CharUtils.isAsciiAlphaUpper(splitedStrings.get(0).charAt(0))) {
return CaseFormat.UPPER_UNDERSCORE;
} else {
return CaseFormat.LOWER_UNDERSCORE;
}
}else{
//判断不出那个
return CaseFormat.LOWER_CAMEL;
}
}
@Override
public String detect(String identifier) {
if (identifier.length() <= lengthsOfPrefixAndSuffix) {
return NOT_DETECTED;
}
boolean prefixMatches = prefix.isEmpty() ||
(identifier.startsWith(prefix) && Ascii.isUpperCase(identifier.charAt(prefix.length())));
boolean suffixMatches = suffix.isEmpty() || identifier.endsWith(suffix);
if (prefixMatches && suffixMatches) {
String detected = identifier.substring(prefix.length(), identifier.length() - suffix.length());
return prefix.isEmpty()
? detected
: CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, detected);
}
return NOT_DETECTED;
}
@Override
public List<Table> getTableByDataSource(McgDataSource mcgDataSource) {
List<Table> result = null;
McgBizAdapter mcgBizAdapter = new FlowDataAdapterImpl(mcgDataSource);
try {
result = mcgBizAdapter.getTablesByDataSource(mcgDataSource.getDbName());
} catch (SQLException e) {
logger.error("获取所有表名出错,异常信息:{}", e.getMessage());
}
if(result != null && result.size() > 0) {
for(Table table : result) {
String entityName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, table.getTableName());
table.setDaoName(entityName + "Dao");
table.setEntityName(entityName);
table.setXmlName(entityName + "Mapper");
}
}
return result;
}
@Override
public RelationshipMetadata<R> createRelationMetadata(AnnotatedElement<?> annotatedElement, Map<Class<?>, TypeMetadata> metadataByType) {
Relation relationAnnotation;
boolean batchable;
if (annotatedElement instanceof PropertyMethod) {
relationAnnotation = annotatedElement.getAnnotation(Relation.class);
batchable = true;
} else if (annotatedElement instanceof AnnotatedType) {
AnnotatedType annotatedType = (AnnotatedType) annotatedElement;
relationAnnotation = annotatedType.getAnnotation(Relation.class);
batchable = annotatedType.getAnnotatedElement().isAnnotation() || isBatchable(annotatedElement);
} else {
throw new XOException("Annotated element is not supported: " + annotatedElement);
}
String name = null;
if (relationAnnotation != null) {
String value = relationAnnotation.value();
if (!Relation.DEFAULT_VALUE.equals(value)) {
name = value;
}
}
if (name == null) {
name = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, annotatedElement.getName());
}
return new RelationshipMetadata<>(createRelationshipType(name), batchable);
}
private List<String> resolvePossibleNames(Descriptor descriptor) {
return Optional.ofNullable(descriptor.getClass().getAnnotation(Symbol.class))
.map(s -> Arrays.asList(s.value()))
.orElseGet(() -> {
/* TODO: extract Descriptor parameter type such that DescriptorImpl extends Descriptor<XX> returns XX.
* Then, if `baseClass == fooXX` we get natural name `foo`.
*/
return singletonList(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, descriptor.getKlass().toJavaClass().getSimpleName()));
});
}
/**
* Compute the name of the class prefix from the package name. This converts
* the dot-separated package name to camel case, so foo.bar becomes fooBar.
*
* @param packageName the @provide package name
* @return the converted class prefix
*/
private String getClassPrefixFromDottedName(String packageName) {
// CaseFormat doesn't have a format for names separated by dots, so we transform
// the dots into dashes. Then we can use the regular CaseFormat transformation
// to camel case instead of having to write our own.
String packageNameWithDashes = packageName.replace('.', '-');
return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, packageNameWithDashes);
}
private static String serverMetricName(String property, int status, String result) {
final String name = "armeriaServerHelloService" +
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, property);
return MetricRegistry.name(name,
"hostnamePattern:*", "httpStatus:" + status,
"method:hello", result, "service:" + Iface.class.getName());
}
private String getMessage(Throwable error, String suffix, String defaultMessage) {
if (this.constants == null) {
return defaultMessage;
}
try {
String className = error.getClass().getSimpleName();
if (error instanceof CommandException) {
className = ((CommandException) error).getCauseSimpleClassName();
}
String methodName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, className) + suffix;
return this.constants.getString(methodName);
} catch (MissingResourceException exc) {
return defaultMessage;
}
}
@Override
public void collectIds(@NotNull ServiceParameterCollectorParameter.Id parameter) {
for(PhpClass phpClass: PhpIndex.getInstance(parameter.getProject()).getAllSubclasses(ShopwareFQDN.PLUGIN_BOOTSTRAP)) {
String formattedPluginName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, phpClass.getName());
parameter.add(new ContainerParameter(formattedPluginName + ".plugin_dir", getRelativeToProjectPath(phpClass), true));
parameter.add(new ContainerParameter(formattedPluginName + ".plugin_name", phpClass.getName(), true));
}
parameter.addAll(DEFAULTS);
}
private Builder(EnumSerialization enumSerialization, CaseFormat fromFieldNameFormat,
CaseFormat toFieldNameFormat) {
this.serializedNameExtensions = new HashSet<Extension<FieldOptions, String>>();
this.serializedEnumValueExtensions = new HashSet<Extension<EnumValueOptions, String>>();
setEnumSerialization(enumSerialization);
setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat);
}
/** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused") @Deprecated
private static Function<String, String> convertCaseOld(final CaseFormat src, final CaseFormat target) {
// TODO PERSISTENCE WORKAROUND
return new Function<String, String>() {
@Override
public String apply(String input) {
return src.to(target, input);
}
};
}
private static <T> Yaml getYaml(Class<T> tClass) {
Constructor c = new Constructor(tClass);
c.setPropertyUtils(new PropertyUtils() {
@Override
public Property getProperty(Class<?> type, String name) {
if (name.indexOf('-') > -1) {
name = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name);
}
return super.getProperty(type, name);
}
});
return new Yaml(c);
}
private RelationalPathBase<?> getRelationalPathBase(Class<?> queryClass) {
String fieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, queryClass.getSimpleName().substring(1));
Field field = ReflectionUtils.findField(queryClass, fieldName);
if (field == null) {
throw new IllegalArgumentException("Did not find a static field of the same type in " + queryClass);
}
return (RelationalPathBase<?>) ReflectionUtils.getField(field, null);
}
@Override
public String toString() {
return mSourceLocation.toString() // needs short string.
+ " "
+ CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, mSeverity.toString())
+ ":\n\t"
+ mLog;
}
private SortedMap<String, Object> resolveAllUnconfiguredAttributesForTarget(
CommandRunnerParams params, BuckQueryEnvironment env, QueryBuildTarget target)
throws QueryException {
Map<String, Object> attributes = getAllUnconfiguredAttributesForTarget(params, env, target);
PatternsMatcher patternsMatcher = new PatternsMatcher(outputAttributes());
SortedMap<String, Object> convertedAttributes = new TreeMap<>();
if (!patternsMatcher.isMatchesNone()) {
for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
String snakeCaseKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, attributeName);
if (!patternsMatcher.matches(snakeCaseKey)) {
continue;
}
Object jsonObject = attribute.getValue();
if (!(jsonObject instanceof ListWithSelects)) {
convertedAttributes.put(snakeCaseKey, jsonObject);
continue;
}
convertedAttributes.put(
snakeCaseKey, resolveUnconfiguredAttribute((ListWithSelects) jsonObject));
}
}
if (patternsMatcher.matches(InternalTargetAttributeNames.DIRECT_DEPENDENCIES)) {
convertedAttributes.put(
InternalTargetAttributeNames.DIRECT_DEPENDENCIES,
env.getNode(target).getParseDeps().stream()
.map(Object::toString)
.collect(ImmutableList.toImmutableList()));
}
return convertedAttributes;
}
public static String executeQueryToJson(Database dbSource, String sql) throws GroundException {
Logger.debug("executeQueryToJson: {}", sql);
try {
Connection con = dbSource.getConnection();
Statement stmt = con.createStatement();
final ResultSet resultSet = stmt.executeQuery(sql);
final long columnCount = resultSet.getMetaData().getColumnCount();
final List<Map<String, Object>> objList = new ArrayList<>();
while (resultSet.next()) {
final Map<String, Object> rowData = new HashMap<>();
for (int column = 1; column <= columnCount; column++) {
String key = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, resultSet.getMetaData().getColumnLabel(column));
rowData.put(key, resultSet.getObject(column));
}
objList.add(rowData);
}
stmt.close();
con.close();
return GroundUtils.listToJson(objList);
} catch (SQLException e) {
Logger.error("ERROR: executeQueryToJson SQL : {} Message: {} Trace: {}", sql, e.getMessage(), e.getStackTrace());
throw new GroundException(e);
}
}
@Override
public Set<QueryBuildTarget> eval(
QueryEvaluator<QueryBuildTarget> evaluator,
QueryEnvironment<QueryBuildTarget> env,
ImmutableList<Argument<QueryBuildTarget>> args)
throws QueryException {
QueryExpression<QueryBuildTarget> argument = args.get(args.size() - 1).getExpression();
String attr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, args.get(0).getWord());
String attrValue = args.get(1).getWord();
Pattern compiledPattern;
try {
compiledPattern = Pattern.compile(attrValue);
} catch (IllegalArgumentException e) {
throw new QueryException(
String.format("Illegal pattern regexp '%s': %s", attrValue, e.getMessage()));
}
// filterAttributeContents() below will traverse the entire type hierarchy of each attr (see the
// various type coercers). Collection types are (1) very common (2) expensive to convert to
// string and (3) we shouldn't apply the filter to the stringified form, and so we have a fast
// path to ignore them.
Predicate<Object> predicate =
input ->
!(input instanceof Collection || input instanceof Map)
&& compiledPattern.matcher(input.toString()).find();
ImmutableSet.Builder<QueryBuildTarget> result = new ImmutableSet.Builder<>();
Set<QueryBuildTarget> targets = evaluator.eval(argument, env);
for (QueryBuildTarget target : targets) {
Set<Object> matchingObjects = env.filterAttributeContents(target, attr, predicate);
if (!matchingObjects.isEmpty()) {
result.add(target);
}
}
return result.build();
}
@Override
public void run() {
final File targetDir = new File(outputFolder);
LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
List<SupportingFile> supportingFiles =
ImmutableList
.of(new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator)
.join("src/main/java", asPath(targetPackage)), mainClass
.concat(".java")), new SupportingFile("README.mustache",
"", "README.md"), new SupportingFile("api.template",
"src/main/resources" + File.separator + name,
"api.mustache"), new SupportingFile("model.template",
"src/main/resources" + File.separator + name,
"model.mustache"), new SupportingFile("services.mustache",
"src/main/resources/META-INF/services",
"io.swagger.codegen.CodegenConfig"));
String swaggerVersion = Version.readVersionFromResources();
Map<String, Object> data =
new ImmutableMap.Builder<String, Object>().put("generatorPackage", targetPackage)
.put("generatorClass", mainClass).put("name", name)
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
.put("swaggerCodegenVersion", swaggerVersion).build();
with(supportingFiles).convert(processFiles(targetDir, data));
}
@Test
public void testConvertKeyToLowerHyphen() throws Exception {
ConfigKey<String> key = ConfigKeys.newStringConfigKey("privateKeyFile", "my descr", "my default val");
ConfigKey<String> key2 = ConfigKeys.convert(key, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_HYPHEN);
assertEquals(key2.getName(), "private-key-file");
assertEquals(key2.getType(), String.class);
assertEquals(key2.getDescription(), "my descr");
assertEquals(key2.getDefaultValue(), "my default val");
}
private String getName( Class<?> klass )
{
if ( AnnotationUtils.isAnnotationPresent( klass, JacksonXmlRootElement.class ) )
{
JacksonXmlRootElement rootElement = AnnotationUtils.getAnnotation( klass, JacksonXmlRootElement.class );
if ( !StringUtils.isEmpty( rootElement.localName() ) )
{
return rootElement.localName();
}
}
return CaseFormat.UPPER_CAMEL.to( CaseFormat.LOWER_CAMEL, klass.getSimpleName() );
}
private static void showAlert(AlertType error, String headerText, String contentText, Window owner) {
Platform.runLater(() -> {
Alert alert = new Alert(error);
alert.initOwner(owner);
alert.setTitle(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, alert.getAlertType().name()));
alert.setHeaderText(headerText);
alert.getDialogPane().setContent(getTextNodeContent(contentText));
decorateWithCss(alert);
alert.showAndWait();
});
}