Thursday

JFreeChart example - create charts in Java and save them as jpeg

Download jcommon-1.0.16.jar and add to the build path.

https://mvnrepository.com/artifact/jfree/jcommon/1.0.16

For maven:
<dependency>
    <groupId>jfree</groupId>
    <artifactId>jcommon</artifactId>
    <version>1.0.16</version>
</dependency>
Download jfreechart-1.0.13.jar and add to the build path.

https://mvnrepository.com/artifact/jfree/jfreechart/1.0.13
For maven:
<dependency>
    <groupId>jfree</groupId>
    <artifactId>jfreechart</artifactId>
    <version>1.0.13</version>
</dependency>

import java.io.IOException;

public class Main {

       public static void main(String[] args) throws IOException {

              PieChart3D pieChart3D = new PieChart3D("Comparison", "Which operating system are you using?");
              pieChart3D.pack();
              pieChart3D.setVisible(true);

              PieChart pieChart = new PieChart("Comparison", "Which operating system are you using?");
              pieChart.pack();
              pieChart.setVisible(true);

              XYAreaChart xyAreaChart = new XYAreaChart("Comparison", "Sample XY Area Chart");
              xyAreaChart.pack();
              xyAreaChart.setVisible(true);

              XYLineChart xyLineChart = new XYLineChart("Comparison", "Sample XY Line Chart");
              xyLineChart.pack();
              xyLineChart.setVisible(true);

              XYStepAreaChart xyStepAreaChart = new XYStepAreaChart("Comparison", "Sample XY Step Area Chart");
              xyStepAreaChart.pack();
              xyStepAreaChart.setVisible(true);

              //We will save the following chart to a file named chart.jpg
              VerticalBarChart3D verticalBarChart3D = new VerticalBarChart3D("Comparison", "Sample Vertical Bar Chart");
       }
}


import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


public class PieChart extends JFrame {

    private static final long serialVersionUID = 1L;

    public PieChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        PieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }

    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("Linux", 29);
        result.setValue("Mac", 20);
        result.setValue("Windows", 51);
        return result;
    }

    private JFreeChart createChart(PieDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createPieChart(
            title,                  // chart title
            dataset,                // data
            true,                   // include legend
            true,
            false
        );


        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
}



import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


public class PieChart3D extends JFrame {

    private static final long serialVersionUID = 1L;

    public PieChart3D(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        PieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }

    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("Linux", 29);
        result.setValue("Mac", 20);
        result.setValue("Windows", 51);
        return result;
    }

    private JFreeChart createChart(PieDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createPieChart3D(
            title,                  // chart title
            dataset,                // data
            true,                   // include legend
            true,
            false
        );

        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
}



import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;


public class VerticalBarChart3D extends JFrame {

    private static final long serialVersionUID = 1L;

    public VerticalBarChart3D(String applicationTitle, String chartTitle) throws IOException {
        super(applicationTitle);
        DefaultCategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);

        BufferedImage image = chart.createBufferedImage(500,300);
        JLabel lblChart = new JLabel();
        lblChart.setIcon(new ImageIcon(image));
        ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);
    }

    private  DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
        categoryDataset.setValue(6,"Marks" ,"Aditi" ); 
        categoryDataset.setValue(3,"Marks" ,"Pooja" ); 
        categoryDataset.setValue(10,"Marks" ,"Ria" ); 
        categoryDataset.setValue(5,"Marks" ,"Twinkle" ); 
        categoryDataset.setValue(20,"Marks" ,"Rutvi" );

        return categoryDataset;
    }

    private JFreeChart createChart(DefaultCategoryDataset dataset, String title) {

        JFreeChart chart = ChartFactory.createBarChart(
            title,                  // chart title
            "Students",              // X-Axis label
            "Marks",                 // Y-Axis label,
            dataset,
            PlotOrientation.VERTICAL,      //Plot orientation 
            false,                // Show legend 
            true,                // Use tooltips 
            false                // Generate URLs 
        );

        chart.getTitle().setPaint(Color.BLUE);    // Set the colour of the title 
        chart.setBackgroundPaint(Color.WHITE);    // Set the background colour of the chart
        CategoryPlot cp = (CategoryPlot ) chart.getPlot();
        cp.setBackgroundPaint(Color.CYAN);      
        cp.setRangeGridlinePaint(Color.RED);

        return chart;
    }
}



