FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
javaxt-express/src/javaxt/express/cms/WebSite.java at master · javaxt-project/javaxt-express · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
javaxt-project
/
javaxt-express
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
javaxt-express
/
src
/
javaxt
/
express
/
cms
/
WebSite.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
1694 lines (1336 loc) · 58.9 KB
Breadcrumbs
javaxt-express
/
src
/
javaxt
/
express
/
cms
/
WebSite.java
Copy path
File metadata and controls
1694 lines (1336 loc) · 58.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package
javaxt
.
express
.
cms
;
import
javaxt
.
express
.
FileManager
;
import
javaxt
.
express
.
utils
.
Git
;
import
javaxt
.
express
.
utils
.
MDParser
;
import
javaxt
.
http
.
servlet
.*;
import
javaxt
.
http
.
websocket
.*;
import
javaxt
.
utils
.
Console
;
import
java
.
io
.
IOException
;
import
java
.
util
.*;
import
java
.
util
.
concurrent
.
ConcurrentHashMap
;
import
java
.
util
.
concurrent
.
atomic
.
AtomicLong
;
//******************************************************************************
//** WebSite Servlet
//******************************************************************************
/**
* Servlet used to serve up files and images for a website. HTML pages are
* assembled on-the-fly using an HTML template and content files. Keywords
* in the content files and template are substituted at runtime. Assembled
* files are cached by clients using last modified dates.
*
******************************************************************************/
public
abstract
class
WebSite
extends
HttpServlet
{
protected
static
Console
console
=
new
Console
();
private
javaxt
.
io
.
Directory
web
;
private
FileManager
fileManager
;
private
javaxt
.
io
.
File
template
;
private
Tabs
tabs
;
private
String
companyName
;
private
String
companyAcronym
;
private
String
author
;
private
String
keywords
;
private
Redirects
redirects
;
private
ConcurrentHashMap
<
String
,
Content
>
mdCache
;
private
Git
git
;
private
ConcurrentHashMap
<
Long
,
WebSocketListener
>
wsListeners
;
private
AtomicLong
wsID
;
private
ConcurrentHashMap
<
String
,
Long
>
recentSaves
;
//paths saved via browser, to avoid double-commit
private
String
[]
fileExtensions
=
new
String
[]{
".html"
,
".txt"
,
".md"
};
/** */
private
String
[]
defaultFileNames
=
new
String
[]{
"home"
,
"index"
,
"Overview"
};
private
String
[]
contentFolders
=
new
String
[]{
"content"
,
"documentation"
,
//javaxt.com
"wiki"
//legacy
};
//**************************************************************************
//** Constructor
//**************************************************************************
/** Used to instantiate the website.
*
* @param web Directory that contains html files, css, javascript, images,
* etc. Assumes the template, tabs, and redirects are found in the style
* folder.
*
* @param servletPath URL path to the website (relative to the hostname).
*/
public
WebSite
(
javaxt
.
io
.
Directory
web
,
String
servletPath
){
this
.
web
=
web
;
this
.
template
=
new
javaxt
.
io
.
File
(
web
+
"style/template.html"
);
this
.
tabs
=
new
Tabs
(
new
javaxt
.
io
.
File
(
web
+
"style/tabs.txt"
));
this
.
redirects
=
new
Redirects
(
new
javaxt
.
io
.
File
(
web
+
"style/redirects.txt"
));
setServletPath
(
servletPath
);
this
.
fileManager
=
new
FileManager
(
web
);
this
.
mdCache
=
new
ConcurrentHashMap
<>();
this
.
git
=
new
Git
(
web
);
this
.
wsListeners
=
new
ConcurrentHashMap
<>();
this
.
wsID
=
new
AtomicLong
(
0
);
this
.
recentSaves
=
new
ConcurrentHashMap
<>();
initFileWatcher
();
}
//**************************************************************************
//** Constructor
//**************************************************************************
public
WebSite
(
javaxt
.
io
.
Directory
web
){
this
(
web
,
"/"
);
}
//**************************************************************************
//** getWebDirectory
//**************************************************************************
public
javaxt
.
io
.
Directory
getWebDirectory
(){
return
web
;
}
//**************************************************************************
//** getFileManager
//**************************************************************************
public
FileManager
getFileManager
(){
return
fileManager
;
}
//**************************************************************************
//** getFileExtensions
//**************************************************************************
/** Returns a list of known/supported file extensions supported by this
* class. Contents of these files will be injected into a template and
* rendered to the client.
*/
public
String
[]
getFileExtensions
(){
return
fileExtensions
;
}
//**************************************************************************
//** setCompanyName
//**************************************************************************
public
void
setCompanyName
(
String
companyName
){
this
.
setCompanyName
(
companyName
,
null
);
}
public
void
setCompanyName
(
String
companyName
,
String
companyAcronym
){
this
.
companyName
=
companyName
;
this
.
companyAcronym
=
companyAcronym
;
}
//**************************************************************************
//** getCompanyName
//**************************************************************************
public
String
getCompanyName
(){
return
companyName
;
}
//**************************************************************************
//** setAuthor
//**************************************************************************
public
void
setAuthor
(
String
author
){
this
.
author
=
author
;
}
//**************************************************************************
//** getAuthor
//**************************************************************************
public
String
getAuthor
(){
return
author
;
}
//**************************************************************************
//** getCopyright
//**************************************************************************
/** Returns the copyright text (e.g. "Copyright © 2012"). Classes that
* extend this class can override this method.
*/
protected
String
getCopyright
(){
return
"Copyright © "
+
getYear
();
}
//**************************************************************************
//** getYear
//**************************************************************************
/** Returns the current year. Commonly used in the copyright text (e.g.
* "Copyright © 2012"). Classes that extend this class can override
* this method.
*/
protected
int
getYear
(){
return
new
javaxt
.
utils
.
Date
().
getYear
();
}
//**************************************************************************
//** canEdit
//**************************************************************************
/** Returns true if the current request is authorized to edit content files.
* Returns false by default. Override this method to implement access
* control for content editing.
*/
protected
boolean
canEdit
(
HttpServletRequest
request
){
return
false
;
}
//**************************************************************************
//** beforeSave
//**************************************************************************
/** Called before a content file is saved. Override to validate or transform
* content, or throw an exception to abort the save.
*/
protected
void
beforeSave
(
javaxt
.
io
.
File
file
,
String
content
,
HttpServletRequest
request
){}
//**************************************************************************
//** onSave
//**************************************************************************
/** Called after a content file has been saved. Override to add logging,
* notifications, or other post-save actions.
*/
protected
void
onSave
(
javaxt
.
io
.
File
file
,
HttpServletRequest
request
){}
//**************************************************************************
//** onFileUpdate
//**************************************************************************
/** Called when a file in the web directory is created, modified, or deleted.
* Detected by the file watcher, not by a browser request. Override to add
* logging, indexing, or other side effects.
*
* @param file The file that changed.
* @param action One of "CREATE", "UPDATE", or "DELETE".
*/
protected
void
onFileUpdate
(
javaxt
.
io
.
File
file
,
String
action
){}
//**************************************************************************
//** processRequest
//**************************************************************************
public
void
processRequest
(
HttpServletRequest
request
,
HttpServletResponse
response
)
throws
ServletException
,
IOException
{
//Handle WebSocket upgrade
if
(
request
.
isWebSocket
()){
createWebSocket
(
request
,
response
);
return
;
}
long
t
=
System
.
currentTimeMillis
();
//Redirect as needed
java
.
net
.
URL
url
=
request
.
getURL
();
if
(
redirect
(
url
,
response
))
return
;
//Upgrade to HTTPS if we can...
if
(
this
.
supportsHttps
()){
response
.
setHeader
(
"Content-Security-Policy"
,
"upgrade-insecure-requests"
);
String
upgradeRequest
=
request
.
getHeader
(
"Upgrade-Insecure-Requests"
);
if
(
upgradeRequest
!=
null
&&
upgradeRequest
.
equals
(
"1"
)){
if
(!
url
.
getProtocol
().
equalsIgnoreCase
(
"https"
)){
String
location
=
url
.
toString
();
location
=
"https"
+
location
.
substring
(
location
.
indexOf
(
":"
));
response
.
setStatus
(
307
);
//response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
response
.
setHeader
(
"Vary"
,
"Upgrade-Insecure-Requests"
);
response
.
setHeader
(
"Location"
,
location
);
return
;
}
}
}
//Get path from URL, excluding servlet path and leading "/" character
String
path
=
getPath
(
url
);
//Special case for Certbot. When generating certificates using the
//certonly command, Certbot creates a hidden directory in the web root.
//The web server must return the files in this hidden directory. However,
//the filemanager does not allow access to hidden directories so we need
//to handle these requests manually.
if
(
path
.
startsWith
(
".well-known"
)){
console
.
log
(
path
);
java
.
io
.
File
file
=
new
java
.
io
.
File
(
web
+
path
);
console
.
log
(
file
+
"
\t
"
+
file
.
exists
());
//Send file
if
(
file
.
exists
()){
response
.
write
(
file
,
javaxt
.
io
.
File
.
getContentType
(
file
.
getName
()),
true
);
}
else
{
response
.
setStatus
(
404
);
response
.
setContentType
(
"text/plain"
);
}
return
;
}
//Send static file if we can
javaxt
.
io
.
File
file
=
getFile
(
path
);
if
(
file
!=
null
){
//Check whether the file ends in a ".html" or ".txt" extension. If so,
//check whether the file is static or if needs to be wrapped
//in a template.
boolean
sendFile
=
true
;
String
ext
=
file
.
getExtension
().
toLowerCase
();
if
(
ext
.
equals
(
"html"
)){
//Don't send html files unless they end with a </html> tag
sendFile
= !
isSnippet
(
file
);
}
else
if
(
ext
.
equals
(
"txt"
)){
//Don't send text files from any of the content folders (e.g. wiki directory)
String
filePath
=
file
.
getDirectory
().
toString
();
for
(
String
folderName
:
contentFolders
){
int
idx
=
filePath
.
indexOf
(
"/"
+
folderName
+
"/"
);
if
(
idx
>-
1
){
sendFile
=
false
;
break
;
}
}
}
if
(
sendFile
){
sendFile
(
file
,
fileManager
,
request
,
response
);
return
;
}
}
else
{
//Check whether the url path ends with a file extension. Return an error
int
idx
=
path
.
lastIndexOf
(
"/"
);
if
(
idx
>-
1
)
path
=
path
.
substring
(
idx
);
idx
=
path
.
lastIndexOf
(
"."
);
if
(
idx
>-
1
){
//console.log(path);
response
.
sendError
(
404
);
return
;
}
}
//Handle content editing requests
String
saveParam
=
request
.
getParameter
(
"save"
);
if
(
saveParam
!=
null
&&
saveParam
.
equals
(
"true"
)){
if
(
request
.
getMethod
().
equals
(
"POST"
)){
handleSave
(
request
,
response
);
return
;
}
}
String
sourceParam
=
request
.
getParameter
(
"source"
);
if
(
sourceParam
!=
null
&&
sourceParam
.
equals
(
"true"
)){
handleSource
(
request
,
response
);
return
;
}
String
historyParam
=
request
.
getParameter
(
"history"
);
if
(
historyParam
!=
null
&&
historyParam
.
equals
(
"true"
)){
handleHistory
(
request
,
response
);
return
;
}
String
diffParam
=
request
.
getParameter
(
"diff"
);
if
(
diffParam
!=
null
&&
diffParam
.
length
()>
0
){
handleDiff
(
request
,
response
,
diffParam
);
return
;
}
String
versionParam
=
request
.
getParameter
(
"version"
);
if
(
versionParam
!=
null
&&
versionParam
.
length
()>
0
){
handleVersion
(
request
,
response
,
versionParam
);
return
;
}
String
deleteParam
=
request
.
getParameter
(
"delete"
);
if
(
deleteParam
!=
null
&&
deleteParam
.
equals
(
"true"
)){
if
(
request
.
getMethod
().
equals
(
"POST"
)){
handleDelete
(
request
,
response
);
return
;
}
}
String
canEditParam
=
request
.
getParameter
(
"canEdit"
);
if
(
canEditParam
!=
null
&&
canEditParam
.
equals
(
"true"
)){
response
.
setStatus
(
200
);
response
.
setContentType
(
"text/plain"
);
response
.
write
(
canEdit
(
request
) ?
"true"
:
"false"
);
return
;
}
//If we're still here, generate html response
sendHTML
(
request
,
response
);
//console.log("processRequest", System.currentTimeMillis()-t);
}
//**************************************************************************
//** sendFile
//**************************************************************************
/** Used to send a static file to the client (e.g. css, javascript, images,
* zip files, etc). By default, this method simple calls the following:
<pre>
fileManager.sendFile(file, request, response);
</pre>
*
* Callers can override this method and add additional logic (e.g. auditing,
* authorization, logging, etc).
*/
protected
void
sendFile
(
javaxt
.
io
.
File
file
,
FileManager
fileManager
,
HttpServletRequest
request
,
HttpServletResponse
response
)
throws
ServletException
,
java
.
io
.
IOException
{
fileManager
.
sendFile
(
file
,
request
,
response
);
}
//**************************************************************************
//** getPath
//**************************************************************************
/** Returns the path part of a url, excluding servlet path and leading "/"
* character
*/
private
String
getPath
(
java
.
net
.
URL
url
){
String
path
=
url
.
getPath
();
String
servletPath
=
getServletPath
();
if
(!
servletPath
.
endsWith
(
"/"
))
servletPath
+=
"/"
;
path
=
path
.
substring
(
path
.
indexOf
(
servletPath
)).
substring
(
servletPath
.
length
());
if
(
path
.
startsWith
(
"/"
))
path
=
path
.
substring
(
1
);
return
path
;
}
//**************************************************************************
//** getFile
//**************************************************************************
/** Returns a path to a static file (e.g. css, javascript, images, zip, etc)
*/
private
javaxt
.
io
.
File
getFile
(
String
path
){
//Restrict access to the "bin" directory
if
(
path
.
toLowerCase
().
startsWith
(
"bin/"
)){
return
null
;
}
//Construct a list of possible file paths
ArrayList
<
String
>
files
=
new
ArrayList
<>();
files
.
add
(
path
);
files
.
add
(
"downloads/"
+
path
);
//Loop through possible file combinations
for
(
String
str
:
files
){
java
.
io
.
File
file
=
fileManager
.
getFile
(
str
);
if
(
file
!=
null
)
return
new
javaxt
.
io
.
File
(
file
);
}
return
null
;
}
//**************************************************************************
//** sendHTML
//**************************************************************************
/** Used to construct an html document from a template and an html snippet.
*/
private
void
sendHTML
(
HttpServletRequest
request
,
HttpServletResponse
response
)
throws
ServletException
,
IOException
{
long
t
=
System
.
currentTimeMillis
();
String
servletPath
=
getServletPath
();
if
(!
servletPath
.
endsWith
(
"/"
))
servletPath
+=
"/"
;
//Get the html file
java
.
net
.
URL
url
=
request
.
getURL
();
javaxt
.
io
.
File
file
=
getHtmlFile
(
url
);
//<--Watch for NPE!
//Check whether the client wants the raw file content or if we should
//wrap the content in a template (default).
boolean
useTemplate
=
true
;
String
templateParam
=
request
.
getParameter
(
"template"
);
if
(
templateParam
!=
null
){
if
(
templateParam
.
equals
(
"false"
)){
useTemplate
=
false
;
}
}
if
(
useTemplate
){
if
(
template
==
null
|| !
template
.
exists
())
useTemplate
=
false
;
}
//Calculate last modified date and estimated file fize
TreeSet
<
Long
>
dates
=
new
TreeSet
<>();
if
(
file
!=
null
)
dates
.
add
(
file
.
getDate
().
getTime
());
if
(
useTemplate
){
dates
.
add
(
template
.
getDate
().
getTime
());
dates
.
add
(
tabs
.
getLastModified
());
}
//Get content
Content
content
=
getContent
(
request
,
file
);
if
(
content
==
null
)
content
=
getPartialIndex
(
request
);
if
(
content
==
null
)
content
=
getPageNotFound
(
request
);
dates
.
add
(
content
.
getDate
().
getTime
());
String
html
=
content
.
getHTML
();
//Update HTML. Note that there are currently two major bottlenecks here:
//(1) html parser in "useTemplate" block and (2) the updateLinks method
//Both can be mitigated with some simple caching
long
t0
=
System
.
currentTimeMillis
();
if
(
useTemplate
){
//Instantiate html parser
long
t1
=
System
.
currentTimeMillis
();
javaxt
.
html
.
Parser
document
=
new
javaxt
.
html
.
Parser
(
html
);
//Extract Title
String
title
=
null
;
try
{
javaxt
.
html
.
Element
el
=
document
.
getElementByTagName
(
"title"
);
html
=
html
.
replace
(
el
.
getOuterHTML
(),
""
);
title
=
el
.
getInnerText
().
trim
();
}
catch
(
Exception
e
){}
if
(
title
==
null
){
try
{
title
=
document
.
getElementByTagName
(
"h1"
).
getInnerHTML
();
}
catch
(
Exception
e
){}
}
if
(
title
==
null
){
if
(
companyName
!=
null
&&
companyAcronym
!=
null
){
title
=
companyAcronym
+
" - "
+
companyName
;
}
else
{
if
(
file
!=
null
){
title
=
file
.
getName
(
false
);
for
(
String
fileName
:
defaultFileNames
){
if
(
title
.
equalsIgnoreCase
(
fileName
)){
title
=
file
.
getDirectory
().
getName
();
break
;
}
}
}
}
}
if
(
title
==
null
)
title
=
""
;
//Extract Description
String
description
=
null
;
try
{
javaxt
.
html
.
Element
el
=
document
.
getElementByTagName
(
"description"
);
html
=
html
.
replace
(
el
.
getOuterHTML
(),
""
);
description
=
el
.
getInnerHTML
();
}
catch
(
Exception
e
){}
if
(
description
==
null
)
description
=
""
;
//Extract Keywords
String
keywords
=
null
;
try
{
javaxt
.
html
.
Element
el
=
document
.
getElementByTagName
(
"keywords"
);
html
=
html
.
replace
(
el
.
getOuterHTML
(),
""
);
keywords
=
el
.
getInnerHTML
();
}
catch
(
Exception
e
){}
if
(
keywords
==
null
)
keywords
=
this
.
keywords
;
if
(
keywords
==
null
)
keywords
=
""
;
//console.log("parser", System.currentTimeMillis()-t1);
html
=
template
.
getText
().
replace
(
"<%=content%>"
,
html
);
html
=
html
.
replace
(
"<%=title%>"
,
title
);
html
=
html
.
replace
(
"<%=description%>"
,
description
);
html
=
html
.
replace
(
"<%=keywords%>"
,
keywords
);
html
=
html
.
replace
(
"<%=author%>"
,
author
==
null
?
""
:
author
);
html
=
html
.
replace
(
"<%=companyName%>"
,
companyName
==
null
?
""
:
companyName
);
html
=
html
.
replace
(
"<%=year%>"
,
getYear
()+
""
);
html
=
html
.
replace
(
"<%=copyright%>"
,
getCopyright
());
html
=
html
.
replace
(
"<%=tabs%>"
,
getTabs
(
url
.
getPath
(),
tabs
));
html
=
html
.
replace
(
"<%=breadcrumbs%>"
,
getBreadcrumbs
(
request
));
html
=
html
.
replace
(
"<%=sidebar%>"
,
getSidebar
(
request
));
html
=
html
.
replace
(
"<%=Path%>"
,
servletPath
);
html
=
updateLinks
(
html
,
dates
,
template
);
//console.log("useTemplate", System.currentTimeMillis()-t0);
}
else
{
html
=
html
.
replace
(
"<%=Path%>"
,
servletPath
);
html
=
updateLinks
(
html
,
dates
,
file
);
//console.log("updateLinks", System.currentTimeMillis()-t0);
}
//Remove any orphan tags
if
(
html
.
contains
(
"<%="
) &&
html
.
contains
(
"%>"
)){
StringBuilder
str
=
new
StringBuilder
();
String
[]
arr
=
html
.
split
(
"<%="
);
for
(
int
i
=
0
;
i
<
arr
.
length
;
i
++){
String
s
=
arr
[
i
];
if
(
i
>
0
){
int
idx
=
s
.
indexOf
(
"%>"
);
if
(
idx
>-
1
)
s
=
s
.
substring
(
idx
+
2
);
}
str
.
append
(
s
);
}
html
=
str
.
toString
();
}
//Trim the html
html
=
html
.
trim
();
//console.log("html", System.currentTimeMillis()-t);
//Get last modified date
long
lastModified
=
dates
.
last
();
//Set response headers
response
.
setStatus
(
content
.
getStatusCode
());
response
.
setContentType
(
"text/html"
);
//Send response
response
.
write
(
html
,
lastModified
);
//console.log("sendHTML", System.currentTimeMillis()-t);
}
//**************************************************************************
//** updateLinks
//**************************************************************************
/** Updates links in "script" and "link" tags with a querystring representing
* the last modified date of the file.
*/
private
String
updateLinks
(
String
html
,
TreeSet
<
Long
>
dates
,
javaxt
.
io
.
File
htmlFile
){
//Generate a list of supported tags
HashMap
<
String
,
String
>
tagsWithLinks
=
new
HashMap
();
tagsWithLinks
.
put
(
"script"
,
"src"
);
tagsWithLinks
.
put
(
"link"
,
"href"
);
//Get elements that match the supported tags
ArrayList
<
javaxt
.
html
.
Element
>
elements
=
new
ArrayList
<>();
javaxt
.
html
.
Parser
document
=
new
javaxt
.
html
.
Parser
(
html
);
for
(
String
tagName
:
tagsWithLinks
.
keySet
()){
String
linkAttr
=
tagsWithLinks
.
get
(
tagName
);
for
(
javaxt
.
html
.
Element
el
:
document
.
getElementsByTagName
(
tagName
)){
String
url
=
el
.
getAttribute
(
linkAttr
);
if
(!(
url
==
null
||
url
.
isEmpty
())){
String
t
=
url
.
toLowerCase
();
if
(!
t
.
startsWith
(
"http://"
) && !
t
.
startsWith
(
"https://"
) && !
t
.
startsWith
(
"//"
)){
elements
.
add
(
el
);
}
}
}
}
if
(
elements
.
isEmpty
())
return
html
;
//Generate an XML document
StringBuilder
str
=
new
StringBuilder
();
str
.
append
(
"<?xml version=
\"
1.0
\"
encoding=
\"
UTF-8
\"
standalone=
\"
no
\"
?>
\r
\n
"
);
str
.
append
(
"<links>"
);
for
(
javaxt
.
html
.
Element
el
:
elements
){
str
.
append
(
"
\r
\n
"
);
str
.
append
(
el
.
toString
());
if
(!
el
.
isClosed
()){
str
.
append
(
"</"
+
el
.
getName
() +
">"
);
}
}
str
.
append
(
"
\r
\n
</links>"
);
org
.
w3c
.
dom
.
Document
xml
=
javaxt
.
xml
.
DOM
.
createDocument
(
str
.
toString
());
//Update links in the XML
try
{
long
lastUpdate
=
fileManager
.
updateLinks
(
htmlFile
,
xml
);
dates
.
add
(
lastUpdate
);
}
catch
(
Exception
e
){
throw
new
RuntimeException
(
e
);
}
//Update html document
org
.
w3c
.
dom
.
Node
outerNode
=
javaxt
.
xml
.
DOM
.
getOuterNode
(
xml
);
org
.
w3c
.
dom
.
Node
[]
nodes
=
javaxt
.
xml
.
DOM
.
getNodes
(
outerNode
.
getChildNodes
());
for
(
int
i
=
0
;
i
<
nodes
.
length
;
i
++){
org
.
w3c
.
dom
.
Node
node
=
nodes
[
i
];
String
orgTag
=
elements
.
get
(
i
).
getOuterHTML
();
String
newTag
=
javaxt
.
xml
.
DOM
.
getText
(
node
);
//Replace any self-enclosing script tags as needed
String
nodeName
=
node
.
getNodeName
().
toLowerCase
();
if
(
newTag
.
endsWith
(
"/>"
) &&
nodeName
.
equals
(
"script"
)){
newTag
=
newTag
.
substring
(
0
,
newTag
.
length
()-
2
);
newTag
+=
"></"
+
nodeName
+
">"
;
}
html
=
html
.
replace
(
orgTag
,
newTag
);
}
return
html
;
}
//**************************************************************************
//** getContent
//**************************************************************************
/** Returns an html snippet found in the given file. This method can be
* overridden to generate dynamic content or to support custom tags.
*/
protected
Content
getContent
(
HttpServletRequest
request
,
javaxt
.
io
.
File
file
){
if
(
file
==
null
|| !
file
.
exists
()){
return
null
;
}
else
{
String
txt
=
file
.
getText
(
"UTF-8"
);
String
ext
=
file
.
getExtension
();
java
.
util
.
Date
date
=
file
.
getDate
();
Content
content
;
if
(
ext
.
equalsIgnoreCase
(
"md"
)){
String
key
=
file
.
toString
().
replace
(
web
.
toString
(),
""
);
synchronized
(
mdCache
){
Content
cached
=
mdCache
.
get
(
key
);
if
(
cached
!=
null
){
if
(!
date
.
after
(
cached
.
getDate
())){
return
cached
;
}
}
String
html
=
MDParser
.
toHTML
(
txt
);
content
=
new
Content
(
html
,
date
);
mdCache
.
put
(
key
,
content
);
}
}
else
{
content
=
new
Content
(
txt
,
date
);
}
return
content
;
}
}
//**************************************************************************
//** getHtmlFile
//**************************************************************************
/** Maps the requested URL to an html snippet found in an html or txt file.
* Returns null if suitable a file is not found.
*/
private
javaxt
.
io
.
File
getHtmlFile
(
java
.
net
.
URL
url
){
//Get path from url
String
path
=
url
.
getPath
();
String
servletPath
=
getServletPath
();
if
(!
servletPath
.
endsWith
(
"/"
))
servletPath
+=
"/"
;
path
=
path
.
substring
(
path
.
indexOf
(
servletPath
)).
substring
(
servletPath
.
length
());
//Remove leading and trailing "/" characters
if
(
path
.
startsWith
(
"/"
))
path
=
path
.
substring
(
1
);
if
(
path
.
endsWith
(
"/"
))
path
=
path
.
substring
(
0
,
path
.
length
()-
1
);
//Check whether the url points directly to a file (minus the file extension)
//or if the url points to a directory. If so, return the file.
String
folderPath
=
web
.
toString
();
javaxt
.
io
.
File
file
=
getFile
(
path
,
folderPath
);
if
(
file
!=
null
)
return
file
;
//If we are still here, check whether the url is missing a content folder
//in its path (e.g. "documentation", "wiki").
for
(
String
folderName
:
contentFolders
){
folderPath
=
web
+
folderName
+
"/"
;
file
=
getFile
(
path
,
folderPath
);
if
(
file
!=
null
)
return
file
;
}
return
null
;
}
//**************************************************************************
//** getFile
//**************************************************************************
private
javaxt
.
io
.
File
getFile
(
String
path
,
String
folderPath
){
//Check whether the url points directly to a file (minus the file extension)
if
(
path
.
length
()>
0
){
//System.out.println("Checking: " + folderPath + path + ".*");
for
(
String
fileExtension
:
fileExtensions
){
javaxt
.
io
.
File
file
=
new
javaxt
.
io
.
File
(
folderPath
+
path
+
fileExtension
);
if
(
file
.
exists
()){
if
(
isSnippet
(
file
))
return
file
;
}
}
}
//Check whether the url points to a directory. If so, check whether the
//directory has a welcome file (e.g. index.html, Overview.txt, etc).
javaxt
.
io
.
Directory
dir
=
new
javaxt
.
io
.
Directory
(
folderPath
+
path
);
//System.out.println("Search: " + dir + " <--" + dir.exists());
if
(
dir
.
exists
()){
for
(
String
fileName
:
defaultFileNames
){
for
(
String
fileExtension
:
fileExtensions
){
javaxt
.
io
.
File
file
=
new
javaxt
.
io
.
File
(
dir
,
fileName
+
fileExtension
);
if
(
file
.
exists
()){
if
(
isSnippet
(
file
))
return
file
;
}
}
}
}
return
null
;
}
//**************************************************************************
//** isSnippet
//**************************************************************************
private
boolean
isSnippet
(
javaxt
.
io
.
File
file
){
String
ext
=
file
.
getExtension
();
if
(
ext
!=
null
&&
ext
.
equalsIgnoreCase
(
"md"
))
return
true
;
String
str
=
file
.
getText
(
"UTF-8"
).
trim
();
return
!
str
.
endsWith
(
"</html>"
);
}
//**************************************************************************
//** getIndex
//**************************************************************************
/** Returns an html snippet with paths to all the html/txt files found in
* the given file path. Note that the file date is updated to reflect the
* most current file.
*/
protected
Content
getIndex
(
javaxt
.
io
.
File
file
){
return
getIndex
(
file
.
getDirectory
(),
file
);
}
//**************************************************************************
//** getIndex
//**************************************************************************
/** Returns an html snippet with links to all the content files found under
* the given directory (recursively). The optional "exclude" file (e.g. the
* index file itself) is omitted from the listing. When an "exclude" file is
* given, the listing is treated as a full index page and the top-most
* directory of each branch is rendered as an "h2" heading. Otherwise (e.g.
* the "not found" subtree, called with a null exclude) every directory is
* rendered as a plain list item.
*/
protected
Content
getIndex
(
javaxt
.
io
.
Directory
dir
,
javaxt
.
io
.
File
exclude
){
//Render "h2" headers only for full index pages, which are identified by
//having an index file to exclude; bare subtrees use plain list items.
boolean
useHeaders
=
exclude
!=
null
;
//Get relative path to the directory
String
path
=
dir
.
toString
();
path
=
path
.
substring
(
web
.
toString
().
length
());
path
=
path
.
replace
(
"
\\
"
,
"/"
);
if
(!
path
.
startsWith
(
"/"
))
path
=
"/"
+
path
;
if
(!
path
.
endsWith
(
"/"
))
path
+=
"/"
;
//Generate list of files and dates
List
<
javaxt
.
io
.
File
>
files
=
new
LinkedList
<>();
TreeSet
<
Long
>
dates
=
new
TreeSet
<>();
dates
.
add
((
exclude
!=
null
?
exclude
.
getDate
() :
dir
.
getDate
()).
getTime
());
for
(
javaxt
.
io
.
File
f
:
dir
.
getFiles
(
fileExtensions
,
true
)){
if
(
exclude
==
null
|| !
f
.
equals
(
exclude
)){
files
.
add
(
f
);
dates
.
add
(
f
.
getDate
().
getTime
());
}
}
//Build table of contents using ul/li tags
StringBuilder
toc
=
new
StringBuilder
();
toc
.
append
(
"<ul>
\r
\n
"
);
String
[]
prevDirs
=
new
String
[
0
];
int
len
=
dir
.
getPath
().
length
();
for
(
javaxt
.
io
.
File
f
:
files
){
String
fileName
=
f
.
getName
(
false
);
//Get the file's directory relative to the index directory,
//normalized to forward slashes with no leading slash and a
//trailing slash (e.g. "sql/ConnectionPool/")
String
relPath
=
f
.
getDirectory
().
getPath
().
substring
(
len
).
replace
(
"
\\
"
,
"/"
);
if
(
relPath
.
startsWith
(
"/"
))
relPath
=
relPath
.
substring
(
1
);
if
(
relPath
.
length
()>
0
&& !
relPath
.
endsWith
(
"/"
))
relPath
+=
"/"
;
String
[]
currDirs
=
relPath
.
length
()==
0
?
new
String
[
0
] :
relPath
.
split
(
"/"
);
//Find how many leading directories the previous and current paths share
int
common
=
0
;
while
(
common
<
prevDirs
.
length
&&
common
<
currDirs
.
length
&&
prevDirs
[
common
].
equals
(
currDirs
[
common
])){
common
++;
}
//Close the directories that are no longer part of the current path
for
(
int
i
=
prevDirs
.
length
;
i
>
common
;
i
--){
toc
.
append
(
"</ul>
\r
\n
"
);
}
//Open the directories that are new to the current path, emitting a
//header for each level (an "h2" for the top-most level)
for
(
int
i
=
common
;
i
<
currDirs
.
length
;
i
++){
String
dirName
=
currDirs
[
i
];
String
tag
= (
useHeaders
&&
i
==
0
) ?
"h2"
:
null
;
toc
.
append
(
"<li>"
);
if
(
tag
!=
null
)
toc
.
append
(
"<"
+
tag
+
">"
);
toc
.
append
(
dirName
.
replace
(
"_"
,
" "
));
if
(
tag
!=
null
)
toc
.
append
(
"</"
+
tag
+
">"
);
toc
.
append
(
"</li>
\r
\n
"
);
toc
.
append
(
"<ul>
\r
\n
"
);
}
//Append a link to the file
String
link
=
path
+
relPath
+
fileName
;
toc
.
append
(
"<li><a href=
\"
"
+
link
+
"
\"
>"
+
fileName
.
replace
(
"_"
,
" "
) +
"</a></li>
\r
\n
"
);
prevDirs
=
currDirs
;
}
//Close any directories that are still open
for
(
int
i
=
prevDirs
.
length
;
i
>
0
;
i
--){
toc
.
append
(
"</ul>
\r
\n
"
);
}
toc
.
append
(
"</ul>
\r
\n
"
);
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL