Example usage for com.google.common.base CaseFormat LOWER_UNDERSCORE

List of usage examples for com.google.common.base CaseFormat LOWER_UNDERSCORE

Introduction

In this page you can find the example usage for com.google.common.base CaseFormat LOWER_UNDERSCORE.

Prototype

CaseFormat LOWER_UNDERSCORE

To view the source code for com.google.common.base CaseFormat LOWER_UNDERSCORE.

Click Source Link

Document

C++ variable naming convention, e.g., "lower_underscore".

Usage

From source file:name.martingeisse.admin.customization.Main.java

/**
 * The main method//from   w ww  . j av  a  2 s.c  o m
 * @param args command-line arguments (ignored)
 * @throws Exception on errors
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception {

    // --- code generation start ---
    /*
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/phorum?zeroDateTimeBehavior=convertToNull&useTimezone=false", "root", "");
    MetaDataExporter exporter = new MetaDataExporter();
    exporter.setTargetFolder(new File("generated"));
    exporter.setPackageName("phorum");
    exporter.setSerializerClass(MetaDataSerializer.class);
    exporter.setBeanSerializer(new BeanSerializer(true));
    exporter.export(connection.getMetaData());
    connection.close();
    System.exit(0);
    */
    // --- code generation end ---

    //      DatabaseDescriptor mainDatabase = new DatabaseDescriptor();
    //      mainDatabase.setDisplayName("main database");
    //      mainDatabase.setUrl("jdbc:postgresql://localhost/admintest");
    //      mainDatabase.setUsername("postgres");
    //      mainDatabase.setPassword("postgres");
    //      ApplicationConfiguration.addDatabase(mainDatabase);

    // the database
    //      final AbstractDatabaseDescriptor phpbbDatabase = new MysqlDatabaseDescriptor();
    //      phpbbDatabase.setDisplayName("phpBB database");
    //      phpbbDatabase.setUrl("jdbc:mysql://localhost/phpbb");
    //      phpbbDatabase.setUsername("root");
    //      phpbbDatabase.setPassword("");
    //      ApplicationConfiguration.get().addDatabase(phpbbDatabase);

    //
    // The database. Note about "useTimezone=false": This is needed so we can load local dates and
    // datetimes from the database. JDBC uses an inherently broken model here, which we're trying to
    // circumvent. Speaking in Joda-Time terms, the database stores a local date or datetime value,
    // NOT an instant -- that is, the timezone is implicit, not stored. JDBC, however, always
    // wants to convert this to an instant that is expressed as a java.sql.Date or java.sql.Timestamp,
    // i.e. an instant that is represented in UTC, using an implicit timezone whose origin depends
    // on the JDBC driver. To obtain a local value without too much hassle, we set "useTimezone=false"
    // to make this conversion a NOP, i.e. make JDBC assume that the database value is a local value
    // that is to be interpreted as UTC, so the conversion just takes this value and adds "UTC" to it.
    // We then take the value and create a local value as a Joda object by throwing away the "UTC" again.
    //
    // NOTE: This description is specific to MySQL. For other databases, we basically need to do
    // whatever is necessary to read the local value from the database as a local value expressed
    // as a Joda object, circumventing JDBC's stupidity and implicit rules.
    //
    // NOTE: The server stores a server-wide time zone setting. One *could* use that to interpret
    // database values as instants instead of local values. However, (1) this setting cannot be
    // trusted to be correct since it's not used in many places in DB-side time handling (i.e.
    // we might very well have to deal with an incorrectly configured database and existing
    // applications that know how to work around it), and (2) we'll have to deal with values in the
    // DB that are meant as local values, and might even be part of a (local value, time zone) pair.
    // Applying the server time zone to such values would be incorrect. So we'll only deal with the
    // server time zone as much as needed to get rid of it and obtain the local values that are
    // actually stored in the DB tables.
    //
    // If part of the application wants to store an instant in the database -- a quite common task --
    // we'll rather have the application convert it manually, possibly providing access to
    // automatic type conversion (e.g. an implicitly converting ISqlDateTimeTypeInfo). The
    // admin framework should not do this -- it would be an implicit conversion layer that adds
    // confusion, and it would be unclear to the application developer how the time zone used
    // for that conversion is related to the SQL server time zone setting.
    //
    // NOTE: Actually we don't absolutely *need* that parameter for MySQL since it's the default.
    //
    final MysqlDatabaseDescriptor phorumDatabase = new MysqlDatabaseDescriptor();
    phorumDatabase.setDisplayName("Phorum database");
    phorumDatabase.setUrl("jdbc:mysql://localhost/phorum?zeroDateTimeBehavior=convertToNull&useTimezone=false");
    phorumDatabase.setUsername("root");
    phorumDatabase.setPassword("");
    phorumDatabase.setDefaultTimeZone(DateTimeZone.forID("Europe/Berlin"));
    // phorumDatabase.setDefaultTimeZone(DateTimeZone.forID("Europe/London"));
    phorumDatabase.initialize();
    ApplicationConfiguration.get().addDatabase(phorumDatabase);
    EntityConnectionManager.initializeDatabaseDescriptors(phorumDatabase);

    // plugins / capabilities
    ApplicationConfiguration.get().addPlugin(new DefaultPlugin());
    // ApplicationConfiguration.get().addPlugin(new FixedNameEntityReferenceDetector("extensions", "group_id", "extension_groups"));
    ApplicationConfiguration.get().addPlugin(new CustomizationPlugin());
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, null, "modificationTimestamp", false));
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, null, "modificationUser_id", false));
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, "User", "lastLoginAttemptTimestamp", false));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("ids", "IDs only", IdOnlyGlobalEntityListPanel.class));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("roleList", "Role List", RoleOrderListPanel.class));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("popdata", "Populator / DataView", PopulatorDataViewPanel.class));

    final ExplicitEntityPropertyFilter userPropertyFilter = new ExplicitEntityPropertyFilter(2, "User");
    userPropertyFilter.getVisiblePropertyNames().add("id");
    userPropertyFilter.getVisiblePropertyNames().add("name");
    ApplicationConfiguration.get().addPlugin(userPropertyFilter);

    // general parameters
    //      PagesConfigurationUtil.setPageBorderFactory(new name.martingeisse.admin.customization.PageBorderFactory());

    // entity parameters
    EntityConfiguration generalEntityConfiguration = new EntityConfiguration();
    //      generalEntityConfiguration.setEntityNameMappingStrategy(new PrefixEliminatingEntityNameMappingStrategy("phpbb_"));
    IEntityNameMappingStrategy.PARAMETER_KEY.set(new PrefixEliminatingEntityNameMappingStrategy("phorum_"));
    EntityConfiguration.parameterKey.set(generalEntityConfiguration);

    // entity navigation contributors
    /*
    EntityCapabilities.entityNavigationContributorCapability.add(new IEntityNavigationContributor() {
       @Override
       public void contributeNavigationNodes(EntityDescriptor entity, NavigationNode mainEntityInstanceNode) {
    if (entity.getName().equals("settings")) {
       mainEntityInstanceNode.setHandler(new EntityInstancePanelHandler(SettingPanel.class));
    } else {
       mainEntityInstanceNode.setHandler(new EntityInstancePanelHandler(RawEntityPresentationPanel.class));
    }
    mainEntityInstanceNode.getChildFactory().createEntityInstancePanelChild("edit", "Edit", NavigationMountedEntityAutoformPanel.class);
       }
    });
    */

    // test raw entity presentation column order
    //      EntityConfigurationUtil.getGeneralEntityConfiguration().setEntityListFieldOrder(new IEntityListFieldOrder() {
    //         @Override
    //         public int compare(EntityPropertyDescriptor prop1, EntityPropertyDescriptor prop2) {
    //            return prop1.getName().compareTo(prop2.getName());
    //         }
    //      });

    // test entity search support
    EntityCapabilities.entitySearchContributorCapability.add(new IEntitySearchContributor() {

        @Override
        public IEntitySearchStrategy getSearchStrategy(EntityDescriptor entity) {
            return new IEntitySearchStrategy() {
                @Override
                public Predicate createFilter(EntityDescriptor entity, String searchTerm) {
                    EntityConditions conditions = new EntityConditions(entity);
                    conditions.addFieldComparison("name", Ops.LIKE, "%" + searchTerm.replace("%", "") + "%");
                    return conditions;
                }
            };
        }

        @Override
        public int getScore(EntityDescriptor entity) {
            return (entity.getProperties().get("name") == null ? Integer.MIN_VALUE : 0);
        }

    });

    // entity autoforms
    IEntityAnnotatedClassResolver classResolver = new EntityAutoformAnnotatedClassResolver(
            "name.martingeisse.admin.customization.entity");
    EntityCapabilities.entityAnnotationContributorCapability
            .add(new AnnotatedClassEntityAnnotationContributor(classResolver));

    // initialize specific entity code mapping
    IEntityOrmMapper.PARAMETER_KEY.set(new IEntityOrmMapper() {
        @Override
        public EntityOrmMapping map(EntityDescriptor entityDescriptor) {
            try {
                String baseName = entityDescriptor.getName();
                String suffix = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, baseName);
                String className = "phorum.Phorum" + suffix;
                String qclassName = "phorum.QPhorum" + suffix;
                return new EntityOrmMapping(entityDescriptor, Class.forName(className), GenericTypeUtil
                        .<Class<? extends RelationalPath<?>>>unsafeCast(Class.forName(qclassName)));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    });

    // run
    WebServerLauncher.launch();

}

