View Javadoc

1   /*
2    * Copyright 2002,2005 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.apache.commons.jelly.tags.memory;
18  
19  import org.apache.commons.jelly.JellyTagException;
20  import org.apache.commons.jelly.TagSupport;
21  import org.apache.commons.jelly.XMLOutput;
22  
23  /***
24   * Tag supporting displaying free memory.
25   *
26   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
27   */
28  public class FreeMemoryTag extends TagSupport {
29  
30      private static final int MB = 1024 * 1024;
31      private static final int KB = 1024;
32  
33      private String style = "mb";
34  
35      public void setStyle(String style) {
36          if (style == null) {
37              style = "mb";
38          }
39          this.style = style.toLowerCase();
40      }
41  
42      public String getStyle() {
43          return this.style;
44      }
45   
46      // Tag interface
47      //-------------------------------------------------------------------------
48      public void doTag(XMLOutput output) throws JellyTagException {
49  
50          Runtime r = Runtime.getRuntime();
51  
52          try {
53              long total = r.totalMemory();
54              long free = total - r.freeMemory();
55  
56              if (style.equals("kb")) {
57                  free /= KB;
58                  total /= KB;
59              }
60              else if (style.equals("mb")) {
61                  free /= MB;
62                  total /= MB;
63              }
64              
65              output.write( free + style + "/" + total + style );
66          }
67          catch ( Exception e ) {
68              throw new JellyTagException( "Error writing to output", e );
69          }
70      }
71  
72  }