Encode non-ascii text (#79)

* Encode non-ascii text

* Add test
This commit is contained in:
Egor Cherniak 2024-07-24 20:01:01 +03:00 committed by GitHub
parent 2053895fb3
commit e9c4990e58
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 33 additions and 4 deletions

View File

@ -13,13 +13,16 @@ import dev.vality.woody.api.flow.error.*;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.nio.charset.Charset;
import java.util.Objects; import java.nio.charset.CharsetEncoder;
import java.util.Optional; import java.nio.charset.StandardCharsets;
import java.util.*;
public class ErrorMapping { public class ErrorMapping {
private static final String DEFAULT_PATTERN_REASON = "'%s' - '%s'"; private static final String DEFAULT_PATTERN_REASON = "'%s' - '%s'";
private static final String DEFAULT_BASE64_PREFIX = "base64:";
private static final CharsetEncoder ASCII_ENCODER = StandardCharsets.US_ASCII.newEncoder();
/** /**
* Pattern for reason failure * Pattern for reason failure
@ -137,7 +140,26 @@ public class ErrorMapping {
code, description, state); code, description, state);
var errorDefinition = new WErrorDefinition(WErrorSource.INTERNAL); var errorDefinition = new WErrorDefinition(WErrorSource.INTERNAL);
errorDefinition.setErrorType(WErrorType.UNEXPECTED_ERROR); errorDefinition.setErrorType(WErrorType.UNEXPECTED_ERROR);
errorDefinition.setErrorReason(String.format("code = %s, description = %s", code, description)); errorDefinition.setErrorReason(String.format("code = %s, description = %s",
makeCompatibleWithHttpHeader(code),
makeCompatibleWithHttpHeader(description)));
return new WRuntimeException(errorMessage, errorDefinition); return new WRuntimeException(errorMessage, errorDefinition);
} }
private String makeCompatibleWithHttpHeader(String text) {
if (text == null || !containsNonAsciiSymbols(text)) {
return text;
}
return DEFAULT_BASE64_PREFIX +
Base64.getEncoder().withoutPadding().encodeToString(text.getBytes(StandardCharsets.UTF_8));
}
private boolean containsNonAsciiSymbols(String text) {
for (char c : text.toCharArray()) {
if (!ASCII_ENCODER.canEncode(c)) {
return true;
}
}
return false;
}
} }

View File

@ -33,6 +33,13 @@ public class ErrorMappingTest {
errorMappingFull.mapFailure("00001").toString()); errorMappingFull.mapFailure("00001").toString());
} }
@Test
public void nonAsciiTest() {
var errorMappingFull = new ErrorMapping("'%s' - '%s'", List.of());
var exception = assertThrows(WRuntimeException.class, () -> errorMappingFull.mapFailure("ы"));
assertEquals("code = base64:0Ys, description = null", exception.getErrorDefinition().getErrorReason());
}
@Test @Test
public void testNullDesc() { public void testNullDesc() {
Error error = new Error(); Error error = new Error();