From source file:org.syncany.plugins.transfer.TransferPluginUtil.java

/**
 * Determines the {@link TransferManager} class for a given
 * {@link TransferPlugin} class.//  w  w w.  java 2s . co m
 */
public static Class<? extends TransferManager> getTransferManagerClass(
        Class<? extends TransferPlugin> transferPluginClass) {
    String pluginNameIdentifier = TransferPluginUtil.getPluginPackageName(transferPluginClass);

    if (pluginNameIdentifier == null) {
        throw new RuntimeException("There are no valid transfer manager attached to that plugin ("
                + transferPluginClass.getName() + ")");
    } else {
        try {
            String pluginPackageIdentifier = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,
                    pluginNameIdentifier);
            String transferManagerClassName = MessageFormat.format(PLUGIN_TRANSFER_MANAGER_CLASS_NAME,
                    pluginPackageIdentifier, pluginNameIdentifier);
            return Class.forName(transferManagerClassName).asSubclass(TransferManager.class);
        } catch (Exception e) {
            throw new RuntimeException("Cannot find matching transfer manager class for plugin ("
                    + transferPluginClass.getName() + ")");
        }
    }
}

From source file:org.brooth.jeta.apt.processors.ObservableProcessor.java

public boolean process(TypeSpec.Builder builder, RoundContext context) {
    ClassName masterClassName = ClassName.get(context.metacodeContext().masterElement());
    builder.addSuperinterface(//w  w  w . ja v  a 2s .  c o  m
            ParameterizedTypeName.get(ClassName.get(ObservableMetacode.class), masterClassName));

    MethodSpec.Builder applyMethodSpecBuilder = MethodSpec.methodBuilder("applyObservable")
            .addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(void.class)
            .addParameter(masterClassName, "master");

    for (Element element : context.elements()) {
        String fieldName = element.getSimpleName().toString();

        String monitorFiledName = fieldName + "_MONITOR";
        builder.addField(FieldSpec.builder(Object.class, monitorFiledName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("new Object()")
                .build());

        TypeName observersTypeName = TypeName.get(element.asType());
        TypeName mapTypeName = ParameterizedTypeName.get(ClassName.get(Map.class), masterClassName,
                observersTypeName);
        FieldSpec observersField = FieldSpec.builder(mapTypeName, fieldName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC).initializer("new $T()", ParameterizedTypeName
                        .get(ClassName.get(WeakHashMap.class), masterClassName, observersTypeName))
                .build();
        builder.addField(observersField);

        String eventTypeStr = observersTypeName.toString();
        int i = eventTypeStr.indexOf('<');
        if (i == -1)
            throw new IllegalArgumentException(
                    "Not valid @Subject usage, define event type as generic of Observers");

        eventTypeStr = eventTypeStr.substring(i + 1, eventTypeStr.lastIndexOf('>'));
        String methodHashName = "get" + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL,
                CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, eventTypeStr).replaceAll("\\.", "_"))
                + "Observers";

        MethodSpec getObserversMethodSpec = MethodSpec.methodBuilder(methodHashName)
                .addModifiers(Modifier.STATIC, Modifier.PUBLIC).returns(observersTypeName)
                .addParameter(masterClassName, "master")
                .addStatement("$T result = $L.get(master)", observersTypeName, fieldName)
                .beginControlFlow("if (result == null)").beginControlFlow("synchronized ($L)", monitorFiledName)
                .beginControlFlow("if (!$L.containsKey(master))", fieldName)
                .addStatement("result = new $T()", observersTypeName)
                .addStatement("$L.put(master, result)", fieldName).endControlFlow().endControlFlow()
                .endControlFlow().addStatement("return result").build();
        builder.addMethod(getObserversMethodSpec);

        applyMethodSpecBuilder.addStatement("master.$L = $L(master)", fieldName, methodHashName);
    }
    builder.addMethod(applyMethodSpecBuilder.build());

    return false;
}

