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

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

Introduction

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

Prototype

CaseFormat LOWER_CAMEL

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

Click Source Link

Document

Java variable naming convention, e.g., "lowerCamel".

Usage

From source file:com.eucalyptus.reporting.units.Units.java

private String capitalize(final Object item) {
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, item.toString());
}

From source file:org.killbill.commons.jdbi.mapper.LowerToCamelBeanMapper.java

public T map(final int row, final ResultSet rs, final StatementContext ctx) throws SQLException {
    final T bean;
    try {/*from  w w  w.  j a  v  a  2 s . com*/
        bean = type.newInstance();
    } catch (final Exception e) {
        throw new IllegalArgumentException(
                String.format("A bean, %s, was mapped " + "which was not instantiable", type.getName()), e);
    }

    final Class beanClass = bean.getClass();
    final ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 1; i <= metadata.getColumnCount(); ++i) {
        final String name = metadata.getColumnLabel(i).toLowerCase();

        final PropertyDescriptor descriptor = properties.get(name);

        if (descriptor != null) {
            final Class<?> type = descriptor.getPropertyType();

            Object value;

            if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
                value = rs.getBoolean(i);
            } else if (type.isAssignableFrom(Byte.class) || type.isAssignableFrom(byte.class)) {
                value = rs.getByte(i);
            } else if (type.isAssignableFrom(Short.class) || type.isAssignableFrom(short.class)) {
                value = rs.getShort(i);
            } else if (type.isAssignableFrom(Integer.class) || type.isAssignableFrom(int.class)) {
                value = rs.getInt(i);
            } else if (type.isAssignableFrom(Long.class) || type.isAssignableFrom(long.class)) {
                value = rs.getLong(i);
            } else if (type.isAssignableFrom(Float.class) || type.isAssignableFrom(float.class)) {
                value = rs.getFloat(i);
            } else if (type.isAssignableFrom(Double.class) || type.isAssignableFrom(double.class)) {
                value = rs.getDouble(i);
            } else if (type.isAssignableFrom(BigDecimal.class)) {
                value = rs.getBigDecimal(i);
            } else if (type.isAssignableFrom(DateTime.class)) {
                final Timestamp timestamp = rs.getTimestamp(i);
                value = timestamp == null ? null : new DateTime(timestamp).toDateTime(DateTimeZone.UTC);
            } else if (type.isAssignableFrom(Time.class)) {
                value = rs.getTime(i);
            } else if (type.isAssignableFrom(LocalDate.class)) {
                //
                // We store the LocalDate into a mysql 'date' as a string
                // (See https://github.com/killbill/killbill-commons/blob/master/jdbi/src/main/java/org/killbill/commons/jdbi/argument/LocalDateArgumentFactory.java)
                // So we also read it as a String which avoids any kind of transformation
                //
                // Note that we used previously the getDate(index, Calendar) method, but this is not thread safe as we discovered
                // unless maybe -- untested --we pass a new instance of a Calendar each time
                //
                final String dateString = rs.getString(i);
                value = dateString == null ? null : new LocalDate(dateString, DateTimeZone.UTC);
            } else if (type.isAssignableFrom(DateTimeZone.class)) {
                final String dateTimeZoneString = rs.getString(i);
                value = dateTimeZoneString == null ? null : DateTimeZone.forID(dateTimeZoneString);
            } else if (type.isAssignableFrom(String.class)) {
                value = rs.getString(i);
            } else if (type.isAssignableFrom(UUID.class)) {
                final String uuidString = rs.getString(i);
                value = uuidString == null ? null : UUID.fromString(uuidString);
            } else if (type.isEnum()) {
                final String enumString = rs.getString(i);
                //noinspection unchecked
                value = enumString == null ? null : Enum.valueOf((Class<Enum>) type, enumString);
            } else if (type == byte[].class) {
                value = rs.getBytes(i);
            } else {
                value = rs.getObject(i);
            }

            // For h2, transform a JdbcBlob into a byte[]
            if (value instanceof Blob) {
                final Blob blob = (Blob) value;
                value = blob.getBytes(0, (int) blob.length());
            }
            if (rs.wasNull() && !type.isPrimitive()) {
                value = null;
            }

            try {
                final Method writeMethod = descriptor.getWriteMethod();
                if (writeMethod != null) {
                    writeMethod.invoke(bean, value);
                } else {
                    final String camelCasedName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
                    final Field field = getField(beanClass, camelCasedName);
                    field.setAccessible(true); // Often private...
                    field.set(bean, value);
                }
            } catch (final NoSuchFieldException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to find field for " + "property, %s", name), e);
            } catch (final IllegalAccessException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to access setter for " + "property, %s", name), e);
            } catch (final InvocationTargetException e) {
                throw new IllegalArgumentException(String.format(
                        "Invocation target exception trying to " + "invoker setter for the %s property", name),
                        e);
            } catch (final NullPointerException e) {
                throw new IllegalArgumentException(
                        String.format("No appropriate method to " + "write value %s ", value.toString()), e);
            }
        }
    }

    return bean;
}

