1 package org.apache.ojb.broker.query;
2
3 /* Copyright 2002-2005 The Apache Software Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 import java.util.*;
19
20 /**
21 * This Class contains utility functions for Criterias.
22 *
23 * @author <a href="mailto:on@ibis.odessa.ua">Oleg Nitz</a>
24 * @version $Id: CriteriaUtils.java,v 1.1 2007-08-24 22:17:36 ewestfal Exp $
25 */
26 public class CriteriaUtils
27 {
28
29 /**
30 * Disjunctive Normal Form: list of Criteria, which don't contain ORs,
31 * the elements of the list joined by ORs give the condition equivalent
32 * to the original Criteria.
33 */
34 public static List getDNF(Criteria crit)
35 {
36 List dnf = new ArrayList();
37 Enumeration e = crit.getElements();
38 Criteria tmpCrit;
39
40 while (e.hasMoreElements())
41 {
42 Object o = e.nextElement();
43 if (o instanceof Criteria)
44 {
45 Criteria pc = (Criteria) o;
46 switch (pc.getType())
47 {
48 case (Criteria.OR):
49 {
50 dnf.addAll(getDNF(pc));
51 break;
52 }
53 case (Criteria.AND):
54 {
55 dnf = getDnfAndDnf(dnf, getDNF(pc));
56 break;
57 }
58 }
59 }
60 else
61 {
62 SelectionCriteria c = (SelectionCriteria) o;
63 tmpCrit = new Criteria();
64 tmpCrit.getCriteria().add(c);
65 if (dnf.isEmpty())
66 {
67 dnf.add(tmpCrit);
68 }
69 else
70 {
71 //#ifdef JDK13
72 dnf = getDnfAndDnf(dnf, Collections.singletonList(tmpCrit));
73 //#else
74 /*
75 Vector singletonList = new Vector(1);
76 singletonList.add(tmpCrit);
77 dnf = getDnfAndDnf(dnf,singletonList);
78 */
79
80 //#endif
81
82
83 }
84 }
85 } // while
86
87 return dnf;
88 }
89
90 /**
91 * (a OR b) AND (c OR d) -> (a AND c) OR (a AND d) OR (b AND c) OR (b AND d)
92 */
93 private static List getDnfAndDnf(List dnf1, List dnf2)
94 {
95 ArrayList dnf = new ArrayList();
96
97 for (Iterator it1 = dnf1.iterator(); it1.hasNext(); )
98 {
99 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