Skip to content

Commit

Permalink
Fix: IllegalArgument Exception in String converter
Browse files Browse the repository at this point in the history
Signed-off-by: Asif Sohail Mohammed <[email protected]>
  • Loading branch information
asifsmohammed committed Aug 15, 2023
1 parent a5c4fe2 commit a3b5f91
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@

package org.opensearch.dataprepper.typeconverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

import static org.opensearch.dataprepper.logging.DataPrepperMarkers.EVENT;

public class StringConverter implements TypeConverter<String> {
public String convert(Object source) throws IllegalArgumentException {
private static final Logger LOG = LoggerFactory.getLogger(StringConverter.class);

public String convert(final Object source) {
if (source instanceof Long) {
return Long.toString(((Number)source).longValue());
}
Expand All @@ -25,6 +34,11 @@ public String convert(Object source) throws IllegalArgumentException {
if (source instanceof String) {
return (String)source;
}
throw new IllegalArgumentException("Unsupported type conversion");
LOG.error(EVENT, "Unable to convert {} to String", source);
if (Objects.nonNull(source)) {
return source.toString();
} else {
return "";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@

import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class StringConverterTests {
@Test
Expand Down Expand Up @@ -64,9 +63,25 @@ void testStringToStringConversion() {
assertThat(converter.convert(strConstant), equalTo(strConstant));
}
@Test
void testInvalidStringConversion() {
void testNullValueStringConversion() {
StringConverter converter = new StringConverter();
final Map<Object, Object> map = Collections.emptyMap();
assertThrows(IllegalArgumentException.class, () -> converter.convert(map));
final String expectedString = "";
assertThat(converter.convert(null), equalTo(expectedString));
}

@Test
void testMapToStringConversion() {
StringConverter converter = new StringConverter();
final Map<Object, Object> map = Map.of("testKey", "testValue");
final String expectedString = "{testKey=testValue}";
assertThat(converter.convert(map), equalTo(expectedString));
}

@Test
void testListToStringConversion() {
StringConverter converter = new StringConverter();
final List<Object> list = List.of("listItem1", "listItem2");
final String expectedString = "[listItem1, listItem2]";
assertThat(converter.convert(list), equalTo(expectedString));
}
}

0 comments on commit a3b5f91

Please sign in to comment.