import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;


public class XYAreaChart extends JFrame {

    private static final long serialVersionUID = 1L;

    public XYAreaChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);

        XYSeries series = createDataset();
        XYDataset xydataset = new XYSeriesCollection(series);
        JFreeChart chart = createXYAreaChart(xydataset, chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }

    private  XYSeries createDataset() {
        XYSeries result = new XYSeries ("Average Size");
        result.add(20, 29);
        result.add(40, 20);
        result.add(78, 51);

        return result;
    }

    private JFreeChart createXYAreaChart(XYDataset xydataset, String title) {
 
        JFreeChart chart = ChartFactory.createXYAreaChart(
            title,                  // chart title
            "Height",           // X-Axis label
            "Weight",           // Y-Axis label
            xydataset,          // Dataset
            PlotOrientation.VERTICAL,
            true,            // include legend
            true,            // tooltips
            true             // urls
        );

        XYPlot plot = (XYPlot) chart.getXYPlot();
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
}



import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;


public class XYLineChart extends JFrame {

    private static final long serialVersionUID = 1L;

    public XYLineChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);

        XYSeries series = createDataset();
        XYDataset xydataset = new XYSeriesCollection(series);
        JFreeChart chart = createXYLineChart(xydataset, chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }

    private  XYSeries createDataset() {
        XYSeries result = new XYSeries ("Average Size");
        result.add(20, 29);
        result.add(40, 20);
        result.add(78, 51);

        return result;
    }

    private JFreeChart createXYLineChart(XYDataset xydataset, String title) {

        JFreeChart chart = ChartFactory.createXYLineChart(
            title,                  // chart title
            "Height",           // X-Axis label
            "Weight",           // Y-Axis label
            xydataset,          // Dataset
            PlotOrientation.VERTICAL,
            true,            // include legend
            true,            // tooltips
            true             // urls
        );

        XYPlot plot = (XYPlot) chart.getXYPlot();
        plot.setForegroundAlpha(0.5f);
  
        return chart;
    }
}



import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;


public class XYStepAreaChart extends JFrame {

    private static final long serialVersionUID = 1L;

    public XYStepAreaChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);

        XYSeries series = createDataset();
        XYDataset xydataset = new XYSeriesCollection(series);

        JFreeChart stepAreaChart = createXYStepAreaChart(xydataset, chartTitle);
        ChartPanel stepAreaChartPanel = new ChartPanel(stepAreaChart);
        stepAreaChartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(stepAreaChartPanel);
    }

    private  XYSeries createDataset() {
        XYSeries result = new XYSeries ("Average Size");

        result.add(20, 29);
        result.add(40, 20);
        result.add(78, 51);
  
        return result;
    }

    private JFreeChart createXYStepAreaChart(XYDataset xydataset, String title) {
        JFreeChart chart = ChartFactory.createXYStepAreaChart(
            title,                  // chart title
            "Height",           // X-Axis label
            "Weight",           // Y-Axis label
            xydataset,          // Dataset
            PlotOrientation.VERTICAL,
            true,            // include legend
            true,            // tooltips
            true             // urls
        );

        XYPlot plot = (XYPlot) chart.getXYPlot();
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
}

Tuesday

Ehcache hello world example

Ehcache is a Java open source cache implematation.

Download ehcache-2.9.0.jar and add to build path.

https://mvnrepository.com/artifact/net.sf.ehcache/ehcache/2.9.0 
For maven:
<dependency>

                <groupId>net.sf.ehcache</groupId>

                <artifactId>ehcache</artifactId>

                <version>2.9.0</version>

</dependency>
Download slf4j-api-1.6.1.jar (for Ehcache log) and add to build path.

https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.6.1

For maven:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
</dependency>
Download slf4j-jdk14-1.7.5.jar and add to build path.

https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14/1.7.5

For maven:
 <dependency>

    <groupId>org.slf4j</groupId>

    <artifactId>slf4j-jdk14</artifactId>

    <version>1.7.5</version>

</dependency>

package main.java.com.code.more.talk.less;

