1 package org.apache.maven.doxia.linkcheck.validation;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.Reader;
25 import java.util.Locale;
26
27 import org.apache.maven.doxia.linkcheck.model.LinkcheckFileResult;
28 import org.codehaus.plexus.util.IOUtil;
29 import org.codehaus.plexus.util.ReaderFactory;
30 import org.codehaus.plexus.util.StringUtils;
31 import org.codehaus.plexus.util.WriterFactory;
32
33
34
35
36
37
38
39
40 public final class FileLinkValidator
41 implements LinkValidator
42 {
43 private String encoding;
44
45
46
47
48 public FileLinkValidator( String encoding )
49 {
50 if ( StringUtils.isEmpty( encoding ) )
51 {
52 encoding = WriterFactory.UTF_8;
53 }
54 this.encoding = encoding;
55 }
56
57
58 public LinkValidationResult validateLink( LinkValidationItem lvi )
59 {
60 File f = getFile( lvi );
61
62 if ( f.exists() )
63 {
64 return new LinkValidationResult( LinkcheckFileResult.VALID_LEVEL, false, "" );
65 }
66
67 return new LinkValidationResult( LinkcheckFileResult.ERROR_LEVEL, false, "doesn't exist." );
68 }
69
70
71 public Object getResourceKey( LinkValidationItem lvi )
72 {
73 String link = lvi.getLink();
74
75
76
77 if ( link.toLowerCase( Locale.ENGLISH ).startsWith( "http://" )
78 || link.toLowerCase( Locale.ENGLISH ).startsWith( "https://" ) || link.indexOf( '@' ) != -1
79 || link.startsWith( "/" ) )
80 {
81 return null;
82 }
83
84 return getFile( lvi ).getAbsolutePath();
85 }
86
87
88
89
90
91
92
93
94
95
96
97 private File getFile( LinkValidationItem lvi )
98 {
99 String link = lvi.getLink();
100
101 if ( link.indexOf( '#' ) != -1 )
102 {
103 String anchor = link.substring( link.indexOf( '#' ) + 1 );
104 link = link.substring( 0, link.indexOf( '#' ) );
105
106
107 if ( link.trim().length() == 0 )
108 {
109
110 String content = read( lvi.getSource(), encoding );
111 if ( Anchors.matchesAnchor( content, anchor ) )
112 {
113 return lvi.getSource();
114 }
115
116
117 return new File( lvi.getLink() );
118 }
119
120
121 String content = read( new File( lvi.getSource().getParentFile(), link ), encoding );
122 if ( Anchors.matchesAnchor( content, anchor ) )
123 {
124 return new File( lvi.getSource().getParentFile(), link );
125 }
126
127
128 return new File( lvi.getLink() );
129 }
130
131 if ( link.indexOf( '?' ) != -1 )
132 {
133 link = link.substring( 0, link.indexOf( '?' ) );
134
135
136
137 if ( link.trim().length() == 0 )
138 {
139 return lvi.getSource();
140 }
141 }
142
143 return new File( lvi.getSource().getParentFile(), link );
144 }
145
146
147
148
149
150
151 private static String read( File f, String encoding )
152 {
153 Reader reader = null;
154 try
155 {
156 reader = ReaderFactory.newReader( f, encoding );
157 return IOUtil.toString( reader );
158 }
159 catch ( IOException e )
160 {
161
162 }
163 finally
164 {
165 IOUtil.close( reader );
166 }
167
168 return null;
169 }
170 }