Skip to content

Commit

Permalink
feat: updated existing converters
Browse files Browse the repository at this point in the history
  • Loading branch information
SethFalco committed Feb 4, 2024
1 parent a234761 commit d7c8bba
Show file tree
Hide file tree
Showing 12 changed files with 367 additions and 139 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.nio.file.Path;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
Expand Down Expand Up @@ -66,6 +67,7 @@
import org.apache.commons.beanutils2.converters.FileConverter;
import org.apache.commons.beanutils2.converters.FloatConverter;
import org.apache.commons.beanutils2.converters.InetAddressConverter;
import org.apache.commons.beanutils2.converters.InstantConverter;
import org.apache.commons.beanutils2.converters.IntegerConverter;
import org.apache.commons.beanutils2.converters.LocalDateConverter;
import org.apache.commons.beanutils2.converters.LocalDateTimeConverter;
Expand Down Expand Up @@ -128,6 +130,7 @@
* <li>java.sql.Date (no default value)</li>
* <li>java.sql.Time (no default value)</li>
* <li>java.sql.Timestamp (no default value)</li>
* <li>java.time.Instant (no default value)</li>
* <li>java.time.LocalDate (no default value)</li>
* <li>java.time.LocalDateTime (no default value)</li>
* <li>java.time.LocalTime (no default value)</li>
Expand Down Expand Up @@ -566,6 +569,7 @@ private void registerArrays(final boolean throwException, final int defaultArray
registerArrayConverter(Dimension.class, new DimensionConverter(), throwException, defaultArraySize);
registerArrayConverter(File.class, new FileConverter(), throwException, defaultArraySize);
registerArrayConverter(InetAddress.class, new InetAddressConverter(), throwException, defaultArraySize);
registerArrayConverter(Instant.class, new InstantConverter(), throwException, defaultArraySize);
registerArrayConverter(Path.class, new PathConverter(), throwException, defaultArraySize);
registerArrayConverter(java.sql.Date.class, new SqlDateConverter(), throwException, defaultArraySize);
registerArrayConverter(java.sql.Time.class, new SqlTimeConverter(), throwException, defaultArraySize);
Expand Down Expand Up @@ -602,6 +606,7 @@ private void registerArrays(final boolean throwException, final int defaultArray
* <li>{@link java.util.Date.class} - {@link DateConverter}</li>
* <li>{@link java.util.Calendar.class} - {@link CalendarConverter}</li>
* <li>{@code File.class} - {@link FileConverter}</li>
* <li>{@code Instant.class} - {@link InstantConverter}</li>
* <li>{@code Path.class} - {@link PathConverter}</li>
* <li>{@link java.sql.Date.class} - {@link SqlDateConverter}</li>
* <li>{@link java.sql.Time.class} - {@link SqlTimeConverter}</li>
Expand Down Expand Up @@ -637,6 +642,7 @@ private void registerOther(final boolean throwException) {
register(Calendar.class, throwException ? new CalendarConverter() : new CalendarConverter(null));
register(File.class, throwException ? new FileConverter() : new FileConverter(null));
register(InetAddress.class, throwException ? new InetAddressConverter() : new InetAddressConverter(null));
register(Instant.class, throwException ? new InstantConverter() : new InstantConverter(null));
register(Path.class, throwException ? new PathConverter() : new PathConverter(null));
register(java.sql.Date.class, throwException ? new SqlDateConverter() : new SqlDateConverter(null));
register(java.sql.Time.class, throwException ? new SqlTimeConverter() : new SqlTimeConverter(null));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,19 @@
* <p>
* Can be configured to either return a <i>default value</i> or throw a
* {@code ConversionException} if a conversion error occurs.
* </p>
*
* <p>
* Also accepts hexadecimal {@link String strings} if values are prefixed with {@link #HEX_PREFIX}.
* </p>
*
* @since 1.3
*/
public final class CharacterConverter extends AbstractConverter<Character> {

/** Determines if an input is a hexadecimal {@link String}. */
private static final String HEX_PREFIX = "0x";

/**
* Constructs a <b>java.lang.Character</b> <i>Converter</i> that throws
* a {@code ConversionException} if an error occurs.
Expand Down Expand Up @@ -84,7 +92,19 @@ protected String convertToString(final Object value) {
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Exception {
if (Character.class.equals(type) || Character.TYPE.equals(type)) {
return type.cast(Character.valueOf(value.toString().charAt(0)));
final String stringValue = toString(value);

if (stringValue.isEmpty()) {
throw new IllegalArgumentException("Value must not be empty");
}

if (stringValue.length() > 2 && stringValue.substring(0, 2).equalsIgnoreCase(HEX_PREFIX)) {
final String substring = stringValue.substring(HEX_PREFIX.length());
final int hex = Integer.parseInt(substring, 16);
return type.cast((char) hex);
}

return type.cast(stringValue.charAt(0));
}

throw conversionException(type, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
Expand Down Expand Up @@ -152,6 +153,8 @@ protected String convertToString(final Object value) {
} else if (value instanceof TemporalAccessor) {
// Backstop for other TemporalAccessor implementations.
date = Date.from(Instant.from(((TemporalAccessor) value)));
} else if (value instanceof Instant) {
date = Date.from((Instant) value);
}

String result = null;
Expand Down Expand Up @@ -188,6 +191,7 @@ protected String convertToString(final Object value) {
* <li>{@link java.time.LocalDate}</li>
* <li>{@link java.time.LocalDateTime}</li>
* <li>{@link java.time.OffsetDateTime}</li>
* <li>{@link java.time.Instant}</li>
* <li>{@link java.time.ZonedDateTime}</li>
* <li>{@link java.sql.Date}</li>
* <li>{@link java.sql.Time}</li>
Expand Down Expand Up @@ -269,6 +273,11 @@ protected <T> T convertToType(final Class<T> targetType, final Object value) thr
return toDate(targetType, date.toInstant().toEpochMilli());
}

if (value instanceof Instant) {
final Instant date = (Instant) value;
return toDate(targetType, date.toEpochMilli());
}

// Convert all other types to String & handle
final String stringValue = toTrim(value);
if (stringValue.isEmpty()) {
Expand Down Expand Up @@ -587,6 +596,10 @@ private <T> T toDate(final Class<T> type, final long value) {
return type.cast(offsetDateTime);
}

if (type.equals(Instant.class)) {
return type.cast(Instant.ofEpochMilli(value));
}

// java.util.Calendar
if (type.equals(Calendar.class)) {
Calendar calendar = null;
Expand Down Expand Up @@ -620,6 +633,7 @@ private <T> T toDate(final Class<T> type, final long value) {
* <li>{@link java.sql.Date}</li>
* <li>{@link java.sql.Time}</li>
* <li>{@link java.sql.Timestamp}</li>
* <li>{@link java.time.Instant}</li>
* </ul>
* <p>
* <strong>N.B.</strong> No default String conversion
Expand Down Expand Up @@ -663,6 +677,14 @@ private <T> T toDate(final Class<T> type, final String value) {
}
}

if (type.equals(Instant.class)) {
try {
return type.cast(Instant.parse(value));
} catch (final DateTimeParseException ex) {
throw new ConversionException("String must be in ISO-8601 format to create a java.time.Instant");
}
}

final String msg = toString(getClass()) + " does not support default String to '"
+ toString(type) + "' conversion.";
if (log().isWarnEnabled()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public DurationConverter(final Duration defaultValue) {
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
if (Duration.class.equals(type)) {
return type.cast(Duration.parse((String.valueOf(value))));
return type.cast(Duration.parse(toString(value)));
}

throw conversionException(type, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
*/
package org.apache.commons.beanutils2.converters;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* {@link org.apache.commons.beanutils2.Converter} implementation that handles conversion
* to and from <b>java.lang.Enum</b> objects.
Expand All @@ -30,6 +33,11 @@
*/
public final class EnumConverter<E extends Enum<E>> extends AbstractConverter<Enum<E>> {

/** Matches if a given input is an enum string. */
private static final Pattern ENUM_PATTERN = Pattern.compile(
"((?:[a-z\\d.]+)*)\\.([A-Za-z\\d]+)[#.]([A-Z\\d_]+)"
);

/**
* Constructs a <b>java.lang.Enum</b> <i>Converter</i> that throws
* a {@code ConversionException} if an error occurs.
Expand Down Expand Up @@ -63,15 +71,37 @@ public EnumConverter(final Enum<E> defaultValue) {
@Override
protected <R> R convertToType(final Class<R> type, final Object value) throws Throwable {
if (Enum.class.isAssignableFrom(type)) {
final String enumValue = String.valueOf(value);
final R[] constants = type.getEnumConstants();
if (constants == null) {
throw conversionException(type, value);
final String stringValue = toString(value);

try {
return type.cast((Enum) Enum.valueOf((Class) type, stringValue));
} catch (IllegalArgumentException ex) {
// Continue to check fully qualified name.
}

Matcher matcher = ENUM_PATTERN.matcher(stringValue);

if (!matcher.matches()) {
throw new IllegalArgumentException(
"Value doesn't follow Enum naming convention, expecting value like: java.time.DayOfWeek.MONDAY");
}
for (final R candidate : constants) {
if (((Enum)candidate).name().equalsIgnoreCase(enumValue)) {
return candidate;

String className = matcher.group(1) + "." + matcher.group(2);

try {
Class classForName = Class.forName(className);

if (!classForName.isEnum()) {
throw new IllegalArgumentException("Value isn't an enumerated type.");
}

if (!type.isAssignableFrom(classForName)) {
throw new IllegalArgumentException("Class is not the required type.");
}

return type.cast((Enum) Enum.valueOf(classForName, matcher.group(3)));
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Class \"" + className + "\" doesn't exist.", ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils2.converters;

import java.time.Instant;

/**
* {@link org.apache.commons.beanutils2.Converter} implementation that handles conversion
* to and from {@link Instant} objects.
*
* <p>
* Can be configured to either return a <i>default value</i> or throw a
* {@code ConversionException} if a conversion error occurs.
* </p>
*
* @since 2.0
* @see Instant
*/
public final class InstantConverter extends DateTimeConverter<Instant> {

/**
* Constructs a {@link Instant} <i>Converter</i> that throws a {@code ConversionException} if an
* error occurs.
*/
public InstantConverter() {
super();
}

/**
* Constructs a {@link Instant} <i>Converter</i> that returns a default value if an error occurs.
*
* @param defaultValue The default value to be returned if the value to be converted is missing or an error occurs
* converting the value.
*/
public InstantConverter(final Instant defaultValue) {
super(defaultValue);
}

/**
* Gets the default type this {@code Converter} handles.
*
* @return The default type this {@code Converter} handles.
*/
@Override
protected Class<Instant> getDefaultType() {
return Instant.class;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public PeriodConverter(final Period defaultValue) {
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
if (Period.class.equals(type)) {
return type.cast(Period.parse((String.valueOf(value))));
return type.cast(Period.parse(toString(value)));
}

throw conversionException(type, value);
Expand Down
Loading

0 comments on commit d7c8bba

Please sign in to comment.