org.teama.AppListDA.java Source code

Java tutorial

Introduction

Here is the source code for org.teama.AppListDA.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.teama;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

/**
 *
 * @author bamidei
 */
public class AppListDA {
    static private ArrayList<App> appList = null;

    static public ArrayList<App> getAppList() {
        if (appList == null)
            load();
        return appList;
    }

    static public App getApp(final int id) {
        if (appList == null)
            load();

        if (appList != null) {
            /* Use collectionUtils to find the matching App from the list */
            return (App) CollectionUtils.find(appList, new Predicate() {
                @Override
                public boolean evaluate(Object o) {
                    App a = (App) o;
                    return a.getAppId() == id;
                }
            });
        } else {
            return null;
        }
    }

    static public boolean load() {
        boolean res;

        /* Get a new list to populate - even if we had already populated, this 
        will throw away the old and replace with a new 'load'.
        */
        appList = new ArrayList<App>();

        /*Simple get all of the defects query.  We'll sort and filter as
            necessary using java collection operations. */
        String query = "SELECT * FROM BugTracker.application";

        try {
            Connection connection = DBconnect.getConnection();
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(query);

            if (rs != null) {
                while (rs.next()) {
                    App i;

                    i = new App(rs.getInt("app_id"), rs.getString("name"), rs.getString("version"));
                    appList.add(i);
                }
            }
            connection.close();
            statement.close();
            res = true;

        } catch (SQLException ex) {
            DBconnect.getLogger().log(Level.SEVERE, "Error Reading application list from database", ex);
            res = false;
        }

        return res;
    }
}