Close

PrimeFaces - MeterGauge with Ajax Polling Example

[Last Updated: Jul 25, 2017]

In this example, we will learn how to use MeterGaugeChartModel to display a meter gauge which updates with ajax polling.

JSF page

src/main/webapp/index.xhtml

<h:form>
    <p:chart id="cpu_gauge" type="metergauge" model="#{cpuUsageBean.meterGaugeModel}"
             style="width:400px;height:250px"/>
    <p:poll interval="1" update="cpu_gauge"/>
</h:form>

The managed bean

@ManagedBean
@ViewScoped
public class CpuUsageBean {
    private AtomicInteger cpuUsage;
    private MeterGaugeChartModel gaugeModel;

    @PostConstruct
    public void init() {
        initCpuGaugeModel();
        initCpuSimulator();
    }

    private void initCpuGaugeModel() {
        gaugeModel = new MeterGaugeChartModel();
        gaugeModel.setIntervals(Arrays.asList(20, 40, 60, 80, 100));
        gaugeModel.setTitle("CPU Usage %");
        gaugeModel.setSeriesColors("aa6666,bb6666,cc6666,dd6666,ee6666");
    }

    private void initCpuSimulator() {
        cpuUsage = new AtomicInteger(50);
        ExecutorService es = Executors.newFixedThreadPool(1);
        es.execute(() -> {
            while (true) {
                int i = ThreadLocalRandom.current()
                                         .nextInt(-15, 16);
                int usage = cpuUsage.get();
                usage += i;
                if (usage < 0) {
                    usage = 0;
                } else if (usage > 100) {
                    usage = 100;
                }
                cpuUsage.set(usage);
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        });
    }


    public MeterGaugeChartModel getMeterGaugeModel() {
        gaugeModel.setValue(cpuUsage.get());
        return gaugeModel;
    }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

PrimeFaces MeterGauge with Ajax Poll Example Select All Download
  • meter-gauge-with-ajax-poll
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also