Skip to content

Commit

Permalink
feat: Use LoaderOptions allowDuplicateKeys to enforce duplicate key d…
Browse files Browse the repository at this point in the history
…etection. (#415)
  • Loading branch information
nielsbasjes committed Apr 14, 2023
1 parent 38751e4 commit 1a3b86d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.fasterxml.jackson.dataformat.yaml;

import com.fasterxml.jackson.core.StreamReadFeature;
import org.yaml.snakeyaml.DumperOptions;

import com.fasterxml.jackson.core.TSFBuilder;
Expand Down Expand Up @@ -226,6 +227,11 @@ public YAMLFactoryBuilder yamlVersionToWrite(DumperOptions.Version v) {
*/
public YAMLFactoryBuilder loaderOptions(LoaderOptions loaderOptions) {
_loaderOptions = loaderOptions;

// If the user wants to block duplicate keys this needs to be set in a different way to work
if (!_loaderOptions.isAllowDuplicateKeys()) {
enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION);
}
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.ModuleTestBase;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.yaml.snakeyaml.LoaderOptions;

public class ParserDupHandlingTest extends ModuleTestBase
{
Expand Down Expand Up @@ -33,6 +34,17 @@ public void testDupChecksEnabled() throws Exception
_verifyDupsFail(mapper, YAML_WITH_DUPS, true);
}

public void testDupChecksEnabledLoaderOptions() throws Exception
{
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setAllowDuplicateKeys(false);
YAMLFactory f = YAMLFactory.builder().loaderOptions(loaderOptions).build();

ObjectMapper mapper = new ObjectMapper(f);
_verifyDupsFail(mapper, YAML_WITH_DUPS, false);
_verifyDupsFail(mapper, YAML_WITH_DUPS, true);
}

private void _verifyDupsOk(ObjectMapper mapper, String doc, boolean useBytes) throws Exception
{
JsonParser p = useBytes ? mapper.getFactory().createParser(new ByteArrayInputStream(doc.getBytes("UTF-8")))
Expand Down

0 comments on commit 1a3b86d

Please sign in to comment.