Unknown macro: {next_previous_links}
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

This sample demonstrates how to perform an advanced search using the "SearchAdminService". We will use the existing search-client sample and modify it for this sample.

  1. The Following code block contains the complete code of the sample. Replace the content of "SearchClient.java" in " G-REG_HOME/samples/search-client/src/org.wso2.carbon.registry.search.client/src/main/java/org/wso2/carbon/registry/search/client"  with the following code block

    SearchClient.java
    /*
    *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
    *
    *  WSO2 Inc. licenses this file to you under the Apache License,
    *  Version 2.0 (the "License"); you may not use this file except
    *  in compliance with the License.
    *  You may obtain a copy of the License at
    *
    *    http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing,
    * software distributed under the License is distributed on an
    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    * KIND, either express or implied.  See the License for the
    * specific language governing permissions and limitations
    * under the License.
    */
    package org.wso2.carbon.registry.search.client;
    import org.apache.axis2.AxisFault;
    import org.apache.axis2.Constants;
    import org.apache.axis2.client.Options;
    import org.apache.axis2.client.ServiceClient;
    import org.apache.axis2.context.ConfigurationContext;
    import org.apache.axis2.context.ConfigurationContextFactory;
    import org.apache.axis2.transport.http.HTTPConstants;
    import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
    import org.wso2.carbon.base.ServerConfiguration;
    import org.wso2.carbon.core.common.AuthenticationException;
    import org.wso2.carbon.governance.api.exception.GovernanceException;
    import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
    import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact;
    import org.wso2.carbon.governance.api.util.GovernanceUtils;
    import org.wso2.carbon.registry.core.Registry;
    import org.wso2.carbon.registry.core.exceptions.RegistryException;
    import org.wso2.carbon.registry.core.pagination.PaginationContext;
    import org.wso2.carbon.registry.core.session.UserRegistry;
    import org.wso2.carbon.registry.search.stub.SearchAdminServiceStub;
    import org.wso2.carbon.registry.search.stub.beans.xsd.AdvancedSearchResultsBean;
    import org.wso2.carbon.registry.search.stub.beans.xsd.ArrayOfString;
    import org.wso2.carbon.registry.search.stub.beans.xsd.CustomSearchParameterBean;
    import org.wso2.carbon.registry.search.stub.beans.xsd.SearchResultsBean;
    import org.wso2.carbon.registry.search.stub.common.xsd.ResourceData;
    import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
    import javax.xml.namespace.QName;
    import java.io.File;
    import java.net.URL;
    
    public class SearchClient {
        private static final String CARBON_HOME = ".." + File.separator + ".." +
                File.separator + ".." + File.separator + ".." + File.separator;
        private static final String axis2Repo = CARBON_HOME + File.separator + "repository" +
                File.separator + "deployment" + File.separator + "client";
        private static final String axis2Conf =
                ServerConfiguration.getInstance().getFirstProperty("Axis2Config.clientAxis2XmlLocation");
        private static final String username = "admin";
        private static final String password = "admin";
        private static final String serverURL = "https://localhost:9443/services/";
        private static ConfigurationContext configContext = null;
        private static Registry registry;
        private static String cookie;
        private static String epr;
        private static SearchAdminServiceStub stub;
        private static AuthenticationAdminStub authenticationAdminStub;
        private static CustomSearchParameterBean customSearchParameterBean;
    
        private static void initialize() throws Exception {
            System.setProperty("javax.net.ssl.trustStore", CARBON_HOME + File.separator + "repository" +
                    File.separator + "resources" + File.separator + "security" + File.separator +
                    "wso2carbon.jks");
            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            System.setProperty("carbon.repo.write.mode", "true");
            configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
                    axis2Repo, axis2Conf);
            epr = serverURL + "SearchAdminService";
            try {
                authenticate(configContext, serverURL, username, password);
                stub = new SearchAdminServiceStub(configContext, epr);
                ServiceClient client = stub._getServiceClient();
                Options options = client.getOptions();
                options.setManageSession(true);
                options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
                stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
                //Increase the time out when sending large attachments
                stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(1000000);
                registry = new WSRegistryServiceClient(serverURL, username, password, configContext);
            } catch (Exception axisFault) {
                String msg = "Failed to initiate WSRegistry Service client. " + axisFault.getMessage();
                throw new RegistryException(msg, axisFault);
            }
        }
    
        public static void main(String[] args) throws Exception {
            try {
                initialize();
                Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin");
                // Should be load the governance artifact.
                GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov);
                addServices(gov);
                SearchResultsBean searchResultsBean = getSearchResults();
                ResourceData[] resourceDatalist = searchResultsBean.getResourceDataList();
                for (ResourceData data : resourceDatalist) {
                    System.out.println("The tag search results -- " + data.getResourcePath());
                }
                AdvancedSearchResultsBean advancedSearchResultsBean = getAdvanceSearchResults();
                ResourceData[] advancedresourceDatalist = advancedSearchResultsBean.getResourceDataList();
                for (ResourceData data : advancedresourceDatalist) {
                    System.out.println("The advance search results -- " + data.getResourcePath());
                }
    
            } finally {
                PaginationContext.destroy();
            }
            System.exit(1);
        }
    
        public static boolean authenticate(ConfigurationContext ctx, String serverURL, String username, String password)
                throws AxisFault, AuthenticationException {
            String serviceEPR = serverURL + "AuthenticationAdmin";
            authenticationAdminStub = new AuthenticationAdminStub(ctx, serviceEPR);
            ServiceClient client = authenticationAdminStub._getServiceClient();
            Options options = client.getOptions();
            options.setManageSession(true);
            try {
                boolean result = authenticationAdminStub.login(username, password, new URL(serviceEPR).getHost());
                if (result) {
                    SearchClient.cookie = ((String) authenticationAdminStub._getServiceClient().getServiceContext().
                            getProperty(HTTPConstants.COOKIE_STRING));
                }
                return result;
            } catch (Exception e) {
                String msg = "Error occurred while logging in";
                throw new AuthenticationException(msg, e);
            }
        }
    
        public static SearchResultsBean getSearchResults() throws Exception {
            String searchType = "Tag";
            String criteria = "newtag";
            SearchResultsBean bean = null;
            try {
                bean = stub.getSearchResults(searchType, criteria);
                if (bean.getResourceDataList() == null) {
                    bean.setResourceDataList(new ResourceData[0]);
                }
            } catch (Exception e) {
                String msg = "Failed to get search results from the search service. " +
                        e.getMessage();
                throw new Exception(msg);
            }
            return bean;
        }
    
        public static AdvancedSearchResultsBean getAdvanceSearchResults() throws Exception {
            customSearchParameterBean = new CustomSearchParameterBean();
            String[][] parameterList = {{"resourcePath", "FlightService1"}, {"mediaType",
                    "application/vnd.wso2-service+xml"}};
            AdvancedSearchResultsBean bean = null;
            ArrayOfString[] arrayOfStrings = new ArrayOfString[parameterList.length];
            for (int i = 0; i < parameterList.length; i++) {
                ArrayOfString arr = new ArrayOfString();
                arr.addArray(parameterList[i][0]);
                if ("null".equals(parameterList[i][1])) {
                    arr.addArray("");
                } else {
                    arr.addArray(parameterList[i][1]);
                }
                arrayOfStrings[i] = arr;
            }
            customSearchParameterBean.setParameterValues(arrayOfStrings);
            try {
                bean = stub.getAdvancedSearchResults(customSearchParameterBean);
                if (bean.getResourceDataList() == null) {
                    bean.setResourceDataList(new ResourceData[0]);
                }
            } catch (Exception e) {
                String msg = "Failed to get search results from the search service. " +
                        e.getMessage();
                throw new Exception(msg);
            }
            return bean;
        }
    
        private static void addServices(Registry govRegistry) throws RegistryException {
            GenericArtifactManager artifactManager = new GenericArtifactManager(govRegistry, "service");
            System.out.println("#############################################\n");
            try{
            for (int i = 1; i < 10; i++) {
                System.out.println("Adding FlightService" + i + " ....");
                GenericArtifact artifact = artifactManager.newGovernanceArtifact(new QName("ns", "FlightService" + i));
                artifactManager.addGenericArtifact(artifact);
            }
            }catch (GovernanceException e){
                System.out.println("Services already added");
            }
            //Services need to be index before search.
            try {
                System.out.println("\n.....Waiting to index services .....!");
                Thread.sleep(2 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    


  2. In order to use the access the "SearchAdminService" we need to initialize "SearchAdminServiceStub" the following code segment initializes the stub and also initializes the registry object that will be needed to add sample data.

    private static void initialize() throws Exception {
    
            System.setProperty("javax.net.ssl.trustStore", CARBON_HOME + File.separator + "repository" +
                    File.separator + "resources" + File.separator + "security" + File.separator +
                    "wso2carbon.jks");
            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            System.setProperty("carbon.repo.write.mode", "true");
            configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
                    axis2Repo, axis2Conf);
            epr = serverURL + "SearchAdminService";
    
            try {
                authenticate(configContext, serverURL, username, password);
                stub = new SearchAdminServiceStub(configContext, epr);
                ServiceClient client = stub._getServiceClient();
                Options options = client.getOptions();
                options.setManageSession(true);
                options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
                stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
                //Increase the time out when sending large attachments
                stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(1000000);
                registry = new WSRegistryServiceClient(serverURL, username, password, configContext);
            } catch (Exception axisFault) {
                String msg = "Failed to initiate WSRegistry Service client. " + axisFault.getMessage();
                throw new RegistryException(msg, axisFault);
            }
        }
  3. The "SearchAdminService" provides two search methods, getSearchResults and getAdvancedSearchResults. 
  4. getSearchResults can be used to search by Tags. The following code segment invokes this method.

     public static SearchResultsBean getSearchResults() throws Exception {
            String searchType = "Tag";
            String criteria = "newtag";
            SearchResultsBean bean = null;
            try {
                bean = stub.getSearchResults(searchType, criteria);
                if (bean.getResourceDataList() == null) {
                    bean.setResourceDataList(new ResourceData[0]);
                }
            } catch (Exception e) {
                String msg = "Failed to get search results from the search service. " +
                        e.getMessage();
                throw new Exception(msg);
            }
            return bean;
        }
  5. getAdvancedSearchResults  can be utilized to do more advance searches. The following code segment searches for an resource which has media type of "application/vnd.wso2-service+xml" and has "FlightService1" in its resource path.

     public static AdvancedSearchResultsBean getAdvanceSearchResults() throws Exception {
    
            customSearchParameterBean = new CustomSearchParameterBean();
            String[][] parameterList = {{"resourcePath", "FlightService1"}, {"mediaType",
                    "application/vnd.wso2-service+xml"}};
            AdvancedSearchResultsBean bean = null;
            ArrayOfString[] arrayOfStrings = new ArrayOfString[parameterList.length];
            for (int i = 0; i < parameterList.length; i++) {
                ArrayOfString arr = new ArrayOfString();
                arr.addArray(parameterList[i][0]);
                if ("null".equals(parameterList[i][1])) {
                    arr.addArray("");
                } else {
                    arr.addArray(parameterList[i][1]);
                }
                arrayOfStrings[i] = arr;
            }
            customSearchParameterBean.setParameterValues(arrayOfStrings);
            try {
                bean = stub.getAdvancedSearchResults(customSearchParameterBean);
                if (bean.getResourceDataList() == null) {
                    bean.setResourceDataList(new ResourceData[0]);
                }
            } catch (Exception e) {
                String msg = "Failed to get search results from the search service. " +
                        e.getMessage();
                throw new Exception(msg);
            }
            return bean;
        }

    in addtion to "resourcePath" and "mediaType" there are several other parameters that can be set for the search the following is an list of all the values permitted. 

    Parameter NameValue
    resourcePathString
    contentString
    createdAfterString - ex "09/10/2013"
    createdBeforeString - ex "09/10/2013"
    createdRangeNegateString - "no" to negate. do not set otherwise
    updatedAfterString - ex "09/10/2013"
    updatedBeforeString - ex "09/10/2013"
    updatedRangeNegateString - "no" to negate. do not set otherwise
    authorString
    authorNameNegateString - "no" to negate. do not set otherwise
    updaterString
    updaterNameNegateString - "no" to negate. do not set otherwise
    tagsString
    commentWordsString
    associationTypeString
    associationDestString
    propertyNameString
    leftPropertyValueString - an Number ex- "12"
    rightPropertyValueString - an Number ex- "12"
    leftOpString - "gt", "ge"
    rightOpString - "lt","le","eq"
    mediaTypeString
    mediaTypeNegateString - "no" to negate. do not set otherwise


  6. To run the sample, go to the G-REG_HOME/bin and run the “ant” command. 


  7. Copy the "org.wso2.carbon.registry.search.stub_4.2.0.jar" from G-REG_HOME/repository/components/plugins folder to the G-REG_HOME/samples/search-client/src/org.wso2.carbon.registry.search.client/lib
  8. Open the command line window and navigate to the G-REG_HOME/bin.

    Linux: sh wso2server.sh
    Windows: wso2server.bat

    Note: Before you execute step 9 you have to keep the server on for five minutes to start the indexing process.

  9. Open a command window and navigate to G-REG_HOME/samples/search-client/src/org.wso2.carbon.registry.search.client and run the “ant” command. Now the sample executes and shows the result on the console.
    1. Add ten services (e.g. FlightService1, FlightService2 … FlightService10).
    2. Wait for two minutes to index the services.
    3. Now after a small delay for indexing you will be able to see the search results.

    In order to see results from "getSearchResults" search add a tag named "newtag" through the managment console to one or more of the services that are added when the sample is run for the first time

  • No labels