Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package javax.faces.model;
 
 
 import java.util.Map;
 import java.util.Set;
 

ResultSetDataModel is a convenience implementation of DataModel that wraps a ResultSet of Java objects. Note that the specified ResultSet MUST be scrollable. In addition, if input components (that will be updating model values) reference this object in value binding expressions, the specified ResultSet MUST be updatable.

 
 
 public class ResultSetDataModel extends DataModel<Map<String,Object>> {
 
 
     // ------------------------------------------------------------ Constructors
 

    

Construct a new ResultSetDataModel with no specified wrapped data.

 
     public ResultSetDataModel() {
 
         this(null);
 
     }


    

Construct a new ResultSetDataModel wrapping the specified ResultSet.

Parameters:
resultSet ResultSet to be wrapped (if any)
 
     public ResultSetDataModel(ResultSet resultSet) {
 
         super();
         setWrappedData(resultSet);
 
    }
    // ------------------------------------------------------ Instance Variables
    // The current row index (zero relative)
    private int index = -1;
    // The metadata for the ResultSet we are wrapping (lazily instantiated)
    private ResultSetMetaData metadata = null;
    // The ResultSet we are wrapping
    private ResultSet resultSet = null;
    // Has the row at the current index been updated?
    private boolean updated = false;
    // -------------------------------------------------------------- Properties


    

Return true if there is wrappedData available, and the result of calling absolute() on the underlying ResultSet, passing the current value of rowIndex plus one (to account for the fact that ResultSet uses one-relative indexing), returns true. Otherwise, return false.

Throws:
javax.faces.FacesException if an error occurs getting the row availability
 
    public boolean isRowAvailable() {
        if ( == null) {
	    return (false);
        } else if ( < 0) {
            return (false);
        }
        try {
            if (.absolute( + 1)) {
                return (true);
            } else {
                return (false);
            }
        } catch (SQLException e) {
            throw new FacesException(e);
        }
    }


    

Return -1, since ResultSet does not provide a standard way to determine the number of available rows without scrolling through the entire ResultSet, and this can be very expensive if the number of rows is large.

Throws:
javax.faces.FacesException if an error occurs getting the row count
    public int getRowCount() {
	return (-1);
    }


    

If row data is available, return a Map representing the values of the columns for the row specified by rowIndex, keyed by the corresponding column names. If no wrapped data is available, return null.

If a non-null Map is returned, its behavior must correspond to the contract for a mutable Map as described in the JavaDocs for AbstractMap, with the following exceptions and specialized behavior:

  • The Map, and any supporting objects it returns, must perform all column name comparisons in a case-insensitive manner. This case-insensitivity must be implemented using a case-insensitive Comparator, such as String.CASE_INSENSITIVE_ORDER.
  • The following methods must throw UnsupportedOperationException: clear(), remove().
  • The entrySet() method must return a Set that has the following behavior:
    • Throw UnsupportedOperationException for any attempt to add or remove entries from the Set, either directly or indirectly through an Iterator returned by the Set.
    • Updates to the value of an entry in this set must write through to the corresponding column value in the underlying ResultSet.
  • The keySet() method must return a Set that throws UnsupportedOperationException on any attempt to add or remove keys, either directly or through an Iterator returned by the Set.
  • The put() method must throw IllegalArgumentException if a key value for which containsKey() returns false is specified. However, if a key already present in the Map is specified, the specified value must write through to the corresponding column value in the underlying ResultSet.
  • The values() method must return a Collection that throws UnsupportedOperationException on any attempt to add or remove values, either directly or through an Iterator returned by the Collection.

Throws:
javax.faces.FacesException if an error occurs getting the row data
java.lang.IllegalArgumentException if now row data is available at the currently specified row index
 
    public Map<String,ObjectgetRowData() {
        if ( == null) {
	    return (null);
        } else if (!isRowAvailable()) {
            throw new NoRowAvailableException();
        }
        try {
            getMetaData();
            return (new ResultSetMap(this.));
        } catch (SQLException e) {
            throw new FacesException(e);
        }
    }


    
 
    public int getRowIndex() {
        return ();
    }


    
 
    public void setRowIndex(int rowIndex) {
        if (rowIndex < -1) {
            throw new IllegalArgumentException();
        }
        // Tell the ResultSet that the previous row was updated if necessary
        if ( && ( != null)) {
            try {
		}
                 = false;
            } catch (SQLException e) {
                throw new FacesException(e);
            }
        }
        int old = ;
         = rowIndex;
	if ( == null) {
	    return;
	}
        if ((old != ) && (listeners != null)) {
            Object rowData = null;
            if (isRowAvailable()) {
                rowData = getRowData();
            }
            DataModelEvent event =
                new DataModelEvent(thisrowData);
            int n = listeners.length;
            for (int i = 0; i < ni++) {
		if (null != listeners[i]) {
		    listeners[i].rowSelected(event);
		}
            }
        }
    }
    public Object getWrappedData() {
        return (this.);
    }


    
    public void setWrappedData(Object data) {
        if (data == null) {
             = null;
             = null;
            setRowIndex(-1);
        } else {
             = null;
             = (ResultSetdata;
             = -1;
            setRowIndex(0);
        }
    }
    // --------------------------------------------------------- Private Methods


    

Return the ResultSetMetaData for the ResultSet we are wrapping, caching it the first time it is returned.

Throws:
javax.faces.FacesException if the ResultSetMetaData cannot be acquired
    private ResultSetMetaData getMetaData() {
        if ( == null) {
            try {
                 = .getMetaData();
            } catch (SQLException e) {
                throw new FacesException(e);
            }
        }
        return ();
    }


    

Mark the current row as having been updated, so that we will call updateRow() before moving elsewhere.

    private void updated() {
        this. = true;
    }
    // --------------------------------------------------------- Private Classes
    // Private implementation of Map that delegates column get and put
    // operations to the underlying ResultSet, after setting the required
    // row index
    // NOT SERIALIZABLE
    @SuppressWarnings({"serial"})
    private static class ResultSetMap extends TreeMap<String,Object> {
        private ResultSetDataModel model;
        public ResultSetMap(ResultSetDataModel model,
                            Comparator<Stringcomparatorthrows SQLException {
            super(comparator);
            this. = model;
             = model.index;
            model.resultSet.absolute( + 1);
            int n = model.metadata.getColumnCount();
            for (int i = 1; i <= ni++) {
                super.put(model.metadata.getColumnName(i),
                          model.metadata.getColumnName(i));
            }
        }
        // The zero-relative row index of our row
        private int index;
        // Removing entries is not allowed
        public void clear() {
            throw new UnsupportedOperationException();
        }
        public boolean containsValue(Object value) {
            for (Iterator i = entrySet().iterator(); i .hasNext(); ) {
                Map.Entry entry = (Map.Entryi.next();
                Object contained = entry.getValue();
                 if (value == null) {
                    if (contained == null) {
                        return (true);
                    }
                } else {
                    if (value.equals(contained)) {
                        return (true);
                    }
                }
            }
            return (false);
        }
        public Set<Map.Entry<String,Object>> entrySet() {
            return (new ResultSetEntries(this));
        }
        public Object get(Object key) {
            if (!containsKey(key)) {
                return (null);
            }
            try {
                ..absolute( + 1);
                return (..getObject((StringrealKey(key)));
            } catch (SQLException e) {
                throw new FacesException(e);
            }
        }
        public Set<StringkeySet() {
            return (new ResultSetKeys(this));
        }
        public Object put(String keyObject value) {
            if (!containsKey(key)) {
                throw new IllegalArgumentException();
            }
            
            try {
                ..absolute( + 1);
                Object previous = ..getObject((StringrealKey(key));
                if ((previous == null) && (value == null)) {
                    return (previous);
                } else if ((previous != null) && (value != null) &&
                           previous.equals(value)) {
                    return (previous);
                }
                ..updateObject((StringrealKey(key), value);
                .updated();
                return (previous);
            } catch (SQLException e) {
                throw new FacesException(e);
            }
        }
        public void putAll(Map<? extends String, ? extends Objectmap) {
            for (Map.Entry<? extends String, ? extends Objectentry : map.entrySet()) {
                put(entry.getKey(), entry.getValue());
            }
        }
        // Removing entries is not allowed
        public Object remove(Object key) {
            throw new UnsupportedOperationException();
        }
        public Collection<Objectvalues() {
            return (new ResultSetValues(this));
        }
        Object realKey(Object key) {
            return (super.get(key));
        }
        Iterator<StringrealKeys() {
            return (super.keySet().iterator());
        }
        private void writeObject(ObjectOutputStream outthrows IOException {
            throw new NotSerializableException();
        }
        private void readObject(ObjectInputStream inthrows IOException {
            throw new NotSerializableException();
        }
    }
    // Private implementation of Set that implements the entrySet() behavior
    // for ResultSetMap
    private static class ResultSetEntries extends AbstractSet<Map.Entry<String,Object>> {
        public ResultSetEntries(ResultSetMap map) {
            this. = map;
        }
        private ResultSetMap map;
        // Adding entries is not allowed
        public boolean add(Map.Entry<String,Objecto) {
            throw new UnsupportedOperationException();
        }
        // Adding entries is not allowed
        public boolean addAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        // Removing entries is not allowed
        public void clear() {
            throw new UnsupportedOperationException();
        }
        public boolean contains(Object o) {
            if (o == null) {
                throw new NullPointerException();
            }
            if (!(o instanceof Map.Entry)) {
                return (false);
            }
            Map.Entry e = (Map.Entryo;
            Object k = e.getKey();
            Object v = e.getValue();
            if (!.containsKey(k)) {
                return (false);
            }
            if (v == null) {
                return (.get(k) == null);
            } else {
                return (v.equals(.get(k)));
            }
        }
        public boolean isEmpty() {
            return (.isEmpty());
        }
        public Iterator<Map.Entry<String,Object>> iterator() {
            return (new ResultSetEntriesIterator());
        }
        // Removing entries is not allowed
        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }
        // Removing entries is not allowed
        public boolean removeAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        // Removing entries is not allowed
        public boolean retainAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        public int size() {
            return (.size());
        }
    }
    // Private implementation of Iterator that implements the iterator()
    // behavior for the Set returned by entrySet() from ResultSetMap
    private static class ResultSetEntriesIterator implements Iterator<Map.Entry<String,Object>> {
        public ResultSetEntriesIterator(ResultSetMap map) {
            this. = map;
            this. = map.keySet().iterator();
        }
        private ResultSetMap map = null;
        private Iterator<Stringkeys = null;
        public boolean hasNext() {
            return (.hasNext());
        }
        public Map.Entry<String,Objectnext() {
            String key = .next();
            return (new ResultSetEntry(key));
        }
        // Removing entries is not allowed
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
    // Private implementation of Map.Entry that implements the behavior for
    // a single entry from the Set returned by entrySet() from ResultSetMap
    private static class ResultSetEntry implements Map.Entry<String,Object> {
        public ResultSetEntry(ResultSetMap mapString key) {
            this. = map;
            this. = key;
        }
        private ResultSetMap map;
        private String key;
        public boolean equals(Object o) {
            if (o == null) {
                return (false);
            }
            if (!(o instanceof Map.Entry)) {
                return (false);
            }
            Map.Entry e = (Map.Entryo;
            if ( == null) {
                if (e.getKey() != null) {
                    return (false);
                }
            } else {
                if (!.equals(e.getKey())) {
                    return (false);
                }
            }
            Object v = .get();
            if (v == null) {
                if (e.getValue() != null) {
                    return (false);
                }
            } else {
                if (!v.equals(e.getValue())) {
                    return (false);
                }
            }
            return (true);
        }
        public String getKey() {
            return ();
        }
        public Object getValue() {
            return (.get());
        }
        public int hashCode() {
            Object value = .get();
            return ((( == null) ? 0 : .hashCode()) ^
                    ((value == null) ? 0 : value.hashCode()));
        }
        public Object setValue(Object value) {
            Object previous = .get();
            .put(value);
            return (previous);
        }
    }
    // Private implementation of Set that implements the keySet() behavior
    // for ResultSetMap
    private static class ResultSetKeys extends AbstractSet<String> {
        public ResultSetKeys(ResultSetMap map) {
            this. = map;
        }
        private ResultSetMap map;
        // Adding keys is not allowed
        public boolean add(String o) {
            throw new UnsupportedOperationException();
        }
        // Adding keys is not allowed
        public boolean addAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        // Removing keys is not allowed
        public void clear() {
            throw new UnsupportedOperationException();
        }
        public boolean contains(Object o) {
            return (.containsKey(o));
        }
        public boolean isEmpty() {
            return (.isEmpty());
        }
        public Iterator<Stringiterator() {
            return (new ResultSetKeysIterator());
        }
        // Removing keys is not allowed
        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }
        // Removing keys is not allowed
        public boolean removeAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        // Removing keys is not allowed
        public boolean retainAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        public int size() {
            return (.size());
        }
    }
    // Private implementation of Iterator that implements the iterator()
    // behavior for the Set returned by keySet() from ResultSetMap
    private static class ResultSetKeysIterator implements Iterator<String> {
        public ResultSetKeysIterator(ResultSetMap map) {
            this. = map.realKeys();
        }
        private Iterator<Stringkeys = null;
        public boolean hasNext() {
            return (.hasNext());
        }
        public String next() {
            return (.next());
        }
        // Removing keys is not allowed
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
    // Private implementation of Collection that implements the behavior
    // for the Collection returned by values() from ResultSetMap
    private static class ResultSetValues extends AbstractCollection<Object> {
        public ResultSetValues(ResultSetMap map) {
            this. = map;
        }
        private ResultSetMap map;
        public boolean add(Object o) {
            throw new UnsupportedOperationException();
        }
        public boolean addAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        public void clear() {
            throw new UnsupportedOperationException();
        }
        public boolean contains(Object value) {
            return (.containsValue(value));
        }
        public Iterator<Objectiterator() {
            return (new ResultSetValuesIterator());
        }
        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }
        public boolean removeAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        public boolean retainAll(Collection c) {
            throw new UnsupportedOperationException();
        }
        public int size() {
            return (.size());
        }
    }
    // Private implementation of Iterator that implements the behavior
    // for the Iterator returned by values().iterator() from ResultSetMap
    private static class ResultSetValuesIterator implements Iterator<Object> {
        public ResultSetValuesIterator(ResultSetMap map) {
            this. = map;
            this. = map.keySet().iterator();
        }
        private ResultSetMap map;
        private Iterator<Stringkeys;
        public boolean hasNext() {
            return (.hasNext());
        }
        public Object next() {
            return (.get(.next()));
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
New to GrepCode? Check out our FAQ X