From source file:datamine.storage.recordbuffers.idl.generator.RecordMetaWrapperGenerator.java

public static String getBaseClassGetterName(Field field) {
    return new StringBuilder().append("get")
            .append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field.getName())).toString();
}

From source file:org.apache.airavata.userprofile.core.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = (ObjectNode) mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {/*from  w  w w . j  ava2  s  .com*/
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

From source file:org.brooth.jeta.apt.processors.ObserverProcessor.java

public boolean process(TypeSpec.Builder builder, RoundContext context) {
    ClassName masterClassName = ClassName.get(context.metacodeContext().masterElement());
    builder.addSuperinterface(//w  w  w . j  ava  2s  .  c o  m
            ParameterizedTypeName.get(ClassName.get(ObserverMetacode.class), masterClassName));
    ClassName handlerClassName = ClassName.get(ObserverHandler.class);

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("applyObservers").addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC).returns(handlerClassName)
            .addParameter(masterClassName, "master", Modifier.FINAL).addParameter(Object.class, "observable")
            .addParameter(Class.class, "observableClass")
            .addStatement("$T handler = new $T()", handlerClassName, handlerClassName);

    for (Element element : context.elements()) {
        final Observe annotation = element.getAnnotation(Observe.class);
        String observableClass = MetacodeUtils.extractClassName(new Runnable() {
            public void run() {
                annotation.value();
            }
        });
        ClassName observableTypeName = ClassName.bestGuess(observableClass);
        ClassName metacodeTypeName = ClassName.bestGuess(MetacodeUtils.toMetacodeName(observableClass));

        List<? extends VariableElement> params = ((ExecutableElement) element).getParameters();
        if (params.size() != 1)
            throw new IllegalArgumentException("Observer method must have one parameter (event)");
        TypeName eventTypeName = TypeName.get(params.get(0).asType());
        if (eventTypeName instanceof ParameterizedTypeName)
            eventTypeName = ((ParameterizedTypeName) eventTypeName).rawType;

        String methodHashName = "get"
                + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, CaseFormat.UPPER_CAMEL
                        .to(CaseFormat.UPPER_UNDERSCORE, eventTypeName.toString()).replaceAll("\\.", "_"))
                + "Observers";

        TypeSpec eventObserverTypeSpec = TypeSpec.anonymousClassBuilder("")
                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(EventObserver.class), eventTypeName))
                .addMethod(MethodSpec.methodBuilder("onEvent").addAnnotation(Override.class)
                        .addModifiers(Modifier.PUBLIC).addParameter(eventTypeName, "event").returns(void.class)
                        .addStatement("master.$N(event)", element.getSimpleName().toString()).build())
                .build();

        methodBuilder.beginControlFlow("if ($T.class == observableClass)", observableTypeName)
                .addStatement("handler.add($T.class, $T.class,\n$T.$L(($T) observable).\nregister($L))",
                        observableTypeName, eventTypeName, metacodeTypeName, methodHashName, observableTypeName,
                        eventObserverTypeSpec)
                .endControlFlow();
    }
    methodBuilder.addStatement("return handler");
    builder.addMethod(methodBuilder.build());
    return false;
}