From source file:dagger2.internal.codegen.SourceFiles.java

/**
 * This method generates names and keys for the framework classes necessary for all of the
 * bindings. It is responsible for the following:
 * <ul>// w ww. j a  v  a 2 s  .c  om
 * <li>Choosing a name that associates the binding with all of the dependency requests for this
 * type.
 * <li>Choosing a name that is <i>probably</i> associated with the type being bound.
 * <li>Ensuring that no two bindings end up with the same name.
 * </ul>
 *
 * @return Returns the mapping from {@link BindingKey} to field, sorted by the name of the field.
 */
static ImmutableMap<BindingKey, FrameworkField> generateBindingFieldsForDependencies(
        DependencyRequestMapper dependencyRequestMapper, Iterable<? extends DependencyRequest> dependencies) {
    ImmutableSetMultimap<BindingKey, DependencyRequest> dependenciesByKey = indexDependenciesByKey(
            dependencies);
    Map<BindingKey, Collection<DependencyRequest>> dependenciesByKeyMap = dependenciesByKey.asMap();
    ImmutableMap.Builder<BindingKey, FrameworkField> bindingFields = ImmutableMap.builder();
    for (Entry<BindingKey, Collection<DependencyRequest>> entry : dependenciesByKeyMap.entrySet()) {
        BindingKey bindingKey = entry.getKey();
        Collection<DependencyRequest> requests = entry.getValue();
        Class<?> frameworkClass = dependencyRequestMapper.getFrameworkClass(requests.iterator().next());
        // collect together all of the names that we would want to call the provider
        ImmutableSet<String> dependencyNames = FluentIterable.from(requests)
                .transform(new DependencyVariableNamer()).toSet();

        if (dependencyNames.size() == 1) {
            // if there's only one name, great! use it!
            String name = Iterables.getOnlyElement(dependencyNames);
            bindingFields.put(bindingKey,
                    FrameworkField.createWithTypeFromKey(frameworkClass, bindingKey, name));
        } else {
            // in the event that a field is being used for a bunch of deps with different names,
            // add all the names together with "And"s in the middle. E.g.: stringAndS
            Iterator<String> namesIterator = dependencyNames.iterator();
            String first = namesIterator.next();
            StringBuilder compositeNameBuilder = new StringBuilder(first);
            while (namesIterator.hasNext()) {
                compositeNameBuilder.append("And")
                        .append(CaseFormat.LOWER_CAMEL.to(UPPER_CAMEL, namesIterator.next()));
            }
            bindingFields.put(bindingKey, FrameworkField.createWithTypeFromKey(frameworkClass, bindingKey,
                    compositeNameBuilder.toString()));
        }
    }
    return bindingFields.build();
}

