
package lj_cust;

import java.util.*;
import wt.util.*;
import wt.fc.*;
import wt.vc.*;
import wt.query.*;
import wt.part.*;

public class MultiClassQuery {
    public static Enumeration findPartsNumbered(String number) throws WTException {

        // labels for the attributes
        final String OID = Persistable.PERSIST_INFO + "." + PersistInfo.OBJECT_IDENTIFIER + "." + ObjectIdentifier.ID;
        final String MASTER = Iterated.MASTER_REFERENCE + "." + ObjectReference.KEY + "." + ObjectIdentifier.ID;
        final int NO_JOIN = -1;

        // the multi-class query spec
        QuerySpec qs = new QuerySpec();
        final int versions = qs.appendClassList(WTPart.class, true);
        final int masters = qs.appendClassList(WTPartMaster.class, false);

        // the join condition: each part master is associated with its iteration(s)
        qs.appendSearchCondition(new SearchCondition(WTPartMaster.class, OID, WTPart.class, MASTER), masters, versions);
        qs.appendAnd();

        // search condition: the part master whose number matches the specified number
        qs.appendSearchCondition(new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL, number), masters, NO_JOIN);
        qs.appendAnd();

        // search condition: the iterations that are the latest of their branch (i.e. it the "versions")
        qs.appendSearchCondition(new SearchCondition(WTPart.class, Iterated.LATEST_ITERATION, SearchCondition.IS_TRUE), versions, NO_JOIN);

        // the new enumeration of objects constructed from the query result
        final QueryResult qr = PersistenceHelper.manager.find(qs);

        return new Enumeration() {
            public boolean hasMoreElements() {
                return qr.hasMoreElements();
            }
            public Object nextElement() throws NoSuchElementException {
                return ((Persistable[])qr.nextElement())[versions];
            }
        };
    }

    public static void main(String[] args) {
        // test program to query for all versions of a part whose number is specified on the command line and
        // print the identities of these to the console
        try {
            if (args.length < 1) {
                System.out.println("Usage: java lj_cust.MultiClassQuery <part number>"+
                " or windchill lj_cust.MultiClassQuery <part number>");
            } else {
                Enumeration e = findPartsNumbered(args[0]);
                while (e.hasMoreElements()) {
                    System.out.println(((WTPart)e.nextElement()).getIdentity());
                }
            }
        } catch (WTException wte) {
            wte.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}