import main.java.com.code.more.talk.less.cache.CacheExample;

public class Test {
      
       public static void main(String[] args) {
             
              CacheExample.getInstance().putElementToCache("months", "1", "Jan");
              CacheExample.getInstance().putElementToCache("months", "2", "Feb");
             
              System.out.println( CacheExample.getInstance().isKeyInCache("months", "1") );
              System.out.println( CacheExample.getInstance().isKeyInCache("months", "5") );
             
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "1") );
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "2") );
              System.out.println( CacheExample.getInstance().getValueofKeyFromCache("months", "5") );

       }

}

package main.java.com.code.more.talk.less.cache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class CacheExample {
               
                private static CacheManager cacheMgr = null;
                private static CacheExample ex = new CacheExample();
               
                public static  CacheExample getInstance() {
                                ex.initCacheManager();
                                return ex;
                }
               
                public Cache getCache(String cacheName) {
                                return cacheMgr.getCache(cacheName);
                }
               
                public void addCache(String cacheName) {
                                cacheMgr.addCache(cacheName);
                }
               
                public void putElementToCache(String cacheName, String key, String value) {
                                getCache(cacheName).put(new Element(key,value));
                }
               
                public boolean isKeyInCache(String cacheName, String key) {
                                return getCache(cacheName).isKeyInCache(key);
                }
               
                public String getValueofKeyFromCache(String cacheName, String key) {
                                Element ele = getCache(cacheName).get(key);
                                String value = (ele == null) ? null : (ele.getObjectValue().toString());
                                return value;
                }
               
                public void shutDown(){
                                cacheMgr.shutdown();
                }
               
                private void initCacheManager() {
                                if(cacheMgr == null) {
                                                synchronized(this) {
                                                                if(cacheMgr == null)
                                                                                cacheMgr = CacheManager.newInstance("src/main/resources/ehcache.xml");
                                                }
                                }

                }
               
                @Override
               public Object clone() throws CloneNotSupportedException {
                    throw new CloneNotSupportedException();
               }

}

Add ehcache.xml file to the following path: "src/main/resources/ehcache.xml"
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
       monitoring="autodetect" dynamicConfig="true">

       <!-- By default, Ehcache stored the cached files in temp folder. -->
       <!-- <diskStore path="java.io.tmpdir" /> -->

       <!-- Ask Ehcache to store cache in this path -->
       <diskStore path="c:\\cache" />

       <!-- Sample cache named cache1
    This cache contains a maximum in memory of 10000 elements, and will expire
    an element if it is idle for more than 5 minutes and lives for more than
    10 minutes.

    If there are more than 10000 elements it will overflow to the
    disk cache, which in this configuration will go to wherever java.io.tmp is
    defined on your system. On a standard Linux system this will be /tmp" -->
       <cache name="months"
              maxEntriesLocalHeap="1000"
              maxEntriesLocalDisk="10000"
              eternal="false"
              diskSpoolBufferSizeMB="20"
              timeToIdleSeconds="300" timeToLiveSeconds="600"
              memoryStoreEvictionPolicy="LFU"
              transactionalMode="off">
              <persistence strategy="localTempSwap" />
       </cache>

</ehcache>

Output:
true
false
Jan
Feb
null

ehcache.xml configuration:
Expiration:
The maximum number of seconds an element can exist in the cache
whatever the access is. = timeToIdleSeconds  
without being accessed. = timeToLiveSeconds
The element expires at this limit and won't be returned from the cache. 
However eternal attribute overrides both of them if it is true so no expiration happens.

Memory Use:
If overflow is enabled, a check for expiry is carried out. 
The eviction of an item from the memory store: memoryStoreEvictionPolicy:
Least Recently Used (LRU) *Default**
Least Frequently Used (LFU)
Least Frequently Used (LFU)
Strategy Options: (<persistence strategy="" />)
localTempSwap: When the node is restarted, any existing data on disk is cleared because it is not designed to be reloaded.
localRestartable: After any restart, the data set is automatically reloaded from disk to the in-memory stores.
References for ehcache.xml configuration:  
http://www.ehcache.org/generated/2.9.0/pdf/Ehcache_Configuration_Guide.pdf