View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.jsp;
12  
13  import jakarta.servlet.jsp.JspException;
14  import jakarta.servlet.jsp.tagext.TagSupport;
15  
16  import java.io.IOException;
17  
18  /**
19   * Silly JSP tag to display duration in milliseconds as hours:minutes:seconds.milliseconds
20   */
21  public class DurationTag extends TagSupport {
22  
23    /** The Constant serialVersionUID. */
24    private static final long serialVersionUID = 1L;
25  
26    /** The value. */
27    private long value;
28  
29    /**
30     * Sets the value.
31     *
32     * @param value the new value
33     */
34    public void setValue(long value) {
35      this.value = value;
36    }
37  
38    @Override
39    public int doStartTag() throws JspException {
40      try {
41        pageContext.getOut().write(duration(value));
42      } catch (IOException e) {
43        throw new JspException("Exception writing duration to JspWriter", e);
44      }
45      return EVAL_BODY_INCLUDE;
46    }
47  
48    /**
49     * Duration.
50     *
51     * @param value the value
52     *
53     * @return the string
54     */
55    public static String duration(long value) {
56      long millis = value % 1000;
57      long sec = value / 1000;
58      long mins = sec / 60;
59      long hours = mins / 60;
60  
61      sec = sec % 60;
62      mins = mins % 60;
63  
64      return hours + ":" + long2Str(mins) + ":" + long2Str(sec) + "." + long3Str(millis);
65    }
66  
67    /**
68     * Long2 str.
69     *
70     * @param value the value
71     *
72     * @return the string
73     */
74    private static String long2Str(long value) {
75      return value < 10 ? "0" + value : Long.toString(value);
76    }
77  
78    /**
79     * Long3 str.
80     *
81     * @param value the value
82     *
83     * @return the string
84     */
85    private static String long3Str(long value) {
86      if (value < 10) {
87        return "00" + value;
88      }
89      if (value < 100) {
90        return "0" + value;
91      }
92      return Long.toString(value);
93    }
94  
95  }