Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow use of LoaderOptions.allowDuplicateKeys to enforce duplicate key detection #415

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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