001/*- 002 * #%L 003 * Smile CDR - CDR 004 * %% 005 * Copyright (C) 2016 - 2026 Smile CDR, Inc. 006 * %% 007 * All rights reserved. 008 * #L% 009 */ 010package ca.cdr.api.hl7v2.util; 011 012import ca.uhn.hl7v2.model.primitive.FormattedTextEncoder; 013import org.apache.commons.lang3.StringUtils; 014 015/** 016 * <p>Utility class for encoding the following character sequences contained in HL7v2 FT (formatted text) fields:</p> 017 * <ul> 018 * <li>\h\ \n\ - Bold text highlighting</li> 019 * <li>\.br\ - Line break</li> 020 * <li>\.ce\ - Center line</li> 021 * <li>\.fi\ - Fill mode (word wrap)</li> 022 * <li>\.nf\ - No-fill mode (no wrap)</li> 023 * <li>\.in X\ - Indent by X spaces</li> 024 * <li>\.ti X\ - Temporarily indent by X spaces</li> 025 * <li>\.sk X\ - Skip X spaces to the right</li> 026 * <li>\.sp X\ - Skip X vertical spaces</li> 027 * </ul> 028 * <p>See {@link OutputFormat} for available output formats.</p> 029 */ 030public final class Hl7v2FormattedTextEncoder { 031 032 /** 033 * Output formats for {@link Hl7v2FormattedTextEncoder} 034 */ 035 public enum OutputFormat { 036 XHTML, 037 MARKDOWN 038 } 039 040 private Hl7v2FormattedTextEncoder() { 041 // Utility class 042 } 043 044 /** 045 * Encodes a String with HL7v2 FT character sequences to the specified output format 046 * @param theFormattedText - A String containing HL7v2 FT character sequences to be encoded 047 * @param theOutputFormat - The {@link OutputFormat} 048 * @return A String with HL7v2 FT character sequences encoded 049 */ 050 public static String encode(String theFormattedText, OutputFormat theOutputFormat) { 051 if (StringUtils.isBlank(theFormattedText)) { 052 return ""; 053 } 054 055 FormattedTextEncoder encoder = FormattedTextEncoder.getInstanceHtml(); 056 String htmlResult = encoder.encode(theFormattedText); 057 058 return switch (theOutputFormat) { 059 case XHTML -> htmlResult; 060 case MARKDOWN -> convertXhtmlToMarkdown(htmlResult); 061 default -> throw new IllegalArgumentException("Cannot handle output format: %s".formatted(theOutputFormat)); 062 }; 063 } 064 065 private static String convertXhtmlToMarkdown(String theXhtml) { 066 return FormattedTextMarkdownConverter.convert(theXhtml).trim(); 067 } 068}