/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.jaxr.read;

import org.jboss.test.jaxr.common.JaxrTestCase;

import javax.xml.registry.BulkResponse;
import javax.xml.registry.FindQualifier;
import javax.xml.registry.infomodel.Organization;
import javax.xml.registry.infomodel.Key;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Test case that reads an Organization from the Jaxr Registry
 * @author <mailto:Anil.Saldhana@jboss.org>Anil Saldhana
 */
public class JaxrReadTestCase
 extends JaxrTestCase {
    /**
     * Constructor
     * @param name
     */
    public JaxrReadTestCase(String name) {
        super(name);
    }
    /**
     * Test case that tests Jaxr Read
     * @throws Exception
     */
    public void testJaxrRead()
    throws Exception {
        if( connection == null ) connection = this.getConnection();
        //Clean up the registry
        this.clearOrganizations("JBoss");
        String key = this.createOrganization();
        assertNotNull("Key Obtained from saving the Org is null?",key);
        getOrgDetails( key );
    }

    /**
     * Given a key of an organization saved in the Jaxr Registry,
     * will try to get the details
     * @param orgid
     * @throws Exception
     */
    protected void getOrgDetails( String orgid)
    throws Exception {

        String querystr = "JBoss";

        if(bqm  == null )  bqm = this.getBusinessQueryManager();
        Collection findQualifiers = new ArrayList();
        findQualifiers.add(FindQualifier.CASE_SENSITIVE_MATCH);
        Collection namePatterns = new ArrayList();
        namePatterns.add("%" + querystr + "%");

        // Find orgs with name containing querystr
        BulkResponse response =
        bqm.findOrganizations(findQualifiers, namePatterns, null,
            null, null, null);
        Collection orgs = response.getCollection();

        System.out.println("getOrgDetails:Found orgs="+orgs.size());
        Iterator iter = orgs.iterator();
        while( iter.hasNext()){
            Organization org = (Organization)iter.next();
            String key = org.getKey().getId();
            System.out.println("Organization Key="+key);
            /**There is a bug.  The key returned while saving the organization
             * is an Association key when it should have been the Organization
             * key. The key returned while querying the organization seems to be
             * the right key.
             */
            //assertEquals("Org Ids the same?",key,orgid);
            assertNotNull("Org Key is null?",key);
        }
    }
}