Search in sources :

Example 1 with UPPER_CAMEL

use of com.google.common.base.CaseFormat.UPPER_CAMEL in project curiostack by curioswitch.

the class GenerateApiServerTask method exec.

@TaskAction
public void exec() {
    var ant = getAnt();
    ant.invokeMethod("echo", ImmutableMap.of("message", "Generating an API server (see " + "https://codelabs.developers.curioswitch.org/defining-a-grpc-api/#1) for details."));
    ant.invokeMethod("input", ImmutableMap.of("message", "What is name of the project? Two artifacts, {name}-api and {name}-server will " + "be generated. {name}-server will be used in deployments and should be relatively " + "concise. The name should be hyphen-case", "addproperty", "name"));
    ant.invokeMethod("input", ImmutableMap.of("message", "What is the path that the files should be written to (e.g., path/to/project)?", "addproperty", "outputPath"));
    ant.invokeMethod("input", ImmutableMap.of("message", "What is the java package to place code under? " + "API will live under {package}.api and server code will live under " + "{package}.server", "addproperty", "javaPackage"));
    ant.invokeMethod("input", ImmutableMap.of("message", "What is the proto package to place the API under? " + "Defaults to same value as the java package + .api.", "addproperty", "protoPackage", "defaultvalue", ant.getProperty("javaPackage") + ".api"));
    ant.invokeMethod("input", ImmutableMap.of("message", "What is the name of the API service? This should generally be UpperCamelCase. " + "Defaults to UpperCamelCase version of {name}Service.", "addproperty", "serviceName", "defaultvalue", LOWER_HYPHEN.to(UPPER_CAMEL, (String) ant.getProperty("name")) + "Service"));
    var outputPathStr = (String) ant.getProperty("outputPath");
    if (outputPathStr.startsWith("/")) {
        throw new IllegalArgumentException("outputPath must be a relative path below the repository root, it cannot begin with /");
    }
    if (outputPathStr.endsWith("/")) {
        outputPathStr = outputPathStr.substring(0, outputPathStr.length() - 1);
    }
    Path outputPath = Paths.get(getProject().getRootDir().getAbsolutePath(), outputPathStr);
    if (Files.exists(outputPath)) {
        throw new IllegalArgumentException("Output path already exists. If this is correct, remove the directory first.");
    }
    Path apiOutputPath = outputPath.resolve("api");
    Path serverOutputPath = outputPath.resolve("server");
    Path copyrightFile = null;
    try (var s = Files.list(getProject().file(".baseline/copyright").toPath())) {
        copyrightFile = s.sorted().findFirst().orElse(null);
    } catch (IOException e) {
    // Ignore exceptions trying to read copyright.
    }
    String copyright = "";
    try (var s = Files.lines(copyrightFile)) {
        copyright = s.map(line -> line.replace("${today.year}", String.valueOf(Year.now().getValue()))).map(line -> " * " + line).collect(Collectors.joining(lineSeparator(), "/*" + lineSeparator(), lineSeparator() + " */" + lineSeparator()));
    } catch (IOException e) {
    // Ignore exceptions trying to read copyright.
    }
    String apiDependency = ':' + (outputPathStr + "/api").replace("/", ":");
    String name = (String) ant.getProperty("name");
    String protoPackage = (String) ant.getProperty("protoPackage");
    String javaPackage = (String) ant.getProperty("javaPackage");
    String serviceName = (String) ant.getProperty("serviceName");
    Map<String, Object> context = ImmutableMap.<String, Object>builder().put("copyright", copyright).put("name", name).put("proto_package", protoPackage).put("java_package", javaPackage).put("service_name", serviceName).put("api_dependency", apiDependency).build();
    render("templates/apiserver/api/build.gradle.kts.tmpl", context, apiOutputPath.resolve("build.gradle.kts"));
    render("templates/apiserver/api/service.proto.tmpl", context, apiOutputPath.resolve("src/main/proto/" + protoPackage.replace(".", "/") + "/" + name + "-service.proto"));
    render("templates/apiserver/server/build.gradle.kts.tmpl", context, serverOutputPath.resolve("build.gradle.kts"));
    render("templates/apiserver/server/Main.java.tmpl", context, serverOutputPath.resolve("src/main/java/" + javaPackage.replace(".", "/") + "/server/" + serviceName + "Main.java"));
    render("templates/apiserver/server/ServiceImpl.java.tmpl", context, serverOutputPath.resolve("src/main/java/" + javaPackage.replace(".", "/") + "/server/" + serviceName + ".java"));
}
Also used : Path(java.nio.file.Path) System.lineSeparator(java.lang.System.lineSeparator) ImmutableMap(com.google.common.collect.ImmutableMap) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) Jinjava(com.hubspot.jinjava.Jinjava) IOException(java.io.IOException) UPPER_CAMEL(com.google.common.base.CaseFormat.UPPER_CAMEL) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) TaskAction(org.gradle.api.tasks.TaskAction) Paths(java.nio.file.Paths) Year(java.time.Year) Map(java.util.Map) DefaultTask(org.gradle.api.DefaultTask) Path(java.nio.file.Path) LOWER_HYPHEN(com.google.common.base.CaseFormat.LOWER_HYPHEN) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) TaskAction(org.gradle.api.tasks.TaskAction)

Example 2 with UPPER_CAMEL

use of com.google.common.base.CaseFormat.UPPER_CAMEL in project airlift by airlift.

the class ConfigurationFactory method build.

