⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 query.java

📁 JoSQL 1.5的源代码。JoSQL(SQL for Java Objects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
		    this.currentObject = o;		} catch (Exception e) {		    throw new QueryExecutionException ("Unable to get value for column: " +						       j + 						       " for: " +						       v.toString () + 						       " from result: " +						       i + 						       " (" +						       o + 						       ")",						       e);							   		}			    }	    if (!addItems)	    {		rs.add (sRes);	    }	}    }    private List getNewObjectSingleColumnValues (List   rows)	                                         throws QueryExecutionException    {	int s = rows.size ();	SelectItemExpression nsei = (SelectItemExpression) this.cols.get (0);	List res = new ArrayList (s);	for (int i = 0; i < s; i++)	{	    Object o = rows.get (i);	    this.currentObject = o;	    try	    {		res.add (nsei.getValue (o,					this));		// Now since the expression can set the current object, put it		// back to rights after the call...		this.currentObject = o;	    } catch (Exception e) {		throw new QueryExecutionException ("Unable to get value for column: " +						   1 + 						   " for: " +						   nsei.toString () + 						   " from result: " +						   i + 						   " (" +						   o + 						   ")",						   e);							   	    }	}	return res;    }    public void setSaveValues (Map s)    {	if (this.parent != null)	{	    this.parent.qd.saveValues.putAll (s);	    return;	}	this.qd.saveValues = s;    }    public void setSaveValue (Object id,			      Object value)    {	if (this.parent != null)	{	    this.parent.setSaveValue (id,				      value);	    return;	}	if (this.qd == null)	{	    return;	}	if (id instanceof String)	{	    id = ((String) id).toLowerCase ();	}	Object old = this.qd.saveValues.get (id);	this.qd.saveValues.put (id,				value);	if (old != null)	{	    this.fireSaveValueChangedEvent (id,					    old,					    value);	}    }    protected void fireSaveValueChangedEvent (Object id,					      Object from,					      Object to)    {	List l = (List) this.listeners.get ("svs");	if ((l == null)	    ||	    (l.size () == 0)	   )	{	    return;	}	SaveValueChangedEvent svce = new SaveValueChangedEvent (this,								id.toString ().toLowerCase (),								from,								to);	for (int i = 0; i < l.size (); i++)	{	    SaveValueChangedListener svcl = (SaveValueChangedListener) l.get (i);	    svcl.saveValueChanged (svce);	}    }    protected void fireBindVariableChangedEvent (String name,						 Object from,						 Object to)    {	List l = (List) this.listeners.get ("bvs");	if ((l == null)	    ||	    (l.size () == 0)	   )	{	    return;	}	BindVariableChangedEvent bvce = new BindVariableChangedEvent (this,								      name,								      from,								      to);	for (int i = 0; i < l.size (); i++)	{	    BindVariableChangedListener bvcl = (BindVariableChangedListener) l.get (i);	    bvcl.bindVariableChanged (bvce);	}    }    /**     * Get the save value for a particular key and group by list.     *     * @param id The id of the save value.     * @param gbs The group by list key.     * @return The object the key maps to.     */    public Object getGroupBySaveValue (Object id,				       List   gbs)    {	if (this.parent != null)	{	    return this.getGroupBySaveValue (id,					     gbs);	}	Map m = this.getGroupBySaveValues (gbs);	if (m == null)	{	    return null;	}	return m.get (id);    }    public Map getGroupBySaveValues (List gbs)    {	if (this.parent != null)	{	    return this.parent.getGroupBySaveValues (gbs);	}	if ((this.qd == null)	    ||	    (this.qd.groupBySaveValues == null)	   )	{	    return null;	}	return (Map) this.qd.groupBySaveValues.get (gbs);    }    /**     * Get the save values for a particular key.     *     * @return The object the key maps to.     */    public Object getSaveValue (Object id)    {	if (this.parent != null)	{	    return this.parent.getSaveValue (id);	}	if ((this.qd == null)	    ||	    (this.qd.saveValues == null)	   )	{	    return null;	}	if (id instanceof String)	{	    id = ((String) id).toLowerCase ();	}	return this.qd.saveValues.get (id);    }    public String getQuery ()    {	return this.query;    }    /**     * Will cause the order by comparator used to order the results     * to be initialized.  This is generally only useful if you are specifying the     * the order bys yourself via: {@link #setOrderByColumns(List)}.  Usage of     * this method is <b>NOT</b> supported, so don't use unless you really know what      * you are doing!     */    public void initOrderByComparator ()	                               throws QueryParseException    {	if (this.orderBys != null)	{	    	    // No caching, this may need to change in the future.	    this.orderByComp = new ListExpressionComparator (this,							     false);	    ListExpressionComparator lec = (ListExpressionComparator) this.orderByComp;	    boolean allAccs = false;	    // Need to check the type of each order by, if we have	    // any "column" indexes check to see if they are an accessor...	    int si = this.orderBys.size (); 	    for (int i = 0; i < si; i++)	    {		OrderBy ob = (OrderBy) this.orderBys.get (i);		// Get the expression...		Expression e = (Expression) ob.getExpression ();		if (e == null)		{		    // Now expect an integer that refers to a column		    // in the select...		    int ci = ob.getIndex ();		    if (ci == 0)		    {			throw new QueryParseException ("Order by column indices should start at 1.");		    }		    if (this.retObjs)		    {			throw new QueryParseException ("Cannot sort on a select column index when the objects are to be returned.");		    }		    if (ci > this.cols.size ())		    {			throw new QueryParseException ("Invalid order by column index: " + 						       ci + 						       ", only: " +						       this.cols.size () + 						       " columns are selected to be returned.");		    }		    // Get the SelectItemExpression.		    SelectItemExpression sei = (SelectItemExpression) this.cols.get (ci - 1);		    // Get the expression...		    e = sei.getExpression ();		} else {		    // Init the expression...		    e.init (this);		}		// Check to see if the expression returns a fixed result, if so		// there's no point adding it.		if (!e.hasFixedResult (this))		{		    lec.addSortItem (e,				     ob.getType ());		}	    }	}    }    /**     * Re-order the objects according to the columns supplied in the <b>dirs</b> Map.     * The Map should be keyed on an Integer and map to a String value, the String value should     * be either: {@link #ORDER_BY_ASC} for the column to be in ascending order or:      * {@link #ORDER_BY_DESC} for the column to be in descending order.  The Integer refers     * to a column in the SELECT part of the statement.     * <p>     * For example:     * <p>     * <pre>     *   SELECT name,     *          directory,     *          file     *          length     *   FROM   java.io.File     * </pre>     * Can be (re)ordered via the following code:     * <pre>     *   Query q = new Query ();     *   q.parse (sql);     *        *   Map reorderBys = new TreeMap ();     *   reorderBys.put (new Integer (2), Query.ORDER_BY_ASC);     *   reorderBys.put (new Integer (3), Query.ORDER_BY_DESC);     *   reorderBys.put (new Integer (1), Query.ORDER_BY_ASC);     *   reorderBys.put (new Integer (4), Query.ORDER_BY_DESC);     *     *   // Note: this call will cause the entire statement to be executed.     *   q.reorder (myFiles,     *              reorderBys);     * </pre>     *     * @param objs The objects you wish to reorder.     * @param dirs The order bys.     * @return The QueryResults.     * @throws QueryParseException If the statement can be parsed, i.e. if any of the order by     *                             columns is out of range.     * @throws QueryExecutionException If the call to: {@link #execute(List)} fails.     * @see #reorder(List,String)     */    public QueryResults reorder (List      objs,				 SortedMap dirs)	                         throws QueryExecutionException,					QueryParseException    {	if (this.isWantObjects ())	{	    throw new QueryParseException ("Only SQL statements that return columns (not the objects passed in) can be re-ordered.");	}	List obs = new ArrayList ();	Iterator iter = dirs.keySet ().iterator ();	while (iter.hasNext ())	{	    Integer in = (Integer) iter.next ();	    	    // See if we have a column for it.	    if (in.intValue () > this.cols.size ())	    {		throw new QueryParseException ("Cannot reorder: " +					       dirs.size () + 					       " columns, only: " +					       this.cols.size () + 					       " are present in the SQL statement.");	    }	    String dir = (String) dirs.get (in);	    	    int d = OrderBy.ASC;	    	    if (dir.equals (Query.ORDER_BY_DESC))	    {		d = OrderBy.DESC;			    }	    	    OrderBy ob = new OrderBy ();	    ob.setIndex (in.intValue ());	    ob.setType (d);	    	    obs.add (ob);	    	}	this.orderBys = obs;		this.initOrderByComparator ();	// Execute the query.	return this.execute (objs);	    }    /**     * Allows the re-ordering of the results via a textual representation of the order bys.     * This is effectively like providing a new ORDER BY clause to the sql.     * <p>     * For example:     * <p>     * <pre>     *   SELECT name,     *          directory,     *          file     *          length     *   FROM   java.io.File     * </pre>     * Can be (re)ordered via the following code:     * <pre>     *   Query q = new Query ();     *   q.parse (sql);     *        *   // Note: this call will cause the entire statement to be executed.     *   q.reorder (myFiles,     *              "name DESC, 3 ASC, length, 1 DESC");     * </pre>     *      * @param objs The objects you wish to re-order.     * @param orderBys The order bys.     * @return The execution results.     * @throws QueryParseException If the statement can be parsed, i.e. if any of the order by     *                             columns is out of range or the order bys cannot be parsed.     * @throws QueryExecutionException If the call to: {@link #execute(List)} fails.     * @see #reorder(List,SortedMap)     */    public QueryResults reorder (List   objs,				 String orderBys)	                         throws QueryParseException,					QueryExecutionException    {	String sql = "";	if (!orderBys.toLowerCase ().startsWith ("order by"))	{	    sql = sql + " ORDER BY ";	}	    	sql = sql + orderBys;	BufferedReader sr = new BufferedReader (new StringReader (sql));	JoSQLParser parser = new JoSQLParser (sr);	List ors = null;	try	{	     ors = parser.OrderBys ();	} catch (Exception e) {	    throw new QueryParseException ("Unable to parse order bys: " + 					   orderBys,					   e);	}		this.orderBys = ors;	this.initOrderByComparator ();	// Execute the query.	return this.execute (objs);    }    public void setClassLoader (ClassLoader cl)    {	this.classLoader = cl;    }    public ClassLoader getClassLoader ()    {	if (this.classLoader == null)	{	    // No custom classloader specified, use the one that loaded	    // this class.	    this.classLoader = this.getClass ().getClassLoader ();	}	return this.classLoader;    }    public Class loadClass (String name)	                    throws Exception    {	return this.getClassLoader ().loadClass (name);    }    public void parse (String q)	               throws QueryParseException    {	this.query = q;	BufferedReader sr = new BufferedReader (new StringReader (q));	long s = System.currentTimeMillis ();	JoSQLParser parser = new JoSQLParser (sr);	this.addTiming ("Time to init josql parser object",			System.currentTimeMillis () - s);	s = System.currentTimeMillis ();	try	{	    parser.parseQuery (this);	} catch (Exception e) {	    throw new QueryParseException ("Unable to parse query: " + 					   q,					   e);	}	this.isParsed = true;	this.addTiming ("Time to parse query into object form",			System.currentTimeMillis () - s);	// Init the query.	this.init ();    }    public void init ()                      throws QueryParseException    {	long s = System.currentTimeMillis ();	// If we don't have a parent, then there must be an explicit class name.	if (this.parent == null)	{	    if (!(this.from instanceof ConstantExpression))	    {		throw new QueryParseException ("The FROM clause of the outer-most Query must be a string that denotes a fully-qualified class name, expression: " +					       this.from + 					       " is not valid.");	    }	    // See if the class name is the special "null".	    String cn = null;	    try	    {		// Should be safe to use a null value here (especially since we know		// how ConstantExpression works ;)		cn = (String) this.from.getValue (null,						  this);	    } catch (Exception e) {				throw new QueryParseException ("Unable to determine FROM clause of the outer-most Query from expression: " +					       this.from +					       ", note: this exception shouldn't be able to happen, so something has gone SERIOUSLY wrong!",					       e);			    }	    if (!cn.equalsIgnoreCase ("null"))	    {		// Load the class that we are dealing with...		try		{		    		    this.objClass = this.loadClass (cn);		} catch (Exception e) {		    		    throw new QueryParseException ("Unable to load FROM class: " + 						   cn,						   e);		    		}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -