package dalclient; import java.util.*; import java.net.*; import java.io.*; /** * Query record class. Holds a table row or dataset descriptor containing * a set of keyword=value pairs for the record. */ public class QueryRecord { LinkedHashMap params = new LinkedHashMap(); QueryRecord(LinkedHashMap m) { params = m; } /* Get the number of fields in the query response record. */ public int getAttributeCount() { return (params.size()); } /* Get an attribute given its keyword name. */ public QRAttribute getAttribute(String key) { String value = (String) params.get(key); return ((value == null) ? null : new QRAttribute(value)); } /* Get the map itself. */ public LinkedHashMap getMap() { return (params); } /* Fetch the referenced dataset to a generated filename. By default * we try to create the file in the current working directory. We * try to guess the file extension from the "Format" dataset attribute, * if given. */ public String getDataset() throws Exception { QRAttribute v = getAttribute("Format"); File cwd = new File("."); String suffix = null; if (v != null) { String s = v.stringValue(); int last = s.lastIndexOf('/'); if (last > 0) suffix = "." + s.substring(last + 1); } File path = cwd.createTempFile("data", suffix, cwd); return (getDataset(path.toString()) ? path.toString() : null); } /* Get the dataset pointed to by the AccessReference attribute. * Returns true if the download is successful, false if there is * no AccessReference attribute for the dataset. */ public boolean getDataset(String path) throws Exception { QRAttribute v = getAttribute("AccessReference"); if (v == null) return (false); readURL(v.stringValue(), path); return (true); } /* ReadURL -- Copy the contents of a URL to the named output file as a * binary stream. */ public long readURL(String url, String path) throws Exception { URL link = new URL(url); InputStream in = link.openStream(); FileOutputStream out = new FileOutputStream(path); byte buf[] = new byte[4096]; int n; long size; for (size=0; (n = in.read(buf, 0, buf.length)) > 0; size += n) out.write(buf, 0, n); return (size); } }