private <T> ConfigurationHolder<T> build(Class<T> configClass, Optional<String> configPrefix, ConfigDefaults<T> configDefaults) {
    if (configClass == null) {
        throw new NullPointerException("configClass is null");
    }
    String prefix = configPrefix.map(value -> value + ".").orElse("");
    ConfigurationMetadata<T> configurationMetadata = getMetadata(configClass);
    configurationMetadata.getProblems().throwIfHasErrors();
    T instance = newInstance(configurationMetadata);
    configDefaults.setDefaults(instance);
    Problems problems = new Problems(monitor);
    for (AttributeMetadata attribute : configurationMetadata.getAttributes().values()) {
        Problems attributeProblems = new Problems(monitor);
        try {
            setConfigProperty(instance, attribute, prefix, attributeProblems);
        } catch (InvalidConfigurationException e) {
            attributeProblems.addError(e.getCause(), e.getMessage());
        }
        problems.record(attributeProblems);
    }
    // Check that none of the defunct properties are still in use
    if (configClass.isAnnotationPresent(DefunctConfig.class)) {
        for (String value : configClass.getAnnotation(DefunctConfig.class).value()) {
            String name = prefix + value;
            if (!value.isEmpty() && properties.get(name) != null) {
                problems.addError("Defunct property '%s' (class [%s]) cannot be configured.", name, configClass.toString());
            }
        }
    }
    // if there already problems, don't run the bean validation as it typically reports duplicate errors
    problems.throwIfHasErrors();
    for (ConstraintViolation<?> violation : validate(instance)) {
        String propertyFieldName = violation.getPropertyPath().toString();
        // upper case first character to match config attribute name
        String attributeName = LOWER_CAMEL.to(UPPER_CAMEL, propertyFieldName);
        AttributeMetadata attribute = configurationMetadata.getAttributes().get(attributeName);
        if (attribute != null && attribute.getInjectionPoint() != null) {
            String propertyName = attribute.getInjectionPoint().getProperty();
            if (!prefix.isEmpty()) {
                propertyName = prefix + propertyName;
            }
            problems.addError("Invalid configuration property %s: %s (for class %s.%s)", propertyName, violation.getMessage(), configClass.getName(), violation.getPropertyPath());
        } else {
            problems.addError("Invalid configuration property with prefix '%s': %s (for class %s.%s)", prefix, violation.getMessage(), configClass.getName(), violation.getPropertyPath());
        }
    }
    problems.throwIfHasErrors();
    return new ConfigurationHolder<>(instance, problems);
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Module(com.google.inject.Module) LoadingCache(com.google.common.cache.LoadingCache) Provider(javax.inject.Provider) ListMultimap(com.google.common.collect.ListMultimap) Key(com.google.inject.Key) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) Message(com.google.inject.spi.Message) Map(java.util.Map) Splitter(com.google.common.base.Splitter) ConstraintViolation(javax.validation.ConstraintViolation) Method(java.lang.reflect.Method) ApacheValidationProvider(org.apache.bval.jsr.ApacheValidationProvider) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConfigurationException(com.google.inject.ConfigurationException) Validator(javax.validation.Validator) Set(java.util.Set) GuardedBy(javax.annotation.concurrent.GuardedBy) Binding(com.google.inject.Binding) String.format(java.lang.String.format) InvocationTargetException(java.lang.reflect.InvocationTargetException) CacheLoader(com.google.common.cache.CacheLoader) LOWER_CAMEL(com.google.common.base.CaseFormat.LOWER_CAMEL) List(java.util.List) ConfigurationMetadata.getConfigurationMetadata(io.airlift.configuration.ConfigurationMetadata.getConfigurationMetadata) Element(com.google.inject.spi.Element) Optional(java.util.Optional) InstanceBinding(com.google.inject.spi.InstanceBinding) CacheBuilder(com.google.common.cache.CacheBuilder) Problems.exceptionFor(io.airlift.configuration.Problems.exceptionFor) TypeToken(com.google.common.reflect.TypeToken) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Multimaps(com.google.common.collect.Multimaps) DefaultElementVisitor(com.google.inject.spi.DefaultElementVisitor) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) Validation(javax.validation.Validation) Nullable(javax.annotation.Nullable) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Sets.newConcurrentHashSet(com.google.common.collect.Sets.newConcurrentHashSet) UPPER_CAMEL(com.google.common.base.CaseFormat.UPPER_CAMEL) Consumer(java.util.function.Consumer) AttributeMetadata(io.airlift.configuration.ConfigurationMetadata.AttributeMetadata) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Elements(com.google.inject.spi.Elements) AttributeMetadata(io.airlift.configuration.ConfigurationMetadata.AttributeMetadata)

Aggregations

UPPER_CAMEL (com.google.common.base.CaseFormat.UPPER_CAMEL)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 Map (java.util.Map)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 LOWER_CAMEL (com.google.common.base.CaseFormat.LOWER_CAMEL)1 LOWER_HYPHEN (com.google.common.base.CaseFormat.LOWER_HYPHEN)1 Splitter (com.google.common.base.Splitter)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 CacheLoader (com.google.common.cache.CacheLoader)1 LoadingCache (com.google.common.cache.LoadingCache)1 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)1 ListMultimap (com.google.common.collect.ListMultimap)1 Multimaps (com.google.common.collect.Multimaps)1 Sets.newConcurrentHashSet (com.google.common.collect.Sets.newConcurrentHashSet)1 Resources (com.google.common.io.Resources)1 TypeToken (com.google.common.reflect.TypeToken)1