1 package org.apache.maven.tools.plugin.extractor.annotations.converter;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Map;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.apache.maven.tools.plugin.extractor.annotations.converter.tag.JavadocTagToHtmlConverter;
27 import org.apache.maven.tools.plugin.extractor.annotations.converter.tag.inline.JavadocInlineTagToHtmlConverter;
28 import org.jsoup.Jsoup;
29 import org.jsoup.nodes.Document;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import javax.inject.Inject;
34 import javax.inject.Named;
35 import javax.inject.Singleton;
36
37
38
39
40 @Named
41 @Singleton
42 public class JavadocInlineTagsToXhtmlConverter
43 {
44 private static final Logger LOG = LoggerFactory.getLogger( JavadocInlineTagsToXhtmlConverter.class );
45
46 private final Map<String, JavadocInlineTagToHtmlConverter> converters;
47
48 private static final Pattern INLINE_TAG_PATTERN = Pattern.compile( "\\{@([^\\s]*)(?:\\s([^\\}]*))?\\}" );
49 private static final int GROUP_TAG_NAME = 1;
50 private static final int GROUP_REFERENCE = 2;
51
52 @Inject
53 public JavadocInlineTagsToXhtmlConverter( Map<String, JavadocInlineTagToHtmlConverter> converters )
54 {
55 this.converters = converters;
56 }
57
58
59
60
61
62
63
64 public String convert( String text, ConverterContext context )
65 {
66 Matcher matcher = INLINE_TAG_PATTERN.matcher( text );
67 StringBuffer sb = new StringBuffer();
68 while ( matcher.find() )
69 {
70 String tagName = matcher.group( GROUP_TAG_NAME );
71 JavadocTagToHtmlConverter converter = converters.get( tagName );
72 String patternReplacement;
73 if ( converter == null )
74 {
75 patternReplacement = matcher.group( 0 ) + "<!-- unsupported tag '" + tagName + "' -->";
76 LOG.warn( "Found unsupported javadoc inline tag '{}' in {}", tagName, context.getLocation() );
77 }
78 else
79 {
80 try
81 {
82 patternReplacement = converter.convert( matcher.group( GROUP_REFERENCE ), context );
83 }
84 catch ( Throwable t )
85 {
86 patternReplacement = matcher.group( 0 ) + "<!-- error processing javadoc tag '" + tagName + "': "
87 + t.getMessage() + " -->";
88 LOG.warn( "Error converting javadoc inline tag '{}' in {}", tagName, context.getLocation(), t );
89 }
90 }
91 matcher.appendReplacement( sb, Matcher.quoteReplacement( patternReplacement ) );
92 }
93 matcher.appendTail( sb );
94 return toXHTML( sb.toString() );
95 }
96
97 static String toXHTML( String bodySnippet )
98 {
99 String html = "<html><head></head><body>" + bodySnippet + "</body>";
100 final Document document = Jsoup.parse( html );
101 document.outputSettings().syntax( Document.OutputSettings.Syntax.xml );
102 return document.body().html();
103 }
104 }