Skip to content

Commit

Permalink
Update CustomPlaceholderResolver to receive bean
Browse files Browse the repository at this point in the history
To be able to do more complex operations,
`CustomPlaceholderResolver` is refactored to also
receive the bean of the resolver
  • Loading branch information
AntonOellerer committed Dec 21, 2021
1 parent f36aeea commit 8511202
Show file tree
Hide file tree
Showing 6 changed files with 25 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
public interface CustomPlaceholderRegistry {
void addHandler(String placeholder, Class<? extends CustomWordPlaceholderData> customWordPlaceholderDataClass);

Optional<PlaceholderData> resolve(String placeholder)
Optional<PlaceholderData> resolve(String placeholder, Object object)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException;

boolean governs(String placeholderName);
boolean governs(String placeholderName, Object object);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void addHandler(String placeholder, Class<? extends CustomWordPlaceholder
}

@Override
public Optional<PlaceholderData> resolve(String placeholder)
public Optional<PlaceholderData> resolve(String placeholder, Object unused)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (customWordPlaceholderDataMap.containsKey(placeholder)) {
return Optional.of(customWordPlaceholderDataMap.get(placeholder).getConstructor().newInstance());
Expand All @@ -27,7 +27,7 @@ public Optional<PlaceholderData> resolve(String placeholder)
}

@Override
public boolean governs(String placeholderName) {
public boolean governs(String placeholderName, Object unused) {
return customWordPlaceholderDataMap.containsKey(placeholderName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
*/
public class FutureReflectionResolver extends ReflectionResolver {
private static final Logger logger = LogManager.getLogger();
private final PlaceholderMapper placeholderMapper = new PlaceholderMapperImpl();

public FutureReflectionResolver(Object value) {
this(value, new CustomPlaceholderRegistryImpl()); //NoOp CustomPlaceholderRegistry
Expand All @@ -34,26 +33,11 @@ public FutureReflectionResolver(Object value, CustomPlaceholderRegistry customPl
super(value, customPlaceholderRegistry);
}


@Override
public Optional<PlaceholderData> resolve(String placeholderName, Locale locale) {
logger.debug("Trying to resolve placeholder {}", placeholderName);
placeholderName = placeholderMapper.map(placeholderName);
Optional<PlaceholderData> result = Optional.empty();
for (String property : placeholderName.split("\\.")) {
result = result.isEmpty()
? doResolve(property, locale)
: result
.flatMap(r -> r.stream().findAny())
.flatMap(r -> r.resolve(property, locale));
}
return result;
}

private Optional<PlaceholderData> doResolve(String placeholderName, Locale locale) {
public Optional<PlaceholderData> doResolve(String placeholderName, Locale locale) {
try {
if (customPlaceholderRegistry.governs(placeholderName)) {
return customPlaceholderRegistry.resolve(placeholderName);
if (customPlaceholderRegistry.governs(placeholderName, bean)) {
return customPlaceholderRegistry.resolve(placeholderName, bean);
}
var property = getBeanProperty(placeholderName);
if (property == null) {
Expand Down
23 changes: 18 additions & 5 deletions src/main/java/com/docutools/jocument/impl/ReflectionResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.docutools.jocument.CustomPlaceholderRegistry;
import com.docutools.jocument.PlaceholderData;
import com.docutools.jocument.PlaceholderMapper;
import com.docutools.jocument.PlaceholderResolver;
import com.docutools.jocument.annotations.Format;
import com.docutools.jocument.annotations.Image;
Expand Down Expand Up @@ -48,6 +49,8 @@ public class ReflectionResolver extends PlaceholderResolver {
protected final Object bean;
private final PropertyUtilsBean pub = new PropertyUtilsBean();
protected final CustomPlaceholderRegistry customPlaceholderRegistry;
private final PlaceholderMapper placeholderMapper = new PlaceholderMapperImpl();


public ReflectionResolver(Object value) {
this(value, new CustomPlaceholderRegistryImpl()); //NoOp CustomPlaceholderRegistry
Expand Down Expand Up @@ -124,21 +127,31 @@ private static DateTimeFormatter toDateTimeFormatter(Format format) {
@Override
public Optional<PlaceholderData> resolve(String placeholderName, Locale locale) {
logger.debug("Trying to resolve placeholder {}", placeholderName);
placeholderName = placeholderMapper.map(placeholderName);
Optional<PlaceholderData> result = Optional.empty();
for (String property : placeholderName.split("\\.")) {
result = result.isEmpty()
? doResolve(property, locale)
: result
.flatMap(r -> r.stream().findAny())
.flatMap(r -> r.resolve(property, locale));
.flatMap(r -> r.stream().findAny())
.flatMap(r -> r.resolve(property, locale));
}
return result;
}

private Optional<PlaceholderData> doResolve(String placeholderName, Locale locale) {
/**
* Method resolving placeholders for the reflection resolver.
* incredibly ugly, but since doResolve is public, the overriden method of FutureReflectionResolver is used when necessary
* could/should maybe be made a bit more explicit by defining a common superinterface
*
* @param placeholderName The name of the placeholder
* @param locale The locale to user for localization
* @return An optional containing `PlaceholderData` if it could be resolved
*/
public Optional<PlaceholderData> doResolve(String placeholderName, Locale locale) {
try {
if (customPlaceholderRegistry.governs(placeholderName)) {
return customPlaceholderRegistry.resolve(placeholderName);
if (customPlaceholderRegistry.governs(placeholderName, bean)) {
return customPlaceholderRegistry.resolve(placeholderName, bean);
}
var property = getBeanProperty(placeholderName);
if (property == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,40 +224,6 @@ void shouldResolveLegacy() throws IOException, InterruptedException {
assertThat(documentWrapper.bodyElement(11).asParagraph().text(), equalTo("And that’s that."));
}

@Test
@DisplayName("Do not fail when placeholder mapping can not be opened.")
void shouldNotFailOnUnavailableMappingFile() throws InterruptedException {
// Arrange
PlaceholderMapperImpl.configure("/does/not/exist");
Template template = Template.fromClassPath("/templates/word/UserProfileTemplate.docx")
.orElseThrow();
PlaceholderResolver resolver = new ReflectionResolver(SampleModelData.PICARD_PERSON);

// Act
Document document = template.startGeneration(resolver);
document.blockUntilCompletion(60000L); // 1 minute

// Assert
assertThat(document.completed(), is(true));
}

@Test
@DisplayName("Do not fail when placeholder mapping can not be opened.")
void shouldNotFailOnNullMappingFile() throws InterruptedException {
// Arrange
PlaceholderMapperImpl.configure(null);
Template template = Template.fromClassPath("/templates/word/UserProfileTemplate.docx")
.orElseThrow();
PlaceholderResolver resolver = new ReflectionResolver(SampleModelData.PICARD_PERSON);

// Act
Document document = template.startGeneration(resolver);
document.blockUntilCompletion(60000L); // 1 minute

// Assert
assertThat(document.completed(), is(true));
}

@Test
@DisplayName("Resolve future placeholder")
void shouldResolveFuture() throws IOException, InterruptedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@ protected void transform(IBodyElement placeholder, XWPFDocument document, Genera
var paragraph = document.insertNewParagraph(WordUtilities.openCursor(placeholder).orElseThrow());
paragraph.createRun().setText("Live your life not celebrating victories, but overcoming defeats.");
WordUtilities.removeIfExists(placeholder);

}
}

0 comments on commit 8511202

Please sign in to comment.