com.google.common.base.CaseFormat Java Examples

The following examples show how to use com.google.common.base.CaseFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JobEventRdbSearch.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #2
Source File: BindTypeContext.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: AbstractNeo4jMetadataFactory.java    From extended-objects with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: CloudUtils.java    From Quantum with MIT License 6 votes vote down vote up
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;
	}
 
Example #5
Source File: BaseEnum.java    From smart-admin with MIT License 6 votes vote down vote up
/**
 * 返回枚举类的说明
 *
 * @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","&nbsp;&nbsp;");
    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>";
}
 
Example #6
Source File: DynaBean.java    From minnal with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: FlowServiceImpl.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: OrderMapping.java    From spring-boot-plus with Apache License 2.0 6 votes vote down vote up
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));
            }
        });
    }
}
 
Example #9
Source File: Naming.java    From immutables with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: CaseFormatUtil.java    From raptor with Apache License 2.0 6 votes vote down vote up
/**
 * 判断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;
    }
}
 
Example #11
Source File: JobEventRdbSearch.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example #12
Source File: RenameTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@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());
}
 
Example #13
Source File: RenameTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@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());
}
 
Example #14
Source File: CodeGenerator.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
public static void genController(String tableName) {
    try {
        freemarker.template.Configuration cfg = getConfiguration();
        Map<String, Object> data = new HashMap<>();
        data.put("date", DATE);
        data.put("author", AUTHOR);
        String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
        data.put("baseRequestMapping", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
        data.put("modelNameUpperCamel", modelNameUpperCamel);
        data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
        data.put("basePackage", ProjectConstant.BASE_PACKAGE);
        data.put("basePackageController", ProjectConstant.CONTROLLER_PACKAGE);
        data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE);
        data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE);

        File file = new File(JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));

        System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
    } catch (Exception e) {
        throw new RuntimeException("生成Controller失败", e);
    }

}
 
Example #15
Source File: GeneratorPlugin.java    From native-samples with Apache License 2.0 5 votes vote down vote up
private void addTasksForSample(Sample sample, Project project) {
    String sampleNameCamelCase = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, sample.getName());
    TaskProvider<SourceCopyTask> sourceCopyTask = project.getTasks().register(sampleNameCamelCase, SourceCopyTask.class, task -> {
        task.getSampleDir().set(sample.getSampleDir());
        sample.getSourceActions().forEach( it -> it.execute(task));
    });
}
 
Example #16
Source File: AdapterNameGenerator.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a name based on the given {@link TypeName}. Names are constants, so will use
 * {@link CaseFormat#UPPER_UNDERSCORE} formatting.
 */
String getName(TypeName typeName) {
  String name = typeToNames.get(typeName);
  if (name != null) {
    return name;
  }
  name = getNameInternal(typeName);
  name = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, name);
  name = adapterNames.getUniqueName(name);
  typeToNames.put(typeName, name);
  return name;
}
 
Example #17
Source File: AbstractGenruleDescription.java    From buck with Apache License 2.0 5 votes vote down vote up
/** @return a {@link String} representing the type of the genrule */
protected String getGenruleType() {
  String base =
      MoreStrings.stripSuffix(getClass().getSimpleName(), "GenruleDescription")
          .orElseThrow(
              () ->
                  new IllegalStateException(
                      "Expected `AbstractGenruleDescription` child class `%s` to end with \"GenruleDescription\""));
  return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, base + "Genrule");
}
 
Example #18
Source File: BindingProcessor.java    From pocketknife with Apache License 2.0 5 votes vote down vote up
private String findSetter(Element element) {
    String field = element.getSimpleName().toString();
    Element parent = element.getEnclosingElement();
    for (Element child : parent.getEnclosedElements()) {
        if (child.getKind() == METHOD && child instanceof ExecutableElement && ((ExecutableElement) child).getParameters().size() == 1 && !(
                (ExecutableElement) child).isVarArgs()) {
            String name = child.getSimpleName().toString();
            if (name.startsWith(SET) && name.substring(SET.length()).equals(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, field))) {
                return name;
            }
        }
    }
    return null;
}
 
Example #19
Source File: SourceFiles.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
private static String factoryPrefix(ProvisionBinding binding) {
  switch (binding.bindingKind()) {
    case INJECTION:
      return "";
    case PROVISION:
      return CaseFormat.LOWER_CAMEL.to(UPPER_CAMEL,
          ((ExecutableElement) binding.bindingElement()).getSimpleName().toString());
    default:
      throw new IllegalArgumentException();
  }
}
 
