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

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

Introduction

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

Prototype

CaseFormat UPPER_CAMEL

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

Click Source Link

Document

Java and C++ class naming convention, e.g., "UpperCamel".

Usage

From source file:edu.berkeley.ground.postgres.dao.version.PostgresItemDao.java

@Override
public T retrieveFromDatabase(String sourceKey) throws GroundException {
    return this.retrieve(String.format(SqlConstants.SELECT_STAR_BY_SOURCE_KEY,
            CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, this.getType().getSimpleName()), sourceKey),
            sourceKey);/* w ww  .j av  a 2 s. co  m*/
}

From source file:org.apache.brooklyn.util.javalang.coerce.EnumTypeCoercions.java

public static <E extends Enum<E>> Maybe<E> tryCoerce(String input, Class<E> targetType) {
    if (input == null)
        return null;
    if (targetType == null)
        return Maybe.absent("Null enum type");
    if (!targetType.isEnum())
        return Maybe.absent("Type '" + targetType + "' is not an enum");

    List<String> options = ImmutableList.of(input,
            CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, input),
            CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, input),
            CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input),
            CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input));
    for (String value : options) {
        try {//from   w ww  .  j  a v a2s  .  co  m
            return Maybe.of(Enum.valueOf(targetType, value));
        } catch (IllegalArgumentException iae) {
            continue;
        }
    }
    Maybe<E> result = Enums.valueOfIgnoreCase(targetType, input);
    if (result.isPresent())
        return result;
    return Maybe.absent(new ClassCoercionException(
            "Invalid value '" + input + "' for " + JavaClassNames.simpleClassName(targetType)
                    + "; expected one of " + Arrays.asList(Enums.values(targetType))));
}

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

/**
 * Determines the {@link TransferManager} class for a given
 * {@link TransferPlugin} class.//from   w w  w . j  av a  2s .  c o 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:name.martingeisse.admin.customization.Main.java

/**
 * The main method/*  ww  w  .j  av  a2s. c om*/
 * @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:com.axelor.csv.script.PrepareCsv.java

/**
 * Method to generate csv files//  w w  w  .  j  a v a 2s .  com
 * @param xmlDir 
 * @param csvDir
 */
public void prepareCsv(String xmlDir, String csvDir) {
    List<String> ignoreType = Arrays.asList("one-to-one", "many-to-many", "one-to-many");
    try {
        if (xmlDir != null && csvDir != null) {
            File xDir = new File(xmlDir);
            File cDir = new File(csvDir);
            List<String[]> blankData = new ArrayList<String[]>();
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            if (xDir.isDirectory() && cDir.isDirectory()) {
                for (File xf : xDir.listFiles()) {
                    LOG.info("Processing XML: " + xf.getName());
                    List<String> fieldList = new ArrayList<String>();
                    Document doc = dBuilder.parse(xf);
                    NodeList nList = doc.getElementsByTagName("module");
                    String module = nList.item(0).getAttributes().getNamedItem("name").getNodeValue();
                    nList = doc.getElementsByTagName("entity");
                    if (nList != null) {
                        NodeList fields = nList.item(0).getChildNodes();
                        Integer count = 0;
                        String csvFileName = module + "_" + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,
                                xf.getName().replace(".xml", ".csv"));
                        while (count < fields.getLength()) {
                            Node field = fields.item(count);
                            NamedNodeMap attrs = field.getAttributes();
                            String type = field.getNodeName();
                            if (attrs != null && attrs.getNamedItem("name") != null
                                    && !ignoreType.contains(type)) {
                                String fieldName = attrs.getNamedItem("name").getNodeValue();
                                if (type.equals("many-to-one")) {
                                    String[] objName = attrs.getNamedItem("ref").getNodeValue().split("\\.");
                                    String refName = objName[objName.length - 1];
                                    String nameColumn = getNameColumn(xmlDir + "/" + refName + ".xml");
                                    if (nameColumn != null)
                                        fieldList.add(fieldName + "." + nameColumn);
                                    else {
                                        fieldList.add(fieldName);
                                        LOG.error("No name column found for " + refName + ", field '"
                                                + attrs.getNamedItem("name").getNodeValue() + "'");
                                    }
                                } else
                                    fieldList.add(fieldName);
                            }

                            count++;
                        }
                        CsvTool.csvWriter(csvDir, csvFileName, ';', StringUtils.join(fieldList, ",").split(","),
                                blankData);
                        LOG.info("CSV file prepared: " + csvFileName);
                    }
                }

            } else
                LOG.error("XML and CSV paths must be directory");
        } else
            LOG.error("Please input XML and CSV directory path");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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(//from   www.j a  va 2 s.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:fr.putnami.pwt.core.error.client.widget.SimpleErrorDisplayer.java

private String getMessage(Throwable error, String suffix, String defaultMessage) {
    if (this.constants == null) {
        return defaultMessage;
    }/*from   ww w. j av  a2 s.  co m*/
    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;
    }
}

From source file:com.bbva.kltt.apirest.core.generator.output.language.OutputLanguageNaming.java

@Override
public String getCamelCaseName(final String name) {
    String nameToFormat = ConstantsCommon.STRING_EMPTY;
    if (name != null) {
        //Converting the spaces and hyphens to underscores
        nameToFormat = name.replaceAll("[ -]", ConstantsCommon.STRING_UNDERSCORE);
    }/*from w w w .  j a v a2  s. com*/

    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, nameToFormat);
}

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

protected void appendTagAttributes(JspWriter writer) throws JspException {
    try {/*  ww w.  j a  v a 2s.  c om*/
        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);
    }
}