From source file:org.embulk.cli.EmbulkNew.java

public boolean newPlugin() throws IOException {
    if (Files.exists(this.pluginBasePath)) {
        throw new IOException("./" + this.fullProjectName + " already exists. Please delete it first.");
    }//from   ww  w  . j  a  va  2 s .  c  om

    Files.createDirectories(this.pluginBasePath);

    System.out.println("Creating " + this.fullProjectName + "/");

    boolean success = false;
    try {
        //
        // Generate gemspec
        //
        final String author = getGitConfig("user.name", "YOUR_NAME");
        final String email = getGitConfig("user.email", "YOUR_NAME");
        final String expectedGitHubAccount = email.split("@")[0];

        // variables used in Velocity templates
        final String rubyClassName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name);
        final String javaClassName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name)
                + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, category) + "Plugin";
        final String javaPackageName = "org.embulk." + embulkCategory + "." + name;
        final String displayName = getDisplayName(name);
        final String displayCategory = category.replace("_", " ");

        final HashMap<String, String> extraGuesses = new HashMap<String, String>();

        final String description;
        switch (category) {
        case "input":
            description = String.format("Loads records from %s.", displayName);
            break;
        case "file_input":
            description = String.format("Reads files stored on %s.", displayName);
            break;
        case "parser":
            description = String.format("Parses %s files read by other file input plugins.", displayName);
            extraGuesses.put("embulk/data/new/ruby/parser_guess.rb.vm",
                    String.format("%s/guess/%s.rb", pluginDirectory, name));
            break;
        case "decoder":
            description = String.format("Decodes %s-encoded files read by other file input plugins.",
                    displayName);
            extraGuesses.put("embulk/data/new/ruby/decoder_guess.rb.vm",
                    String.format("%s/guess/%s.rb", pluginDirectory, name));
            break;
        case "output":
            description = String.format("Dumps records to %s.", displayName);
            break;
        case "file_output":
            description = String.format("Stores files on %s.", displayName);
            break;
        case "formatter":
            description = String.format("Formats %s files for other file output plugins.", displayName);
            break;
        case "encoder":
            description = String.format("Encodes files using %s for other file output plugins.", displayName);
            break;
        case "filter":
            description = String.format("%s", displayName);
            break;
        default:
            throw new RuntimeException("FATAL: Invalid plugin category.");
        }

        //
        // Generate project repository
        //
        final VelocityContext velocityContext = createVelocityContext(author, category, description,
                displayName, displayCategory, email, embulkCategory, this.embulkVersion, expectedGitHubAccount,
                fullProjectName, javaClassName, javaPackageName, language, name, rubyClassName);
        copyTemplated("embulk/data/new/README.md.vm", "README.md", velocityContext);
        copy("embulk/data/new/LICENSE.txt", "LICENSE.txt");
        copyTemplated("embulk/data/new/gitignore.vm", ".gitignore", velocityContext);

        switch (language) {
        case "ruby":
            copy("embulk/data/new/ruby/Rakefile", "Rakefile");
            copy("embulk/data/new/ruby/Gemfile", "Gemfile");
            copy("embulk/data/new/ruby/.ruby-version", ".ruby-version");
            copyTemplated("embulk/data/new/ruby/gemspec.vm", fullProjectName + ".gemspec", velocityContext);
            copyTemplated(String.format("embulk/data/new/ruby/%s.rb.vm", category), this.pluginPath,
                    velocityContext);
            break;
        case "java":
            copy("embulk/data/new/java/gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.jar");
            copy("embulk/data/new/java/gradle/wrapper/gradle-wrapper.properties",
                    "gradle/wrapper/gradle-wrapper.properties");
            copy("embulk/data/new/java/gradlew.bat", "gradlew.bat");
            copy("embulk/data/new/java/gradlew", "gradlew");
            setExecutable("gradlew");
            copy("embulk/data/new/java/config/checkstyle/checkstyle.xml", "config/checkstyle/checkstyle.xml");
            copy("embulk/data/new/java/config/checkstyle/default.xml", "config/checkstyle/default.xml");
            copyTemplated("embulk/data/new/java/build.gradle.vm", "build.gradle", velocityContext);
            copyTemplated("embulk/data/new/java/plugin_loader.rb.vm", this.pluginPath, velocityContext);
            copyTemplated(String.format("embulk/data/new/java/%s.java.vm", category), String
                    .format("src/main/java/%s/%s.java", javaPackageName.replaceAll("\\.", "/"), javaClassName),
                    velocityContext);
            copyTemplated("embulk/data/new/java/test.java.vm", String.format("src/test/java/%s/Test%s.java",
                    javaPackageName.replaceAll("\\.", "/"), javaClassName), velocityContext);
            break;
        }

        for (Map.Entry<String, String> entry : extraGuesses.entrySet()) {
            copyTemplated(entry.getKey(), entry.getValue(), velocityContext);
        }

        System.out.println("");
        System.out.println("Plugin template is successfully generated.");

        switch (language) {
        case "ruby":
            System.out.println("Next steps:");
            System.out.println("");
            System.out.printf("  $ cd %s\n", fullProjectName);
            System.out
                    .println("  $ bundle install                      # install one using rbenv & rbenv-build");
            System.out.println("  $ bundle exec rake                    # build gem to be released");
            System.out
                    .println("  $ bundle exec embulk run config.yml   # you can run plugin using this command");
            break;
        case "java":
            System.out.println("Next steps:");
            System.out.println("");
            System.out.printf("  $ cd %s\n", fullProjectName);
            System.out.println("  $ ./gradlew package");
        }

        success = true;
        System.out.println("");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!success) {
            System.out.println("Failed. Removing the directory created.");
            deleteDirectoryTree(Paths.get(fullProjectName));
        }
    }
    return success;
}