From source file:org.bonitasoft.web.designer.experimental.parametrizedWidget.ParametrizedWidgetFactory.java

private String inputDisplayLabel(ContractInput contractInput) {
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, contractInput.getName())
            .replaceAll("((?<=[a-z])(?=[A-Z]))|((?<=[A-Z])(?=[A-Z][a-z]))", " ");
}

From source file:org.mule.tools.module.loader.JarLoader.java

protected final void populateIcon(final Map<Metadata.Icon, URL> icons, final Metadata.Icon icon,
        final Repository repository, final Class<?> moduleType, final Module module) {
    final Object annotation = Annotations.getAnnotation(moduleType, Annotations.ICONS_ANNOTATION_CLASS_NAME);
    final String path;
    if (annotation != null) {
        path = Reflections.invoke(annotation,
                CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, icon.name()));
    } else {//  www .  j a v a  2 s  .  c om
        path = Reflections.staticGet(Classes.loadClass(Annotations.ICONS_ANNOTATION_CLASS_NAME),
                "GENERIC_" + icon.name());
    }
    final String finalPath = String.format(path, module.getName());
    final URL url = repository.getIconLocation(finalPath);
    if (url != null) {
        icons.put(icon, url);
    }
}

From source file:com.android.build.gradle.internal.pipeline.TransformTask.java

private static AndroidStudioStats.GradleTransformExecution.Type getTransformType(
        @NonNull Class<? extends Transform> taskClass) {
    String taskImpl = taskClass.getSimpleName();
    if (taskImpl.endsWith("Transform")) {
        taskImpl = taskImpl.substring(0, taskImpl.length() - "Transform".length());
    }/* w w  w .  j  ava 2  s .  c  om*/
    String potentialExecutionTypeName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, taskImpl);

    try {
        return AndroidStudioStats.GradleTransformExecution.Type.valueOf(potentialExecutionTypeName);
    } catch (IllegalArgumentException ignored) {
        return AndroidStudioStats.GradleTransformExecution.Type.UNKNOWN_TRANSFORM_TYPE;
    }
}

From source file:com.querydsl.core.alias.Alias.java

/**
 * Create a new alias proxy of the given type
 *
 * @param cl type of the alias//from  ww w.j a  va  2s.c o  m
 * @return alias instance
 */
public static <A> A alias(Class<A> cl) {
    return alias(cl, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, cl.getSimpleName()));
}

From source file:io.prestosql.operator.aggregation.AggregationUtils.java

public static String generateAggregationName(String baseName, TypeSignature outputType,
        List<TypeSignature> inputTypes) {
    StringBuilder sb = new StringBuilder();
    sb.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, outputType.toString()));
    for (TypeSignature inputType : inputTypes) {
        sb.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, inputType.toString()));
    }/*www .  java2  s  . c o  m*/
    sb.append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, baseName.toLowerCase(ENGLISH)));

    return sb.toString();
}

From source file:com.google.cloud.Identity.java

/**
 * Converts a string to an {@code Identity}. Used primarily for converting protobuf-generated
 * policy identities to {@code Identity} objects.
 */// www . j av a2  s.  co  m
public static Identity valueOf(String identityStr) {
    String[] info = identityStr.split(":");
    Type type = Type.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, info[0]));
    if (info.length == 1) {
        return new Identity(type, null);
    } else if (info.length == 2) {
        return new Identity(type, info[1]);
    } else {
        throw new IllegalArgumentException("Illegal identity string: \"" + identityStr + "\"");
    }
}

From source file:org.eclipse.che.api.factory.server.builder.FactoryBuilder.java

