/**
   * Search the service artifacts stored in the registry and find the set of services that satisfy
   * the conditions stated in the given WS-D probe. If the probe does not impose any restrictions on
   * the result set, all the services in the registry will be returned.
   *
   * @param probe a WS-D probe describing the search criteria
   * @return an array of TargetService instances matching the probe or null
   * @throws Exception if an error occurs while accessing the registry
   */
  public static TargetService[] findServices(Probe probe) throws Exception {
    ServiceManager serviceManager = new ServiceManager(getRegistry());
    DiscoveryServiceFilter filter = new DiscoveryServiceFilter(probe);

    // Check whether the inactive services should be skipped when searching
    AxisConfiguration axisConfig;
    String tenantDomain =
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
    ConfigurationContext mainCfgCtx = ConfigHolder.getInstance().getServerConfigurationContext();
    if (tenantDomain != MultitenantConstants.SUPER_TENANT_DOMAIN_NAME) {
      axisConfig = TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, mainCfgCtx);
    } else {
      axisConfig = mainCfgCtx.getAxisConfiguration();
    }

    Parameter parameter = axisConfig.getParameter(DiscoveryConstants.SKIP_INACTIVE_SERVICES);
    filter.setSkipInactiveServices(parameter == null || "true".equals(parameter.getValue()));

    Service[] services = serviceManager.findServices(filter);
    if (services != null && services.length > 0) {
      TargetService[] targetServices = new TargetService[services.length];
      for (int i = 0; i < services.length; i++) {
        targetServices[i] = getTargetService(services[i]);
      }
      return targetServices;
    }
    return null;
  }
  public static void removeService(TargetService service, Map<String, String> headerMap)
      throws Exception {
    ServiceManager serviceManager = new ServiceManager(getRegistry());
    String serviceId = service.getEpr().getAddress();

    Service oldService = serviceManager.getService(serviceId);
    oldService.deactivate();
  }
  /**
   * Find the WS-D target service identified by the given WS-D identifier.
   *
   * @param epr WS-D service identifier
   * @return a TargetService instance with the given ID or null if no such service exists
   * @throws Exception if an error occurs while accessing the registry
   */
  public static TargetService getService(EndpointReference epr) throws Exception {
    ServiceManager serviceManager = new ServiceManager(getRegistry());
    Service service = serviceManager.getService(epr.getAddress());
    if (service == null) {
      return null;
    }

    return getTargetService(service);
  }
 private void addService(String nameSpace, String serviceName) throws RegistryException {
   ServiceManager serviceManager = new ServiceManager(governance);
   Service service;
   service = serviceManager.newService(new QName(nameSpace, serviceName));
   serviceManager.addService(service);
   for (String serviceId : serviceManager.getAllServiceIds()) {
     service = serviceManager.getService(serviceId);
     if (service.getPath().endsWith(serviceName)) {
       Resource resource = governance.get(service.getPath());
       resource.addProperty("x", "10");
       governance.put(service.getPath(), resource);
     }
   }
 }
 public void verifyService() throws RegistryException {
   ServiceManager serviceManager = new ServiceManager(governance);
   GovernanceUtils.loadGovernanceArtifacts(
       (UserRegistry) governance,
       GovernanceUtils.findGovernanceArtifactConfigurations(governance));
   Service[] services = serviceManager.getAllServices();
   boolean resourceFound = false;
   for (Service service : services) {
     if (service.getQName().getLocalPart().equals("SimpleStockQuoteService1M")) {
       resourceFound = true;
     }
   }
   Assert.assertTrue(resourceFound);
 }
  /** @throws Exception */
  @Test(
      groups = "wso2.greg",
      description = "Promote from Commencement to Creation",
      dependsOnMethods = "testAddLcToService")
  public void testPromoteToCreation() throws Exception {

    addRole("managerrole", userInfo.getUserNameWithoutDomain());
    lifeCycle = lifeCycleAdminServiceClient.getLifecycleBean(absPath);
    boolean isPermitted = false;
    for (String action : lifeCycle.getAvailableActions()[0].getActions()) {
      if (action.equalsIgnoreCase(ACTION_PROMOTE)) {
        isPermitted = true;
      }
    }
    assertTrue(isPermitted, "Not allowed to promote with permission");

    lifeCycleAdminServiceClient.invokeAspect(absPath, LC_NAME, ACTION_PROMOTE, null);

    Service[] services = serviceManager.getAllServices();

    for (Service service : services) {
      String path = service.getPath();
      if (path.contains("IntergalacticService13")) {
        serviceString = path;
      }
    }
    lifeCycle = lifeCycleAdminServiceClient.getLifecycleBean(absPath);

    for (Property prop : lifeCycle.getLifecycleProperties()) {
      if (("registry.lifecycle." + LC_NAME + ".state").equalsIgnoreCase(prop.getKey())) {
        assertNotNull(prop.getValues(), "State Value Not Found");
        assertTrue(
            prop.getValues()[0].equalsIgnoreCase(LC_STATE1),
            "Not promoted to Creation with permission");
      }
    }
  }
  /**
   * Add a discovered target service to the governance registry. This method will also create the
   * endpoint artifacts for the service and attach them with the related service artifacts. The
   * service artifact will be given an auto generated name.
   *
   * @param service WS-D target service to be added to the registry
   * @throws Exception if an error occurs while saving the artifacts to the registry
   */
  public static void addService(TargetService service, Map<String, String> headerMap)
      throws Exception {
    ServiceManager serviceManager = new ServiceManager(getRegistry());
    String serviceId = service.getEpr().getAddress();

    // This part is use to remove the prefix of Service ID
    if (serviceId.startsWith(DiscoveryConstants.EPR_ADDRESS_PREFIX)) {
      serviceId = serviceId.replace(DiscoveryConstants.EPR_ADDRESS_PREFIX, "");
    }

    // Delete the existing stuff and start fresh
    Service oldService = serviceManager.getService(serviceId);
    String serviceName = null;
    if (oldService != null) {
      // TODO: Change this once the necessary improvements are in the governance API
      serviceName = oldService.getQName().getLocalPart();
      serviceManager.removeService(serviceId);
    }

    // Create a new service (Use the discovery namespace)
    if (serviceName == null) {
      if (headerMap.containsKey(DiscoveryConstants.DISCOVERY_HEADER_SERVICE_NAME)) {
        serviceName =
            headerMap.get(DiscoveryConstants.DISCOVERY_HEADER_SERVICE_NAME).replace("/", "_");
      } else {
        serviceName =
            DiscoveryConstants.SERVICE_NAME_PREFIX + new GregorianCalendar().getTimeInMillis();
      }
    }

    Service newService =
        serviceManager.newService(
            new QName(DiscoveryConstants.WS_DISCOVERY_NAMESPACE, serviceName));
    newService.setId(serviceId);

    // Set the version if provided
    if (service.getMetadataVersion() != -1) {
      newService.addAttribute(
          DiscoveryConstants.ATTR_METADATA_VERSION, String.valueOf(service.getMetadataVersion()));
    }

    // Store other service metadata (scopes, types, x-addresses)
    QName[] types = service.getTypes();
    String typeList = "";
    if (types != null && types.length > 0) {
      for (int i = 0; i < types.length; i++) {
        typeList = typeList.concat(types[i].toString());
        if (i != types.length - 1) {
          typeList = typeList.concat(",");
        }
      }
    }
    newService.setAttribute(DiscoveryConstants.ATTR_TYPES, typeList);

    URI[] scopes = service.getScopes();
    String scopeList = "";
    if (scopes != null && scopes.length > 0) {
      for (int i = 0; i < scopes.length; i++) {
        scopeList = scopeList.concat(scopes[i].toString());
        if (i != scopes.length - 1) {
          scopeList = scopeList.concat(",");
        }
      }
    }
    newService.setAttribute(DiscoveryConstants.ATTR_SCOPES, scopeList);

    URI[] uris = service.getXAddresses();
    String[] endpoints = new String[uris.length];
    for (int i = 0; i < uris.length; i++) {
      endpoints[i] = ":" + uris[i].toString();
    }
    boolean activate = false;
    if (uris != null && uris.length > 0) {
      newService.setAttributes(DiscoveryConstants.ATTR_ENDPOINTS, endpoints);
      activate = true;
    }

    if (headerMap.containsKey(DiscoveryConstants.DISCOVERY_HEADER_WSDL_URI)
        && headerMap.get(DiscoveryConstants.DISCOVERY_HEADER_WSDL_URI) != "") {
      newService.setAttribute(
          "interface_wsdlURL", headerMap.get(DiscoveryConstants.DISCOVERY_HEADER_WSDL_URI));
    }

    // One hot discovered service coming thru....
    serviceManager.addService(newService);
    if (activate) {
      newService.activate();
    }
  }
 public static void remove(TargetService service) throws Exception {
   ServiceManager serviceManager = new ServiceManager(getRegistry());
   if (serviceManager.getService(service.getEpr().getAddress()) != null) {
     serviceManager.removeService(service.getEpr().getAddress());
   }
 }