From source file:org.apache.brooklyn.util.javalang.Enums.java

/** checks that all accepted enum values are represented by the given set of explicit values */
public static void checkAllEnumeratedIgnoreCase(String contextMessage, Enum<?>[] enumValues,
        String... explicitValues) {
    MutableSet<String> explicitValuesSet = MutableSet
            .copyOf(Iterables.transform(Arrays.asList(explicitValues), StringFunctions.toLowerCase()));

    Set<Enum<?>> missingEnums = MutableSet.of();
    for (Enum<?> e : enumValues) {
        if (explicitValuesSet.remove(e.name().toLowerCase()))
            continue;
        if (explicitValuesSet.remove(e.toString().toLowerCase()))
            continue;

        if (explicitValuesSet
                .remove(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, e.name()).toLowerCase()))
            continue;
        if (explicitValuesSet
                .remove(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.toString()).toLowerCase()))
            continue;

        if (explicitValuesSet
                .remove(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, e.toString()).toLowerCase()))
            continue;
        if (explicitValuesSet
                .remove(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.name()).toLowerCase()))
            continue;

        missingEnums.add(e);/*from   www.  j a va  2  s  .  c o  m*/
    }

    if (!missingEnums.isEmpty() || !explicitValuesSet.isEmpty()) {
        throw new IllegalStateException("Not all options for " + contextMessage + " are enumerated; "
                + "leftover enums = " + missingEnums + "; " + "leftover values = " + explicitValuesSet);
    }
}

