GetArray.java

/***************************************************************************
   Copyright 2012 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.sqlc.setters;


import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/** Convert a SQL Array as returned by a result set object into a Java list. */
public final class GetArray extends RSGetter {
	/** Create an array getter for the column name provided.
		@param name The name of the result set column containing the array to get.
	*/
	public GetArray(final String name) { super(name, "java.util.List"); }

	/** A utility function convert a JDBC SQL Array object into a Java list object.
		@param arr The array to convert.
		@return a Java list containing the objects that were in the array. Returns null if the array object is null.
		@throws SQLException if something goes wrong.
	*/
	public static List parse(final Array arr) throws SQLException {
		if(arr == null) { return null; }
		final Object[] a = (Object[]) arr.getArray();
		final ArrayList<Object> list = new ArrayList<>();
		for(final Object o: a) { list.add(o); }
		return list;
	}

	@Override public Object get(final ResultSet rs) throws SQLException { return parse(rs.getArray(name)); }
	@Override public Object get(final ResultSet rs, final int col) throws SQLException { return parse(rs.getArray(col)); }

	@Override public String getStatic(final String rsVar) {
		return "net.metanotion.sqlc.setters.GetArray.parse(" + rsVar + ".getArray(\"" + name + "\"))";
	}

	@Override public String getStatic(final String rsVar, final int col) {
		return "net.metanotion.sqlc.setters.GetArray.parse(" + rsVar + ".getArray(\"" + col + "\"))";
	}
}