Example #20
Source File: DataSourceConfiguration.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows(ReflectiveOperationException.class)
private static Map<String, Object> findAllGetterProperties(final Object target) {
    Map<String, Object> result = new LinkedHashMap<>();
    for (Method each : findAllGetterMethods(target.getClass())) {
        String propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, each.getName().substring(GETTER_PREFIX.length()));
        if (GENERAL_CLASS_TYPE.contains(each.getReturnType()) && !SKIPPED_PROPERTY_NAMES.contains(propertyName)) {
            result.put(propertyName, each.invoke(target));
        }
    }
    return result;
}
 
Example #21
Source File: HelpCommand.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void emitCompletionHelp(BlazeRuntime runtime, OutErr outErr) {
  Map<String, BlazeCommand> commandsByName = getSortedCommands(runtime);

  outErr.printOutLn("BAZEL_COMMAND_LIST=\"" + SPACE_JOINER.join(commandsByName.keySet()) + "\"");

  outErr.printOutLn("BAZEL_INFO_KEYS=\"");
  for (String name : InfoCommand.getHardwiredInfoItemNames(runtime.getProductName())) {
    outErr.printOutLn(name);
  }
  outErr.printOutLn("\"");

  Consumer<OptionsParser> startupOptionVisitor =
      parser -> {
        outErr.printOutLn("BAZEL_STARTUP_OPTIONS=\"");
        outErr.printOut(parser.getOptionsCompletion());
        outErr.printOutLn("\"");
      };
  CommandOptionVisitor commandOptionVisitor =
      (commandName, commandAnnotation, parser) -> {
        String varName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, commandName);
        if (!Strings.isNullOrEmpty(commandAnnotation.completion())) {
          outErr.printOutLn(
              "BAZEL_COMMAND_"
                  + varName
                  + "_ARGUMENT=\""
                  + commandAnnotation.completion()
                  + "\"");
        }
        outErr.printOutLn("BAZEL_COMMAND_" + varName + "_FLAGS=\"");
        outErr.printOut(parser.getOptionsCompletion());
        outErr.printOutLn("\"");
      };

  visitAllOptions(runtime, startupOptionVisitor, commandOptionVisitor);
}
 
Example #22
Source File: UserGuiInteractor.java    From kafka-message-tool with MIT License 5 votes vote down vote up
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();
    });
}
 
Example #23
Source File: AnnotationProcessingEvent.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public String getEventName() {
  return String.format(
      "%s.%sFinished",
      getAnnotationProcessorName(),
      CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, getOperation().toString()));
}
 
Example #24
Source File: DefaultSchemaService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() );
}
 
Example #25
Source File: ConfigKeysTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #26
Source File: StandardCssObject.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public StandardCssObject() {
  name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, this.getClass().getSimpleName());
  obsolete = false;
  experimental = false;
  vendors = new HashSet<>();
  links = new ArrayList<>();
}
 
Example #27
Source File: Meta.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@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));
}
 
Example #28
Source File: AbstractBuildRule.java    From buck with Apache License 2.0 5 votes vote down vote up
private String getTypeForClass() {
  Class<?> clazz = getClass();
  if (clazz.isAnonymousClass()) {
    clazz = clazz.getSuperclass();
  }
  return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, clazz.getSimpleName()).intern();
}
 
Example #29
Source File: AttrRegexFilterFunction.java    From buck with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source File: CredentialsDirectiveProcessor.java    From gyro with Apache License 2.0 5 votes vote down vote up
@Override
public void process(RootScope scope, DirectiveNode node) {
    validateArguments(node, 1, 2);

    String type = getArgument(scope, node, String.class, 0);
    String name = Optional.ofNullable(getArgument(scope, node, String.class, 1)).orElse("default");
    Scope bodyScope = evaluateBody(scope, node);

    CredentialsSettings settings = scope.getSettings(CredentialsSettings.class);
    Class<? extends Credentials> credentialsClass = settings.getCredentialsClasses().get(type);

    if (credentialsClass == null) {
        throw new GyroException(
            "Make sure @|magenta '@plugin'|@ directive for a cloud provider is placed before @|magenta '@credentials'|@ directive in @|magenta '.gyro/init.gyro'|@ file.");
    }
    Credentials credentials = Reflections.newInstance(credentialsClass);
    credentials.scope = scope;

    for (PropertyDescriptor property : Reflections.getBeanInfo(credentialsClass).getPropertyDescriptors()) {
        Method setter = property.getWriteMethod();

        if (setter != null) {
            Reflections.invoke(setter, credentials, scope.convertValue(
                setter.getGenericParameterTypes()[0],
                bodyScope.get(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, property.getName()))));
        }
    }

    credentials.getNamespaces().stream()
        .map(ns -> ns + "::" + name)
        .forEach(n -> settings.getCredentialsByName().put(n, credentials));
}