From source file:com.salesforce.jprotoc.ProtoTypeMap.java

private static String getJavaOuterClassname(DescriptorProtos.FileDescriptorProto fileDescriptor,
        DescriptorProtos.FileOptions fileOptions) {

    if (fileOptions.hasJavaOuterClassname()) {
        return fileOptions.getJavaOuterClassname();
    }//from w w w.ja v a  2s  .c  o m

    // If the outer class name is not explicitly defined, then we take the proto filename, strip its extension,
    // and convert it from snake case to camel case.
    String filename = fileDescriptor.getName().substring(0,
            fileDescriptor.getName().length() - ".proto".length());

    return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, filename);
}

From source file:com.geemvc.taglib.html.UrlTagSupport.java

protected void appendTagAttributes(JspWriter writer) throws JspException {
    try {//from   w w w.  j a  va 2  s  .co m
        String name = getName();
        String id = getId();

        if (value == null && handler == null && name == null)
            throw new IllegalArgumentException(
                    "You must either specify the value attribute (<h:url value=\"/my/path\">), a target handler method (<h:url handler=\"myHandler\">) or a unique handler-name (<h:url name=\"my-unique-handler-name\">) when using the url tag.");

        // Only write attributes when generating a tag.
        if (getTag() == true) {

            if (name == null)
                name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, handlerMethod().getName());

            if (id == null)
                id = toElementId(handlerMethod().getName());

            writer.write(Char.SPACE);
            writer.write("id");
            writer.write(Char.EQUALS);
            writer.write(Char.DOUBLE_QUOTE);
            writer.write(id);
            writer.write(Char.DOUBLE_QUOTE);
        }

        if (value == null) {
            if (handler != null)
                value = toURI(getControllerClass(), handler);

            else if (name != null)
                value = toURI(name);
        } else {
            ensureMatchingHandlerExists(value);
        }

        if (value == null)
            throw new JspException(
                    "No url could be found or automatically composed. Check your tag definition.");

        // URI may contain parameters.
        if (value.indexOf(Char.CURLY_BRACKET_OPEN) != -1) {
            Map<String, String> pathParameters = pathParameters();
            value = insertParameters(value, pathParameters);
        }

        ServletRequest request = ((PageContext) jspContext).getRequest();
        String url = injector.getInstance(Requests.class).toRequestURL(value,
                https == null ? request.isSecure() : https, request);

        if (!Str.isEmpty(var)) {
            jspContext.setAttribute(var, url, scope());
        } else {
            // Only output the href attribute when a tag is to be generated.
            if (getTag() == true) {
                writer.write(Char.SPACE);
                writer.write("href");
                writer.write(Char.EQUALS);
                writer.write(Char.DOUBLE_QUOTE);
                writer.write(url);
                writer.write(Char.DOUBLE_QUOTE);
            } else {
                writer.write(url);
            }
        }
    } catch (Throwable t) {
        throw new JspException(t);
    }
}