001 package org.apache.ojb.broker.query;
002
003 /* Copyright 2002-2005 The Apache Software Foundation
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 import java.util.*;
019
020 /**
021 * This Class contains utility functions for Criterias.
022 *
023 * @author <a href="mailto:on@ibis.odessa.ua">Oleg Nitz</a>
024 * @version $Id: CriteriaUtils.java,v 1.1 2007-08-24 22:17:36 ewestfal Exp $
025 */
026 public class CriteriaUtils
027 {
028
029 /**
030 * Disjunctive Normal Form: list of Criteria, which don't contain ORs,
031 * the elements of the list joined by ORs give the condition equivalent
032 * to the original Criteria.
033 */
034 public static List getDNF(Criteria crit)
035 {
036 List dnf = new ArrayList();
037 Enumeration e = crit.getElements();
038 Criteria tmpCrit;
039
040 while (e.hasMoreElements())
041 {
042 Object o = e.nextElement();
043 if (o instanceof Criteria)
044 {
045 Criteria pc = (Criteria) o;
046 switch (pc.getType())
047 {
048 case (Criteria.OR):
049 {
050 dnf.addAll(getDNF(pc));
051 break;
052 }
053 case (Criteria.AND):
054 {
055 dnf = getDnfAndDnf(dnf, getDNF(pc));
056 break;
057 }
058 }
059 }
060 else
061 {
062 SelectionCriteria c = (SelectionCriteria) o;
063 tmpCrit = new Criteria();
064 tmpCrit.getCriteria().add(c);
065 if (dnf.isEmpty())
066 {
067 dnf.add(tmpCrit);
068 }
069 else
070 {
071 //#ifdef JDK13
072 dnf = getDnfAndDnf(dnf, Collections.singletonList(tmpCrit));
073 //#else
074 /*
075 Vector singletonList = new Vector(1);
076 singletonList.add(tmpCrit);
077 dnf = getDnfAndDnf(dnf,singletonList);
078 */
079
080 //#endif
081
082
083 }
084 }
085 } // while
086
087 return dnf;
088 }
089
090 /**
091 * (a OR b) AND (c OR d) -> (a AND c) OR (a AND d) OR (b AND c) OR (b AND d)
092 */
093 private static List getDnfAndDnf(List dnf1, List dnf2)
094 {
095 ArrayList dnf = new ArrayList();
096
097 for (Iterator it1 = dnf1.iterator(); it1.hasNext(); )
098 {
099 Criteria crit1 = (Criteria) it1.next();
100
101 for (Iterator it2 = dnf2.iterator(); it2.hasNext(); )
102 {
103 Criteria crit2 = (Criteria) it2.next();
104 Criteria crit = new Criteria();
105 crit.getCriteria().addAll(crit1.getCriteria());
106 crit.getCriteria().addAll(crit2.getCriteria());
107 dnf.add(crit);
108 }
109 }
110
111 return dnf;
112 }
113 }
114