summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
blob: 50feb08639db00f8e6281499b1597d15cc44187a (plain)
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
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletOutputStream;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.logging.ILogger;

/**
 * File templates. This implementation will take
 * an HTML file with a special customer tag
 * <CMS_TEMPLATE> and replace the tag with
 * a series of javascript variable definitions
 * (depending on the servlet)
 * 
 * @version $Revision$, $Date$
 */
public class CMSTemplate extends CMSFile {

    public static final String SUFFIX = ".template";

    /*==========================================================
     * variables
     *==========================================================*/

    /* private variables */
    private String mTemplateFileName = "";
    private ILogger mLogger = CMS.getLogger();
    private long mTimeStamp;

    /* public vaiables */
    public String mPreOutput;
    public String mPostOutput;
    public static final String TEMPLATE_TAG = "<CMS_TEMPLATE>";

    /* Character set for i18n */

    /* Will be set by CMSServlet.getTemplate() */
    private String mCharset = null;

    /*==========================================================
     * constructors
     *==========================================================*/

    /**
     * Constructor
     * 
     * @param file template file to load
     * @param charset character set
     * @throws IOException if the there was an error opening the file
     */
    public CMSTemplate(File file, String charset) throws IOException, EBaseException {
        mCharset = charset;
        mAbsPath = file.getAbsolutePath();
        mLastModified = file.lastModified();
        try {
            init(file);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_CANT_LOAD_TEMPLATE", mAbsPath, e.toString()));
            throw new ECMSGWException(
                    CMS.getLogMessage("CMSGW_ERROR_LOADING_TEMPLATE"));
        }
        String content = mPreOutput + mPostOutput;

        mContent = content.getBytes(mCharset);
    }

    /*==========================================================
     * public methods
     *==========================================================*/

    /* *
     * Load the form from the file and setup the
     * pre/post output buffer if it is a template
     * file. Otherwise, only post output buffer is
     * filled.
     * @param template the template file to load
     * @return true if successful
     */
    public boolean init(File template) throws EBaseException, IOException {
        /* load template */
        String content = loadFile(template);

        if (content == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_TEMPLATE_EMPTY", mAbsPath));
            throw new ECMSGWException(
                    CMS.getLogMessage("CMSGW_TEMPLATE_NO_CONTENT_1", mAbsPath));
        }

        /* time stamp */
        Date now = CMS.getCurrentDate();

        mTimeStamp = now.getTime();

        /* if template file, find template tag substring and set
         * pre/post output string
         */
        int location = content.indexOf(TEMPLATE_TAG);

        if (location == -1) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage(
                    "CMSGW_TEMPLATE_MISSING", mAbsPath, TEMPLATE_TAG));
            throw new ECMSGWException(
                    CMS.getLogMessage("CMSGW_MISSING_TEMPLATE_TAG_2",
                            TEMPLATE_TAG, mAbsPath));
        }
        mPreOutput = content.substring(0, location);
        mPostOutput = content.substring(TEMPLATE_TAG.length() + location);

        return true;
    }

    /**
     * Write a javascript representation of 'input'
     * surrounded by SCRIPT tags to the outputstream
     * 
     * @param rout the outputstream to write to
     * @param input the parameters to write
     */
    public void renderOutput(OutputStream rout, CMSTemplateParams input)
            throws IOException {
        Enumeration<String> e = null;
        Enumeration<IArgBlock> q = null;
        IArgBlock r = null;
        boolean headerBlock = false, fixedBlock = false, queryBlock = false;
        CMSTemplateParams data = (CMSTemplateParams) input;
        HTTPOutputStreamWriter http_out = null;

        if (mCharset == null)
            http_out = new HTTPOutputStreamWriter(rout);
        else
            http_out = new HTTPOutputStreamWriter(rout, mCharset);

        try {
            templateLine out = new templateLine();

            // Output the prolog
            out.print(mPreOutput);

            // Output the header data
            out.println("<SCRIPT LANGUAGE=\"JavaScript\">");
            out.println("var header = new Object();");
            out.println("var fixed = new Object();");
            out.println("var recordSet = new Array;");
            out.println("var result = new Object();");

            // hack 
            out.println("var httpParamsCount = 0;");
            out.println("var httpHeadersCount = 0;");
            out.println("var authTokenCount = 0;");
            out.println("var serverAttrsCount = 0;");
            out.println("header.HTTP_PARAMS = new Array;");
            out.println("header.HTTP_HEADERS = new Array;");
            out.println("header.AUTH_TOKEN = new Array;");
            out.println("header.SERVER_ATTRS = new Array;");

            r = data.getHeader();
            if (r != null) {
                e = r.elements();
                while (e.hasMoreElements()) {
                    headerBlock = true;
                    String n = e.nextElement();
                    Object v = r.getValue(n);

                    out.println("header." + n + " = " + renderValue(v) + ";");
                }
            }

            // Output the fixed data
            r = data.getFixed();
            if (r != null) {
                e = r.elements();
                while (e.hasMoreElements()) {
                    fixedBlock = true;
                    String n = e.nextElement();
                    Object v = r.getValue(n);

                    out.println("fixed." + n + " = " + renderValue(v) + ";");
                }
            }

            // Output the query data
            q = data.queryRecords();
            if (q != null && q.hasMoreElements()) {
                queryBlock = true;
                out.println("var recordCount = 0;");
                out.println("var record;");
                while (q.hasMoreElements()) {
                    out.println("record = new Object;");
                    out.println("record.HTTP_PARAMS = new Array;");
                    out.println("record.HTTP_HEADERS = new Array;");
                    out.println("record.AUTH_TOKEN = new Array;");
                    out.println("record.SERVER_ATTRS = new Array;");

                    // Get a query record
                    r = q.nextElement();
                    e = r.elements();
                    while (e.hasMoreElements()) {
                        String n = e.nextElement();
                        Object v = r.getValue(n);

                        out.println("record." + n + "=" + renderValue(v) + ";");
                    }
                    out.println("recordSet[recordCount++] = record;");
                }
                out.println("record.recordSet = recordSet;");
            }

            //if (headerBlock)
            out.println("result.header = header;");
            //if (fixedBlock)
            out.println("result.fixed = fixed;");
            //if (queryBlock)
            out.println("result.recordSet = recordSet;");
            out.println("</SCRIPT>");
            out.println(mPostOutput);
            http_out.print(out.toString());

        } catch (EBaseException ex) {
            throw new IOException(ex.getMessage());
        }
    }

    /**
     * Ouput the pre-amble HTML Header including
     * the pre-output buffer.
     * 
     * @param out output stream specified
     * @return success or error
     */
    public boolean outputProlog(PrintWriter out) {

        //Debug.trace("FormCache:outputProlog");

        /* output pre-output buffer */
        out.print(mPreOutput);

        /* output JavaScript variables and objects */
        out.println("<SCRIPT LANGUAGE=\"JavaScript\">");
        out.println("var header = new Object();");
        out.println("var result = new Object();");

        return true;
    }

    /**
     * Output the post HTML tags and post-output
     * buffer.
     * 
     * @param out output stream specified
     * @return success or error
     */
    public boolean outputEpilog(PrintWriter out) {

        out.println("</SCRIPT>");
        out.println(mPostOutput);

        return true;
    }

    /**
     * @return full path of template
     */
    public String getTemplateName() {
        return mAbsPath;
    }

    // inherit getabspath, getContent, get last access and set last access 

    /*==========================================================
     * private methods
     *==========================================================*/

    /* load file into string */
    private String loadFile(File template) throws IOException {

        // Debug.trace("FormCache:loadFile");

        /* create input stream, can throw IOException */
        FileInputStream inStream = new FileInputStream(template);
        InputStreamReader inReader = new InputStreamReader(inStream, mCharset);
        ;
        BufferedReader in = new BufferedReader(inReader);
        StringBuffer buf = new StringBuffer();
        String line;

        while ((line = in.readLine()) != null) {
            buf.append(line);
            buf.append('\n');
        }
        try {
            in.close();
            inStream.close();
        } catch (IOException e) {
            log(ILogger.LL_WARN,
                    CMS.getLogMessage("CMSGW_ERR_CLOSE_TEMPL_FILE", mAbsPath, e.getMessage()));
        }
        return buf.toString();
    }

    private String renderValue(Object v) {
        String s = null;

        // Figure out the type of object
        if (v instanceof IRawJS) {
            s = v.toString();
        } else if (v instanceof String) {
            if (v.equals(""))
                s = "null";
            else
                s = "\"" + escapeJavaScriptString((String) v) + "\"";
        } else if (v instanceof Integer) {
            s = ((Integer) v).toString();
        } else if (v instanceof Boolean) {

            if (((Boolean) v).booleanValue() == true) {
                s = "true";
            } else {
                s = "false";
            }
        } else if (v instanceof BigInteger) {
            s = ((BigInteger) v).toString(10);
        } else if (v instanceof Character &&
                ((Character) v).equals(Character.valueOf((char) 0))) {
            s = "null";
        } else {
            s = "\"" + v.toString() + "\"";
        }

        return s;
    }

    /**
     * Escape the contents of src string in preparation to be enclosed in
     * double quotes as a JavaScript String Literal within an <script>
     * portion of an HTML document.
     * stevep - performance improvements - about 4 times faster than before.
     */
    public static String escapeJavaScriptString(String v) {
        int l = v.length();
        char in[] = new char[l];
        char out[] = new char[l * 4];
        int j = 0;

        v.getChars(0, l, in, 0);

        for (int i = 0; i < l; i++) {
            char c = in[i];

            if ((c > 0x23) && (c != 0x5c) && (c != 0x3c) && (c != 0x3e)) {
                out[j++] = c;
                continue;
            }

            if ((c == 0x5c) && ((i + 1) < l) && (in[i + 1] == 'n' ||
                    in[i + 1] == 'r' || in[i + 1] == 'f' || in[i + 1] == 't' ||
                    in[i + 1] == '<' || in[i + 1] == '>' ||
                    in[i + 1] == '\"' || in[i + 1] == '\'' || in[i + 1] == '\\')) {
                if (in[i + 1] == 'x' && ((i + 3) < l) && in[i + 2] == '3' &&
                        (in[i + 3] == 'c' || in[i + 3] == 'e')) {
                    out[j++] = '\\';
                    out[j++] = in[i + 1];
                    out[j++] = in[i + 2];
                    out[j++] = in[i + 3];
                    i += 3;
                } else {
                    out[j++] = '\\';
                    out[j++] = in[i + 1];
                    i++;
                }
                continue;
            }

            switch (c) {
            case '\n':
                out[j++] = '\\';
                out[j++] = 'n';
                break;

            case '\\':
                out[j++] = '\\';
                out[j++] = '\\';
                break;

            case '\"':
                out[j++] = '\\';
                out[j++] = '\"';
                break;

            case '\r':
                out[j++] = '\\';
                out[j++] = 'r';
                break;

            case '\f':
                out[j++] = '\\';
                out[j++] = 'f';
                break;

            case '\t':
                out[j++] = '\\';
                out[j++] = 't';
                break;

            case '<':
                out[j++] = '\\';
                out[j++] = 'x';
                out[j++] = '3';
                out[j++] = 'c';
                break;

            case '>':
                out[j++] = '\\';
                out[j++] = 'x';
                out[j++] = '3';
                out[j++] = 'e';
                break;

            default:
                out[j++] = c;
            }
        }
        return new String(out, 0, j);
    }

    /**
     * Like escapeJavaScriptString(String s) but also escape '[' for
     * HTML processing.
     */
    public static String escapeJavaScriptStringHTML(String v) {
        int l = v.length();
        char in[] = new char[l];
        char out[] = new char[l * 4];
        int j = 0;

        v.getChars(0, l, in, 0);

        for (int i = 0; i < l; i++) {
            char c = in[i];

            if (c > 0x5C) {
                out[j++] = c;
                continue;
            }

            if ((c == 0x5c) && ((i + 1) < l) && (in[i + 1] == 'n' ||
                    in[i + 1] == 'r' || in[i + 1] == 'f' || in[i + 1] == 't' ||
                    in[i + 1] == '<' || in[i + 1] == '>' ||
                    in[i + 1] == '\"' || in[i + 1] == '\'' || in[i + 1] == '\\')) {
                if (in[i + 1] == 'x' && ((i + 3) < l) && in[i + 2] == '3' &&
                        (in[i + 3] == 'c' || in[i + 3] == 'e')) {
                    out[j++] = '\\';
                    out[j++] = in[i + 1];
                    out[j++] = in[i + 2];
                    out[j++] = in[i + 3];
                    i += 3;
                } else {
                    out[j++] = '\\';
                    out[j++] = in[i + 1];
                    i++;
                }
                continue;
            }

            switch (c) {
            case '\n':
                out[j++] = '\\';
                out[j++] = 'n';
                break;

            case '\\':
                out[j++] = '\\';
                out[j++] = '\\';
                break;

            case '\"':
                out[j++] = '\\';
                out[j++] = '\"';
                break;

            case '\r':
                out[j++] = '\\';
                out[j++] = 'r';
                break;

            case '\f':
                out[j++] = '\\';
                out[j++] = 'f';
                break;

            case '\t':
                out[j++] = '\\';
                out[j++] = 't';
                break;

            case '<':
                out[j++] = '\\';
                out[j++] = 'x';
                out[j++] = '3';
                out[j++] = 'c';
                break;
            case '>':
                out[j++] = '\\';
                out[j++] = 'x';
                out[j++] = '3';
                out[j++] = 'e';
                break;

            default:
                out[j++] = c;
            }
        }
        return new String(out, 0, j);
    }

    /**
     * for debugging, return contents that would've been outputed.
     */
    public String getOutput(CMSTemplateParams input)
            throws IOException {
        debugOutputStream out = new debugOutputStream();

        renderOutput(out, input);
        return out.toString();
    }

    private class HTTPOutputStreamWriter extends OutputStreamWriter {
        public HTTPOutputStreamWriter(OutputStream out)
                throws UnsupportedEncodingException {
            super(out);
        }

        public HTTPOutputStreamWriter(OutputStream out, String enc)
                throws UnsupportedEncodingException {
            super(out, enc);
        }

        public void print(String s) throws IOException {
            write(s, 0, s.length());
            flush();
            return;
        }
    }

    private class templateLine {
        private StringBuffer s = new StringBuffer();

        void println(String p) {
            s.append('\n');
            s.append(p);
        }

        void print(String p) {
            s.append(p);
        }

        public String toString() {
            return s.toString();
        }

    }

    private static class debugOutputStream extends ServletOutputStream {
        private StringWriter mStringWriter = new StringWriter();

        public debugOutputStream() {
            super();
        }

        public void write(int b) throws IOException {
            mStringWriter.write(b);
        }

        public String toString() {
            return mStringWriter.toString();
        }

    }

}