/**
 * Validate compatibility of factory parameters.
 *
 * @param object/*from  w  w  w .  j a  v a 2 s. co m*/
 *         - object to validate factory parameters
 * @param parent
 *         - parent object
 * @param methodsProvider
 *         - class that provides methods with {@link org.eclipse.che.api.core.factory.FactoryParameter}
 *         annotations
 * @param allowedMethodsProvider
 *         - class that provides allowed methods
 * @param version
 *         - version of factory
 * @param parentName
 *         - parent parameter queryParameterName
 * @throws org.eclipse.che.api.core.ConflictException
 */
void validateCompatibility(Object object, Object parent, Class methodsProvider, Class allowedMethodsProvider,
        Version version, String parentName, boolean isUpdate) throws ConflictException {
    // validate source
    if (SourceStorageDto.class.equals(methodsProvider) && !hasSubprojectInPath(parent)) {
        sourceStorageParametersValidator.validate((SourceStorage) object, version);
    }

    // get all methods recursively
    for (Method method : methodsProvider.getMethods()) {
        FactoryParameter factoryParameter = method.getAnnotation(FactoryParameter.class);
        // is it factory parameter

        if (factoryParameter == null) {
            continue;
        }
        String fullName = (parentName.isEmpty() ? "" : (parentName + ".")) + CaseFormat.UPPER_CAMEL
                .to(CaseFormat.LOWER_CAMEL, method.getName().startsWith("is") ? method.getName().substring(2)
                        : method.getName().substring(3).toLowerCase());
        // check that field is set
        Object parameterValue;
        try {
            parameterValue = method.invoke(object);
        } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
            // should never happen
            LOG.error(e.getLocalizedMessage(), e);
            throw new ConflictException(FactoryConstants.INVALID_PARAMETER_MESSAGE);
        }

        // if value is null or empty collection or default value for primitives
        if (ValueHelper.isEmpty(parameterValue)) {
            // field must not be a mandatory, unless it's ignored or deprecated or doesn't suit to the version
            if (Obligation.MANDATORY.equals(factoryParameter.obligation())
                    && factoryParameter.deprecatedSince().compareTo(version) > 0
                    && factoryParameter.ignoredSince().compareTo(version) > 0
                    && method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
                throw new ConflictException(
                        String.format(FactoryConstants.MISSING_MANDATORY_MESSAGE, method.getName()));
            }
        } else if (!method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
            throw new ConflictException(
                    String.format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
        } else {
            // is parameter deprecated
            if (factoryParameter.deprecatedSince().compareTo(version) <= 0
                    || (!isUpdate && factoryParameter.setByServer())) {
                throw new ConflictException(String
                        .format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
            }

            // use recursion if parameter is DTO object
            if (method.getReturnType().isAnnotationPresent(DTO.class)) {
                // validate inner objects such Git ot ProjectAttributes
                validateCompatibility(parameterValue, object, method.getReturnType(), method.getReturnType(),
                        version, fullName, isUpdate);
            } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[1];

                Class secMapParamClass = (tp instanceof ParameterizedType)
                        ? (Class) ((ParameterizedType) tp).getRawType()
                        : (Class) tp;
                if (!String.class.equals(secMapParamClass) && !List.class.equals(secMapParamClass)) {
                    if (secMapParamClass.isAnnotationPresent(DTO.class)) {
                        Map<Object, Object> map = (Map) parameterValue;
                        for (Map.Entry<Object, Object> entry : map.entrySet()) {
                            validateCompatibility(entry.getValue(), object, secMapParamClass, secMapParamClass,
                                    version, fullName + "." + entry.getKey(), isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            } else if (List.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];

                Class secListParamClass = (tp instanceof ParameterizedType)
                        ? (Class) ((ParameterizedType) tp).getRawType()
                        : (Class) tp;
                if (!String.class.equals(secListParamClass) && !List.class.equals(secListParamClass)) {
                    if (secListParamClass.isAnnotationPresent(DTO.class)) {
                        List<Object> list = (List) parameterValue;
                        for (Object entry : list) {
                            validateCompatibility(entry, object, secListParamClass, secListParamClass, version,
                                    fullName, isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            }
        }
    }
}