Example #1
0
  public void testBackwardCompatibility() throws RegistryException {
    Registry rootRegistry = embeddedRegistryService.getSystemRegistry();
    Resource r1 = rootRegistry.newResource();
    r1.setContent("r1 content");
    rootRegistry.put("/test/comments/r1", r1);

    rootRegistry.addComment(
        "/test/comments/r1", new Comment("backward-compatibility1 on this resource :)"));
    rootRegistry.addComment(
        "/test/comments/r1", new Comment("backward-compatibility2 on this resource :)"));

    String sql =
        "SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC "
            + "WHERE C.REG_COMMENT_TEXT LIKE ? AND C.REG_ID=RC.REG_COMMENT_ID";

    Resource queryR = rootRegistry.newResource();
    queryR.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    queryR.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE);
    rootRegistry.put("/beep/x", queryR);
    Map<String, String> params = new HashMap<String, String>();
    params.put("query", sql);
    params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE);
    params.put("1", "backward-compatibility1%");
    Collection qResults = rootRegistry.executeQuery("/beep/x", params);

    String[] qPaths = (String[]) qResults.getContent();

    assertEquals("Query result count should be 1", qPaths.length, 1);
  }
  /**
   * @param policyStoreDTO
   * @return
   */
  public static void addPolicyToPDP(PolicyStoreDTO policyStoreDTO) throws EntitlementException {

    Registry registry;
    String policyPath;
    Collection policyCollection;
    Resource resource;

    Map.Entry<PolicyStoreManageModule, Properties> entry =
        EntitlementServiceComponent.getEntitlementConfig()
            .getPolicyStore()
            .entrySet()
            .iterator()
            .next();
    String policyStorePath = entry.getValue().getProperty("policyStorePath");

    if (policyStorePath == null) {
      policyStorePath = "/repository/identity/Entitlement/actualStore/";
    }

    if (policyStoreDTO == null
        || policyStoreDTO.getPolicy() == null
        || policyStoreDTO.getPolicy().trim().length() == 0
        || policyStoreDTO.getPolicyId() == null
        || policyStoreDTO.getPolicyId().trim().length() == 0) {
      return;
    }

    try {
      registry = EntitlementServiceComponent.getRegistryService().getGovernanceSystemRegistry();

      if (registry.resourceExists(policyStorePath)) {
        policyCollection = (Collection) registry.get(policyStorePath);
      } else {
        policyCollection = registry.newCollection();
      }

      registry.put(policyStorePath, policyCollection);
      policyPath = policyStorePath + policyStoreDTO.getPolicyId();

      if (registry.resourceExists(policyPath)) {
        resource = registry.get(policyPath);
      } else {
        resource = registry.newResource();
      }

      resource.setProperty("policyOrder", Integer.toString(policyStoreDTO.getPolicyOrder()));
      resource.setContent(policyStoreDTO.getPolicy());
      resource.setMediaType("application/xacml-policy+xml");
      AttributeDTO[] attributeDTOs = policyStoreDTO.getAttributeDTOs();
      if (attributeDTOs != null) {
        setAttributesAsProperties(attributeDTOs, resource);
      }
      registry.put(policyPath, resource);
    } catch (RegistryException e) {
      log.error(e);
      throw new EntitlementException("Error while adding policy to PDP", e);
    }
  }
Example #3
0
  public void testDefaultQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c3/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c3/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c3/r3";
    registry.put(r3Path, r3);

    registry.applyTag("/c3/r1", "java");
    registry.applyTag("/c3/r2", "jsp");
    registry.applyTag("/c3/r3", "ajax");

    String sql1 =
        "SELECT RT.REG_TAG_ID FROM REG_RESOURCE_TAG RT, REG_RESOURCE R "
            + "WHERE (R.REG_VERSION=RT.REG_VERSION OR "
            + "(R.REG_PATH_ID=RT.REG_PATH_ID AND R.REG_NAME=RT.REG_RESOURCE_NAME)) "
            + "AND R.REG_DESCRIPTION LIKE ? ORDER BY RT.REG_TAG_ID";

    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAGS_RESULT_TYPE);
    systemRegistry.put("/qs/q3", q1);

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("1", "%production%");
    Collection result = registry.executeQuery("/qs/q3", parameters);

    String[] tagPaths = result.getChildren();
    assertEquals("There should be two matching tags.", tagPaths.length, 2);

    Resource tag2 = registry.get(tagPaths[0]);
    assertEquals("First matching tag should be 'java'", (String) tag2.getContent(), "java");

    Resource tag1 = registry.get(tagPaths[1]);
    assertEquals("Second matching tag should be 'jsp'", (String) tag1.getContent(), "jsp");
  }
 /**
  * Remove trusted service
  *
  * @param groupName Group name
  * @param serviceName Service name
  * @param trustedService Trusted service name
  * @throws org.wso2.carbon.security.SecurityConfigException
  */
 private void removeTrustedService(String groupName, String serviceName, String trustedService)
     throws SecurityConfigException {
   Registry registry;
   String resourcePath;
   Resource resource;
   try {
     resourcePath =
         RegistryResources.SERVICE_GROUPS
             + groupName
             + RegistryResources.SERVICES
             + serviceName
             + "/trustedServices";
     registry = getConfigSystemRegistry();
     if (registry != null) {
       if (registry.resourceExists(resourcePath)) {
         resource = registry.get(resourcePath);
         if (resource.getProperty(trustedService) != null) {
           resource.removeProperty(trustedService);
         }
         registry.put(resourcePath, resource);
       }
     }
   } catch (Exception e) {
     String error = "Error occurred while removing trusted service for STS";
     log.error(error, e);
     throw new SecurityConfigException(error, e);
   }
 }
Example #5
0
  public static boolean addDefaultHandlersIfNotAvailable(Registry configSystemRegistry)
      throws RegistryException, FileNotFoundException, XMLStreamException {

    if (!configSystemRegistry.resourceExists(RegistryConstants.HANDLER_CONFIGURATION_PATH)) {
      Collection handlerConfigurationCollection = new CollectionImpl();
      String description = "Handler configurations are stored here.";
      handlerConfigurationCollection.setDescription(description);
      configSystemRegistry.put(
          RegistryConstants.HANDLER_CONFIGURATION_PATH, handlerConfigurationCollection);
      // We don't have any default handler configuration as in lifecycles.
    } else {
      // configue all handlers
      Resource handlerRoot = configSystemRegistry.get(getContextRoot());
      if (!(handlerRoot instanceof Collection)) {
        String msg =
            "Failed to continue as the handler configuration root: "
                + getContextRoot()
                + " is not a collection.";
        log.error(msg);
        throw new RegistryException(msg);
      }
      Collection handlerRootCol = (Collection) handlerRoot;
      String[] handlerConfigPaths = handlerRootCol.getChildren();
      if (handlerConfigPaths != null) {
        for (String handlerConfigPath : handlerConfigPaths) {
          generateHandler(configSystemRegistry, handlerConfigPath);
        }
      }
    }

    return true;
  }
Example #6
0
  public static String[] getHandlerList(Registry configSystemRegistry) throws RegistryException {
    Collection collection;
    try {
      collection = (Collection) configSystemRegistry.get(getContextRoot());
    } catch (Exception e) {
      return null;
    }

    if (collection == null) {
      CollectionImpl handlerCollection = new CollectionImpl();
      configSystemRegistry.put(getContextRoot(), handlerCollection);
      return null;
    } else {
      if (collection.getChildCount() == 0) {
        return null;
      }

      String[] childrenList = collection.getChildren();
      String[] handlerNameList = new String[collection.getChildCount()];
      for (int i = 0; i < childrenList.length; i++) {
        String path = childrenList[i];
        handlerNameList[i] = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
      }
      return handlerNameList;
    }
  }
 /**
  * Creates a collection in the given common location.
  *
  * @param commonLocation location to create the collection.
  * @throws RegistryException If fails to create a collection at given location.
  */
 private void createCollection(String commonLocation) throws RegistryException {
   Registry systemRegistry = CommonUtil.getUnchrootedSystemRegistry(requestContext);
   // Creating a collection if not exists.
   if (!systemRegistry.resourceExists(commonLocation)) {
     systemRegistry.put(commonLocation, systemRegistry.newCollection());
   }
 }
Example #8
0
  public static boolean addHandler(Registry configSystemRegistry, String payload)
      throws RegistryException, XMLStreamException {
    String name;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      name = element.getAttributeValue(new QName("class"));
    } else return false;

    if (isHandlerNameInUse(name))
      throw new RegistryException("The added handler name is already in use!");

    String path = getContextRoot() + name;
    Resource resource;
    if (!handlerExists(configSystemRegistry, name)) {
      resource = new ResourceImpl();
    } else {
      throw new RegistryException("The added handler name is already in use!");
    }
    resource.setContent(payload);
    try {
      configSystemRegistry.beginTransaction();
      configSystemRegistry.put(path, resource);
      generateHandler(configSystemRegistry, path);
      configSystemRegistry.commitTransaction();
    } catch (Exception e) {
      configSystemRegistry.rollbackTransaction();
      throw new RegistryException("Unable to generate handler", e);
    }
    return true;
  }
Example #9
0
  public void testWithoutTableParamsQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c1/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c2/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c2/r3";
    registry.put(r3Path, r3);

    String sql1 =
        "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE, " + "REG_TAG WHERE REG_DESCRIPTION LIKE ?";
    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
    systemRegistry.put("/qs/q1", q1);

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("1", "%production%");
    Resource result = registry.executeQuery("/qs/q1", parameters);

    assertTrue(
        "Search with result type Resource should return a directory.",
        result instanceof org.wso2.carbon.registry.core.Collection);

    List<String> matchingPaths = new ArrayList<String>();
    String[] paths = (String[]) result.getContent();
    matchingPaths.addAll(Arrays.asList(paths));

    assertTrue("Path /c1/r1 should be in the results.", matchingPaths.contains("/c1/r1"));
    assertTrue("Path /c2/r2 should be in the results.", matchingPaths.contains("/c2/r2"));
  }
  /**
   * Method to obtain the custom UI media types.
   *
   * @param configSystemRegistry a configuration system registry instance.
   * @return a String of custom UI media types, in the format name:type,name:type,...
   * @throws RegistryException if the operation failed.
   */
  public static String getCustomUIMediaTypeMappings(Registry configSystemRegistry)
      throws RegistryException {

    RegistryContext registryContext = configSystemRegistry.getRegistryContext();

    if (getCustomUIMediaTypeMappings(registryContext) != null) {
      return getCustomUIMediaTypeMappings(registryContext);
    }

    Resource resource;
    String mediaTypeString = null;

    String resourcePath =
        MIME_TYPE_COLLECTION + RegistryConstants.PATH_SEPARATOR + RESOURCE_MIME_TYPE_INDEX;

    // TODO: Adding the media types should ideally be done by the handler associated with the
    // media type
    if (!configSystemRegistry.resourceExists(resourcePath)) {
      getResourceMediaTypeMappings(configSystemRegistry);
    }
    if (!configSystemRegistry.resourceExists(
        resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX)) {
      resource = configSystemRegistry.newResource();
      resource.setProperty("profiles", "application/vnd.wso2-profiles+xml");
      // resource.setProperty("service", "application/vnd.wso2-service+xml");
      resource.setDescription(
          "This resource contains the media Types associated with "
              + "custom user interfaces on the Registry. Add, Edit or Delete properties to "
              + "Manage Media Types.");
      configSystemRegistry.put(
          resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX, resource);
    } else {
      resource =
          configSystemRegistry.get(
              resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX);
    }
    Properties properties = resource.getProperties();
    if (properties.size() > 0) {
      Set<Object> keySet = properties.keySet();
      for (Object key : keySet) {
        if (key instanceof String) {
          String ext = (String) key;
          if (RegistryUtils.isHiddenProperty(ext)) {
            continue;
          }
          String value = resource.getProperty(ext);
          String mediaTypeMapping = ext + ":" + value;
          if (mediaTypeString == null) {
            mediaTypeString = mediaTypeMapping;
          } else {
            mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
          }
        }
      }
    }
    registryContext.setCustomUIMediaTypes(mediaTypeString);
    return mediaTypeString;
  }
Example #11
0
 public RegistryManager() {
   try {
     if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO)) {
       registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO, registry.newCollection());
     }
   } catch (RegistryException e) {
     String msg = "Error while accessing registry or initializing domain mapping registry path\n";
     log.error(msg + e.getMessage());
   }
 }
Example #12
0
  public void testWithoutWhereQuery() throws Exception {
    Resource r1 = registry.newResource();
    String r1Content = "this is r1 content";
    r1.setContent(r1Content.getBytes());
    r1.setDescription("production ready.");
    String r1Path = "/c1/r1";
    registry.put(r1Path, r1);

    Resource r2 = registry.newResource();
    String r2Content = "content for r2 :)";
    r2.setContent(r2Content);
    r2.setDescription("ready for production use.");
    String r2Path = "/c2/r2";
    registry.put(r2Path, r2);

    Resource r3 = registry.newResource();
    String r3Content = "content for r3 :)";
    r3.setContent(r3Content);
    r3.setDescription("only for government use.");
    String r3Path = "/c2/r3";
    registry.put(r3Path, r3);

    String sql1 = "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE, REG_TAG";
    Resource q1 = systemRegistry.newResource();
    q1.setContent(sql1);
    q1.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
    q1.addProperty(
        RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
    systemRegistry.put("/qs/q1", q1);

    Map parameters = new HashMap();
    Resource result = registry.executeQuery("/qs/q1", parameters);

    assertTrue(
        "Search with result type Resource should return a directory.",
        result instanceof org.wso2.carbon.registry.core.Collection);

    String[] paths = (String[]) result.getContent();
    assertTrue("Should return all the resources", paths.length >= 3);
  }
 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 static boolean putRegistryResource(String path, Resource resource)
     throws DynamicClientRegistrationException {
   boolean status;
   try {
     Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry();
     governanceRegistry.beginTransaction();
     governanceRegistry.put(path, resource);
     governanceRegistry.commitTransaction();
     status = true;
   } catch (RegistryException e) {
     throw new DynamicClientRegistrationException(
         "Error occurred while persisting registry resource : " + e.getMessage(), e);
   }
   return status;
 }
 private void addSchema() throws IOException, RegistryException {
   SchemaManager schemaManager = new SchemaManager(governance);
   String schemaFilePath =
       ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME)
           + File.separator
           + "schema"
           + File.separator;
   Schema schema =
       schemaManager.newSchema(
           FileManager.readFile(schemaFilePath + "Person.xsd").getBytes(), "Person.xsd");
   schemaManager.addSchema(schema);
   schema = schemaManager.getSchema(schema.getId());
   Resource resource = governance.get(schema.getPath());
   resource.addProperty("z", "30");
   governance.put(schema.getPath(), resource);
 }
 private void addPolicy() throws RegistryException, IOException {
   PolicyManager policyManager = new PolicyManager(governance);
   String policyFilePath =
       ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME)
           + File.separator
           + "policy"
           + File.separator;
   Policy policy =
       policyManager.newPolicy(
           FileManager.readFile(policyFilePath + "UTPolicy.xml").getBytes(), "UTPolicy.xml");
   policyManager.addPolicy(policy);
   policy = policyManager.getPolicy(policy.getId());
   Resource resource = governance.get(policy.getPath());
   resource.addProperty("abcxyzpqr", "40");
   governance.put(policy.getPath(), resource);
 }
 private void addWSDL() throws IOException, RegistryException {
   WsdlManager wsdlManager = new WsdlManager(governance);
   Wsdl wsdl;
   String wsdlFilePath =
       ProductConstant.getResourceLocations(ProductConstant.GREG_SERVER_NAME)
           + File.separator
           + "wsdl"
           + File.separator;
   wsdl =
       wsdlManager.newWsdl(
           FileManager.readFile(wsdlFilePath + "echo.wsdl").getBytes(), "echo.wsdl");
   wsdlManager.addWsdl(wsdl);
   wsdl = wsdlManager.getWsdl(wsdl.getId());
   Resource resource = governance.get(wsdl.getPath());
   resource.addProperty("y", "20");
   governance.put(wsdl.getPath(), resource);
 }
  public void testSimpleLifecycle() throws Exception {
    final String RESOURCE = "/r1";
    final String LIFECYCLE = "simpleLifecycle";

    RegistryContext context = registry.getRegistryContext();
    context.selectDBConfig("h2-db");
    context.addAspect(LIFECYCLE, new SimpleLifecycle(), MultitenantConstants.SUPER_TENANT_ID);

    String[] aspects = registry.getAvailableAspects();
    assertTrue(aspects.length > 0);
    boolean found = false;
    for (String aspect : aspects) {
      if (aspect.equals(LIFECYCLE)) {
        found = true;
      }
    }
    assertTrue("Lifecycle not found in available aspects", found);

    Resource resource = registry.newResource();
    resource.setDescription("My thing");
    registry.put(RESOURCE, resource);

    registry.associateAspect(RESOURCE, LIFECYCLE);

    resource = registry.get(RESOURCE);
    assertNotNull(resource);
    String propValue = resource.getProperty(SimpleLifecycle.STATE_PROP);
    assertNotNull(propValue);
    assertEquals("Wrong initial state!", SimpleLifecycle.INIT, propValue);

    String[] actions = registry.getAspectActions(RESOURCE, LIFECYCLE);
    assertNotNull("No available actions", actions);
    assertEquals("Wrong # of available actions", 1, actions.length);
    assertEquals("Wrong available action", SimpleLifecycle.ACTION, actions[0]);

    registry.invokeAspect(RESOURCE, LIFECYCLE, SimpleLifecycle.ACTION);

    resource = registry.get(RESOURCE);

    // OK, now we should be in the next state
    propValue = resource.getProperty(SimpleLifecycle.STATE_PROP);
    assertNotNull(propValue);
    assertEquals("Wrong state!", SimpleLifecycle.FINAL, propValue);
  }
  /**
   * Saves a swagger document in the registry.
   *
   * @param contentStream resource content.
   * @param path resource path.
   * @param documentVersion version of the swagger document.
   * @throws RegistryException If fails to add the swagger document to registry.
   */
  private boolean addSwaggerDocumentToRegistry(
      ByteArrayOutputStream contentStream, String path, String documentVersion)
      throws RegistryException {
    Resource resource;
    /*
    Checks if a resource is already exists in the given path.
    If exists,
    	Compare resource contents and if updated, updates the document, if not skip the updating process
    If not exists,
    	Creates a new resource and add to the resource path.
     */
    if (registry.resourceExists(path)) {
      resource = registry.get(path);
      Object resourceContentObj = resource.getContent();
      String resourceContent;
      if (resourceContentObj instanceof String) {
        resourceContent = (String) resourceContentObj;
        resource.setContent(RegistryUtils.encodeString(resourceContent));
      } else if (resourceContentObj instanceof byte[]) {
        resourceContent = RegistryUtils.decodeBytes((byte[]) resourceContentObj);
      } else {
        throw new RegistryException(CommonConstants.INVALID_CONTENT);
      }
      if (resourceContent.equals(contentStream.toString())) {
        log.info("Old content is same as the new content. Skipping the put action.");
        return false;
      }
    } else {
      // If a resource does not exist in the given path.
      resource = new ResourceImpl();
    }

    String resourceId =
        (resource.getUUID() == null) ? UUID.randomUUID().toString() : resource.getUUID();

    resource.setUUID(resourceId);
    resource.setMediaType(CommonConstants.SWAGGER_MEDIA_TYPE);
    resource.setContent(contentStream.toByteArray());
    resource.addProperty(RegistryConstants.VERSION_PARAMETER_NAME, documentVersion);
    CommonUtil.copyProperties(this.requestContext.getResource(), resource);
    registry.put(path, resource);

    return true;
  }
  private static void addToRegistry(String rootPath, File file, int tenantId) {
    try {
      Registry registry = getRegistry(tenantId);

      // This path is used to store the file resource under registry
      String fileRegistryPath =
          REGISTRY_GADGET_STORAGE_PATH
              + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

      // Adding the file to the Registry
      Resource fileResource = registry.newResource();
      fileResource.setMediaType("application/vnd.wso2-gadget+xml");
      fileResource.setContentStream(new FileInputStream(file));
      registry.put(fileRegistryPath, fileResource);

    } catch (RegistryException e) {
      log.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
      log.error(e.getMessage(), e);
    }
  }
Example #21
0
  public boolean addDomainMappingToRegistry(String hostName, String actualHost)
      throws ADCException, RegistryException {
    boolean successfullyAdded = false;
    try {

      registry.beginTransaction();
      Resource hostResource = registry.newResource();
      hostResource.addProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST, actualHost);
      if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO + hostName)) {
        registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO + hostName, hostResource);
        successfullyAdded = true;
      } else {
        registry.rollbackTransaction();
        String msg = "Requested domain is already taken!";
        log.error(msg);
        throw new ADCException(msg);
      }
      registry.commitTransaction();
    } catch (RegistryException e) {
      registry.rollbackTransaction();
    }
    return successfullyAdded;
  }
  /**
   * Adds the service endpoint element to the registry.
   *
   * @param requestContext current request information.
   * @param endpointElement endpoint metadata element.
   * @param endpointPath endpoint location.
   * @return The resource path of the endpoint.
   * @throws RegistryException If fails to add the endpoint to the registry.
   */
  public static String addEndpointToRegistry(
      RequestContext requestContext, OMElement endpointElement, String endpointPath)
      throws RegistryException {

    if (requestContext == null || endpointElement == null || endpointPath == null) {
      throw new IllegalArgumentException(
          "Some or all of the arguments may be null. Cannot add the endpoint to registry. ");
    }

    endpointPath = getEndpointPath(requestContext, endpointElement, endpointPath);

    Registry registry = requestContext.getRegistry();
    // Creating new resource.
    Resource endpointResource = new ResourceImpl();
    // setting endpoint media type.
    endpointResource.setMediaType(CommonConstants.ENDPOINT_MEDIA_TYPE);
    // set content.
    endpointResource.setContent(RegistryUtils.encodeString(endpointElement.toString()));
    // copy other property
    endpointResource.setProperties(copyProperties(requestContext));
    // set path
    // endpointPath = getChrootedEndpointLocation(requestContext.getRegistryContext()) +
    // endpointPath;

    String resourceId = endpointResource.getUUID();
    // set resource UUID
    resourceId = (resourceId == null) ? UUID.randomUUID().toString() : resourceId;

    endpointResource.setUUID(resourceId);
    // saving the api resource to repository.
    registry.put(endpointPath, endpointResource);
    if (log.isDebugEnabled()) {
      log.debug("Endpoint created at " + endpointPath);
    }
    return endpointPath;
  }
  /**
   * method to persist credentials of a jira account
   *
   * @param registry Registry
   * @param accountInfo AccountInfo
   * @throws IssueTrackerException thrown id unable to store resources in the registry
   */
  public static void persistCredentials(Registry registry, AccountInfo accountInfo)
      throws IssueTrackerException {

    Resource resource = null;

    String path = IssueTrackerConstants.ISSUE_TRACKERS_RESOURCE_PATH + accountInfo.getKey();

    try {
      // if the collection does not exist create one
      if (!registry.resourceExists(IssueTrackerConstants.ISSUE_TRACKERS_RESOURCE_PATH)) {
        Collection collection = registry.newCollection();
        registry.put(IssueTrackerConstants.ISSUE_TRACKERS_RESOURCE_PATH, collection);
      }

      // get registry resource
      if (registry.resourceExists(path)) {
        resource = registry.get(path);
      } else {
        resource = registry.newResource();
      }
    } catch (RegistryException e) {
      ExceptionHandler.handleException("Error accessing registry", e, log);
    }

    // get credentials from account info
    GenericCredentials credentials;
    credentials = accountInfo.getCredentials();

    // set properties of the registry resources
    if (resource != null) {
      resource.addProperty(IssueTrackerConstants.ACCOUNT_KEY, accountInfo.getKey());
      resource.addProperty(IssueTrackerConstants.ISSUE_TRACKER_URL, credentials.getUrl());
      resource.addProperty(IssueTrackerConstants.ACCOUNT_LOGIN_USERNAME, credentials.getUsername());
      resource.addProperty(IssueTrackerConstants.ACCOUNT_EMAIL, accountInfo.getEmail());
      resource.addProperty(IssueTrackerConstants.ACCOUNT_UID, accountInfo.getUid());
      resource.addProperty(
          IssueTrackerConstants.HAS_SUPPORT_ACCOUNT,
          String.valueOf(accountInfo.isHasSupportAccount()));

      // set properties related with automatic reporting
      if (accountInfo.isAutoReportingEnable()) {

        AutoReportingSettings settings = accountInfo.getAutoReportingSettings();
        resource.addProperty(
            IssueTrackerConstants.AUTO_REPORTING, IssueTrackerConstants.IS_AUTO_REPORTING_ENABLED);
        resource.addProperty(
            IssueTrackerConstants.AUTO_REPORTING_PROJECT, settings.getProjectName());
        resource.addProperty(IssueTrackerConstants.AUTO_REPORTING_PRIORITY, settings.getPriority());
        resource.addProperty(
            IssueTrackerConstants.AUTO_REPORTING_ISSUE_TYPE, settings.getIssueType());

      } else {
        resource.addProperty(
            IssueTrackerConstants.AUTO_REPORTING, IssueTrackerConstants.IS_AUTO_REPORTING_DISABLED);
      }

      // encrypt and store password
      String password = credentials.getPassword();

      if (null != password && !"".equals(password)) {
        byte[] bytes = (password).getBytes();

        try {
          String base64String = CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(bytes);
          resource.addProperty(
              IssueTrackerConstants.ACCOUNT_PASSWORD_HIDDEN_PROPERTY, base64String);
        } catch (org.wso2.carbon.core.util.CryptoException e) {
          ExceptionHandler.handleException("Error accessing registry", e, log);
        }
      }
    }

    // put resource to registry
    try {
      registry.put(path, resource);
    } catch (RegistryException e) {
      ExceptionHandler.handleException("Error while persisting accountInfo", e, log);
    }
  }
  /**
   * This method is used to load custom security scenarios used inside Identity STS componsnts.
   *
   * @throws Exception
   */
  private void loadSecurityScenarios() throws Exception {

    Registry registry = registryService.getConfigSystemRegistry();

    try {
      // Scenarios are listed in resources/scenario-config.xml
      URL resource = bundleContext.getBundle().getResource("scenario-config.xml");
      XmlConfiguration xmlConfiguration =
          new XmlConfiguration(resource.openStream(), SecurityConstants.SECURITY_NAMESPACE);

      OMElement[] elements = xmlConfiguration.getElements("//ns:Scenario");

      boolean transactionStarted = Transaction.isStarted();
      if (!transactionStarted) {
        registry.beginTransaction();
      }

      for (OMElement scenarioEle : elements) {
        SecurityScenario scenario = new SecurityScenario();
        String scenarioId = scenarioEle.getAttribute(SecurityConstants.ID_QN).getAttributeValue();

        scenario.setScenarioId(scenarioId);
        scenario.setSummary(
            scenarioEle.getFirstChildWithName(SecurityConstants.SUMMARY_QN).getText());
        scenario.setDescription(
            scenarioEle.getFirstChildWithName(SecurityConstants.DESCRIPTION_QN).getText());
        scenario.setCategory(
            scenarioEle.getFirstChildWithName(SecurityConstants.CATEGORY_QN).getText());
        scenario.setWsuId(scenarioEle.getFirstChildWithName(SecurityConstants.WSUID_QN).getText());
        scenario.setType(scenarioEle.getFirstChildWithName(SecurityConstants.TYPE_QN).getText());

        OMElement genPolicyElem =
            scenarioEle.getFirstChildWithName(SecurityConstants.IS_GEN_POLICY_QN);
        if (genPolicyElem != null && genPolicyElem.getText().equals("false")) {
          scenario.setGeneralPolicy(false);
        }

        String resourceUri = SecurityConstants.SECURITY_POLICY + "/" + scenarioId;

        for (Iterator modules =
                scenarioEle.getFirstChildWithName(SecurityConstants.MODULES_QN).getChildElements();
            modules.hasNext(); ) {
          String module = ((OMElement) modules.next()).getText();
          scenario.addModule(module);
        }

        // Save it in the DB
        SecurityScenarioDatabase.put(scenarioId, scenario);

        // Store the scenario in the Registry
        if (!scenarioId.equals(SecurityConstants.SCENARIO_DISABLE_SECURITY)
            && !scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
          Resource scenarioResource = new ResourceImpl();
          scenarioResource.setContentStream(
              bundleContext.getBundle().getResource(scenarioId + "-policy.xml").openStream());
          if (!registry.resourceExists(resourceUri)) {
            registry.put(resourceUri, scenarioResource);
          }
        }
      }
      if (!transactionStarted) {
        registry.commitTransaction();
      }
    } catch (Exception e) {
      registry.rollbackTransaction();
      throw e;
    }
  }
  public void testLifecycle() throws RegistryException {

    Resource r1 = registry.newResource();
    byte[] r1content = RegistryUtils.encodeString("R1 content");
    r1.setContent(r1content);
    registry.put("/d12/r1", r1);

    String text1 = "this can be used as a test resource.";
    String text2 = "I like this";
    final Comment comment1 = new Comment(text1);
    comment1.setUser("someone");
    registry.addComment("/d12/r1", comment1);
    final Comment comment2 = new Comment(text2);
    comment2.setUser("someone");
    registry.addComment("/d12/r1", comment2);

    Comment[] comments = registry.getComments("/d12/r1");
    Assert.assertNotNull(registry.get("/d12/r1").getContent());

    boolean commentFound = false;
    for (Comment comment : comments) {
      if (comment.getText().equals(text1)) {
        commentFound = true;
        break;
      }
    }
    Assert.assertTrue(
        "comment '" + text1 + "' is not associated with the artifact /d12/r1", commentFound);

    Resource commentsResource = registry.get("/d12/r1;comments");
    Assert.assertTrue(
        "Comment collection resource should be a directory.",
        commentsResource instanceof Collection);
    comments = (Comment[]) commentsResource.getContent();

    List commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(commentResource.getContent());
    }

    Assert.assertTrue(
        text1 + " is not associated for resource /d12/r1.", commentTexts.contains(text1));
    Assert.assertTrue(
        text2 + " is not associated for resource /d12/r1.", commentTexts.contains(text2));

    registry.associateAspect("/d12/r1", LIFECYCLE_NAME);

    registry.invokeAspect("/d12/r1", LIFECYCLE_NAME, "promote");

    Resource resource = registry.get("/developed/d12/r1");
    Assert.assertNotNull(resource);
    Assert.assertNotNull(resource.getContent());

    comments = registry.getComments("/developed/d12/r1");

    commentFound = false;
    for (Comment comment : comments) {
      if (comment.getText().equals(text1)) {
        commentFound = true;
        break;
      }
    }
    Assert.assertTrue(
        "comment '" + text1 + "' is not associated with the artifact /developed/d12/r1",
        commentFound);

    commentsResource = registry.get("/developed/d12/r1;comments");
    Assert.assertTrue(
        "Comment collection resource should be a directory.",
        commentsResource instanceof Collection);
    comments = (Comment[]) commentsResource.getContent();

    commentTexts = new ArrayList();
    for (Comment comment : comments) {
      Resource commentResource = registry.get(comment.getPath());
      commentTexts.add(commentResource.getContent());
    }

    Assert.assertTrue(
        text1 + " is not associated for resource /developed/d12/r1.", commentTexts.contains(text1));
    Assert.assertTrue(
        text2 + " is not associated for resource /developed/d12/r1.", commentTexts.contains(text2));
  }
  private static void transferDirectoryContentToRegistry(
      File rootDirectory, Registry registry, String rootPath, int tenantId) throws Exception {

    try {

      File[] filesAndDirs = rootDirectory.listFiles();
      List<File> filesDirs = Arrays.asList(filesAndDirs);

      for (File file : filesDirs) {

        if (!file.isFile()) {
          // This is a Directory add a new collection
          // This path is used to store the file resource under registry
          String directoryRegistryPath =
              REGISTRY_GADGET_STORAGE_PATH
                  + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

          // If the collection exists no need to create it. If not, create.
          if (!registry.resourceExists(directoryRegistryPath)) {
            Collection newCollection = registry.newCollection();
            registry.put(directoryRegistryPath, newCollection);
          }

          // Set permission for anonymous read. We do it here because it should happen always in
          // order
          // to support mounting a remote registry.
          UserRegistry userRegistry = getRegistry(tenantId);
          AuthorizationManager accessControlAdmin =
              userRegistry.getUserRealm().getAuthorizationManager();

          if (!accessControlAdmin.isRoleAuthorized(
              CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
              RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
              ActionConstants.GET)) {
            accessControlAdmin.authorizeRole(
                CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
                ActionConstants.GET);
          }

          // recurse
          transferDirectoryContentToRegistry(file, registry, rootPath, tenantId);
        } else {
          // Adding gadget to the gadget browser: gadget conf.xml need to be present
          if (file.getName().equals(GADGET_CONF_FILE)) {
            FileInputStream fis = new FileInputStream(file);
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader reader = xif.createXMLStreamReader(fis);

            StAXOMBuilder builder = new StAXOMBuilder(reader);
            OMElement omEle = builder.getDocumentElement();

            String gadgetName = omEle.getFirstChildWithName(new QName("name")).getText();
            String gadgetPath = omEle.getFirstChildWithName(new QName("path")).getText();
            String gadgetDesc = omEle.getFirstChildWithName(new QName("description")).getText();

            Resource res = registry.newResource();
            res.setProperty(DashboardConstants.GADGET_NAME, gadgetName);
            res.setProperty(DashboardConstants.GADGET_DESC, gadgetDesc);
            res.setProperty(DashboardConstants.GADGET_URL, gadgetPath);

            registry.put(
                DashboardConstants.SYSTEM_GADGETREPO_REGISTRY_ROOT
                    + DashboardConstants.GADGETS_COL
                    + "/"
                    + gadgetName,
                res);

          } else {
            // Add this to registry
            addToRegistry(rootPath, file, tenantId);
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new Exception(e);
    }
  }
Example #27
0
  public static boolean updateHandler(Registry configSystemRegistry, String oldName, String payload)
      throws RegistryException, XMLStreamException {
    if (isHandlerNameInUse(oldName))
      throw new RegistryException("Could not update handler since it is already in use!");

    String newName = null;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      newName = element.getAttributeValue(new QName("class"));
    }

    if (newName == null || newName.equals("")) return false; // invalid configuration

    if (oldName == null || oldName.equals("")) {
      String path = getContextRoot() + newName;
      Resource resource;
      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are adding a new handler
      } else {
        resource = new ResourceImpl();
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(path, resource);
        generateHandler(configSystemRegistry, path);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    }

    if (newName.equals(oldName)) {
      // updating the rest of the content
      String oldPath = getContextRoot() + oldName;
      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.put(oldPath, resource);
        generateHandler(configSystemRegistry, oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    } else {
      String oldPath = getContextRoot() + oldName;
      String newPath = getContextRoot() + newName;

      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are trying to use the name of a existing handler
      }

      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }

      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(newPath, resource);
        generateHandler(configSystemRegistry, newPath);
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.delete(oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to renew handler", e);
      }
      return true;
    }
  }
Example #28
0
  /**
   * Simulates a configSystemRegistry operation.
   *
   * <p>Operation criteria: get - path put - path, resourcePath (existing resource), optional :
   * mediaType resourceExists - path delete - path importResource - path, param1 (URL: source URL),
   * optional : mediaType copy - path, param1 (target path) move - path, param1 (target path) rename
   * - path, param1 (target path) removeLink - path createLink - path, param1 (target path),
   * optional : param2 (target sub-path) invokeAspect - path, param1 (aspect name), param2 (action)
   * addAssociation - path, param1 (target path), param2 (association type) removeAssociation -
   * path, param1 (target path), param2 (association type) getAssociations - path, param1
   * (association type) getAllAssociations - path createVersion - path restoreVersion - path
   * getVersions - path applyTag - path, param1 (tag) removeTag - path, param1 (tag) getTags - path
   * getResourcePathsWithTag - param1 (tag) rateResource - path, param1 (Number: rating) getRating -
   * path, param1 (username) getAverageRating - path addComment - path, param1 (comment)
   * removeComment - path editComment - path, param1 (comment) getComments - path searchContent -
   * param1 (keywords) executeQuery - param1 (Map: parameters, ex:- key1:val1,key2:val2,...),
   * optional: path
   *
   * <p>Operations not-supported dump restore
   *
   * @param simulationRequest the simulation request.
   * @throws Exception if an exception occurs while executing any operation, or if an invalid
   *     parameter was entered.
   */
  public static void simulateRegistryOperation(
      Registry rootRegistry, SimulationRequest simulationRequest) throws Exception {
    String operation = simulationRequest.getOperation();
    if (operation == null) {
      return;
    }
    if (operation.toLowerCase().equals("get")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.get(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("resourceexists")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.resourceExists(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("put")) {
      String path = simulationRequest.getPath();
      String resourcePath = simulationRequest.getResourcePath();
      String type = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        type = params[0];
      }

      if (isInvalidateValue(path) || isInvalidateValue(type)) {
        return;
      }
      Resource resource;
      if (!isInvalidateValue(resourcePath) && rootRegistry.resourceExists(resourcePath)) {
        resource = rootRegistry.get(resourcePath);
      } else if (type.toLowerCase().equals("collection")) {
        resource = rootRegistry.newCollection();
      } else {
        resource = rootRegistry.newResource();
      }
      simulationService.setSimulation(true);
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.put(path, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("delete")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.delete(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("importresource")) {
      String path = simulationRequest.getPath();
      String sourceURL = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        sourceURL = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(sourceURL)) {
        return;
      }
      simulationService.setSimulation(true);
      Resource resource = rootRegistry.newResource();
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.importResource(path, sourceURL, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rename")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rename(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("move")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.move(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("copy")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.copy(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removelink")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeLink(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createlink")) {
      String path = simulationRequest.getPath();
      String target = null;
      String targetSubPath = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length > 0) {
        target = params[0];
        if (params.length > 1) {
          targetSubPath = params[1];
        }
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      if (isInvalidateValue(targetSubPath)) {
        rootRegistry.createLink(path, target);
      } else {
        rootRegistry.createLink(path, target, targetSubPath);
      }
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("invokeaspect")) {
      String path = simulationRequest.getPath();
      String aspectName = null;
      String action = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        aspectName = params[0];
        action = params[1];
      }
      if (isInvalidateValue(path) || isInvalidateValue(aspectName) || isInvalidateValue(action)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.invokeAspect(path, aspectName, action);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getassociations")) {
      String path = simulationRequest.getPath();
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        associationType = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAssociations(path, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getallassociations")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAllAssociations(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.createVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("restoreversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.restoreVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getversions")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getVersions(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("applytag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.applyTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removetag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("gettags")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getTags(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getresourcepathswithtag")) {
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getResourcePathsWithTag(tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rateresource")) {
      String path = simulationRequest.getPath();
      int rating = -1;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        try {
          rating = Integer.parseInt(params[0]);
        } catch (NumberFormatException ignored) {
          return;
        }
      }
      if (isInvalidateValue(path) || rating == -1) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rateResource(path, rating);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getrating")) {
      String path = simulationRequest.getPath();
      String username = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        username = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(username)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getRating(path, username);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getaveragerating")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAverageRating(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addComment(path, new Comment(comment));
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("editcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.editComment(path, comment);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeComment")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeComment(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getcomments")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getComments(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("searchcontent")) {
      String keywords = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        keywords = params[0];
      }
      if (isInvalidateValue(keywords)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.searchContent(keywords);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("executequery")) {
      String path = simulationRequest.getPath();
      String queryParams = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        queryParams = params[0];
      }
      Map<String, String> paramMap = new LinkedHashMap<String, String>();
      if (isInvalidateValue(queryParams)) {
        return;
      }
      String[] entries = queryParams.split(",");
      if (entries != null) {
        for (String entry : entries) {
          String[] keyValPair = entry.split(":");
          if (keyValPair != null && keyValPair.length == 2) {
            paramMap.put(keyValPair[0], keyValPair[1]);
          }
        }
      }
      simulationService.setSimulation(true);
      rootRegistry.executeQuery(path, paramMap);
      simulationService.setSimulation(false);
    } else {
      throw new Exception("Unsupported Registry Operation: " + operation);
    }
  }
  /**
   * Method to obtain the resource media types.
   *
   * @param configSystemRegistry a configuration system registry instance.
   * @return a String of resource media types, in the format extension:type,extension:type,...
   * @throws RegistryException if the operation failed.
   */
  public static String getResourceMediaTypeMappings(Registry configSystemRegistry)
      throws RegistryException {

    RegistryContext registryContext = configSystemRegistry.getRegistryContext();

    if (getResourceMediaTypeMappings(registryContext) != null) {
      return getResourceMediaTypeMappings(registryContext);
    }

    Resource resource;
    String mediaTypeString = null;

    String resourcePath =
        MIME_TYPE_COLLECTION + RegistryConstants.PATH_SEPARATOR + RESOURCE_MIME_TYPE_INDEX;

    if (!configSystemRegistry.resourceExists(resourcePath)) {
      resource = configSystemRegistry.newCollection();
    } else {
      resource = configSystemRegistry.get(resourcePath);
      Properties properties = resource.getProperties();
      if (properties.size() > 0) {
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
          if (key instanceof String) {
            String ext = (String) key;
            if (RegistryUtils.isHiddenProperty(ext)) {
              continue;
            }
            String value = resource.getProperty(ext);
            String mediaTypeMapping = ext + ":" + value;
            if (mediaTypeString == null) {
              mediaTypeString = mediaTypeMapping;
            } else {
              mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
            }
          }
        }
      }
      registryContext.setResourceMediaTypes(mediaTypeString);
      return mediaTypeString;
    }

    BufferedReader reader;
    try {
      File mimeFile = getMediaTypesFile();
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(mimeFile)));
    } catch (Exception e) {
      String msg =
          "Failed to read the the media type definitions file. Only a limited "
              + "set of media type definitions will be populated. ";
      log.error(msg, e);
      mediaTypeString = "txt:text/plain,jpg:image/jpeg,gif:image/gif";
      registryContext.setResourceMediaTypes(mediaTypeString);
      return mediaTypeString;
    }

    try {
      while (reader.ready()) {
        String mediaTypeData = reader.readLine().trim();
        if (mediaTypeData.startsWith("#")) {
          // ignore the comments
          continue;
        }

        if (mediaTypeData.length() == 0) {
          // ignore the blank lines
          continue;
        }

        // mime.type file delimits media types:extensions by tabs. if there is no
        // extension associated with a media type, there are no tabs in the line. so we
        // don't need such lines.
        if (mediaTypeData.indexOf('\t') > 0) {

          String[] parts = mediaTypeData.split("\t+");
          if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {

            // there can multiple extensions associated with a single media type. in
            // that case, extensions are delimited by a space.
            String[] extensions = parts[1].trim().split(" ");
            for (String extension : extensions) {
              if (extension.length() > 0) {
                String mediaTypeMapping = extension + ":" + parts[0];
                resource.setProperty(extension, parts[0]);
                if (mediaTypeString == null) {
                  mediaTypeString = mediaTypeMapping;
                } else {
                  mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
                }
              }
            }
          }
        }
      }
      resource.setDescription(
          "This collection contains the media Types available for "
              + "resources on the Registry. Add, Edit or Delete properties to Manage Media "
              + "Types.");
      Resource collection = configSystemRegistry.newCollection();
      collection.setDescription(
          "This collection lists the media types available on the "
              + "Registry Server. Before changing an existing media type, please make sure "
              + "to alter existing resources/collections and related configuration details.");
      configSystemRegistry.put(MIME_TYPE_COLLECTION, collection);
      configSystemRegistry.put(resourcePath, resource);

    } catch (IOException e) {
      String msg = "Could not read the media type mappings file from the location: ";
      throw new RegistryException(msg, e);

    } finally {
      try {
        reader.close();
      } catch (IOException ignore) {
      }
    }
    registryContext.setResourceMediaTypes(mediaTypeString);
    return mediaTypeString;
  }
  /**
   * Saves the REST Service registry artifact created from the imported swagger definition.
   *
   * @param requestContext information about current request.
   * @param data service artifact metadata.
   * @throws RegistryException If a failure occurs when adding the api to registry.
   */
  public static String addServiceToRegistry(RequestContext requestContext, OMElement data)
      throws RegistryException {

    if (requestContext == null || data == null) {
      throw new IllegalArgumentException(
          "Some or all of the arguments may be null. Cannot add the rest service to registry. ");
    }

    Registry registry = requestContext.getRegistry();
    // Creating new resource.
    Resource serviceResource = new ResourceImpl();
    // setting API media type.
    serviceResource.setMediaType(CommonConstants.REST_SERVICE_MEDIA_TYPE);
    serviceResource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);

    OMElement overview =
        data.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, OVERVIEW));
    String serviceVersion =
        overview
            .getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, VERSION))
            .getText();
    String apiName =
        overview
            .getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, NAME))
            .getText();
    serviceVersion =
        (serviceVersion == null) ? CommonConstants.SERVICE_VERSION_DEFAULT_VALUE : serviceVersion;

    String serviceProvider = CarbonContext.getThreadLocalCarbonContext().getUsername();

    String pathExpression = getRestServicePath(requestContext, data, apiName, serviceProvider);

    // set version property.
    serviceResource.setProperty(RegistryConstants.VERSION_PARAMETER_NAME, serviceVersion);
    // copy other property
    serviceResource.setProperties(copyProperties(requestContext));
    // set content.
    serviceResource.setContent(RegistryUtils.encodeString(data.toString()));

    String resourceId = serviceResource.getUUID();
    // set resource UUID
    resourceId = (resourceId == null) ? UUID.randomUUID().toString() : resourceId;

    serviceResource.setUUID(resourceId);
    String servicePath =
        getChrootedServiceLocation(requestContext.getRegistryContext())
            + CarbonContext.getThreadLocalCarbonContext().getUsername()
            + RegistryConstants.PATH_SEPARATOR
            + apiName
            + RegistryConstants.PATH_SEPARATOR
            + serviceVersion
            + RegistryConstants.PATH_SEPARATOR
            + apiName
            + "-rest_service";
    // saving the api resource to repository.

    registry.put(pathExpression, serviceResource);

    String defaultLifeCycle = CommonUtil.getDefaultLifecycle(registry, "restservice");
    if (defaultLifeCycle != null && !defaultLifeCycle.isEmpty()) {
      registry.associateAspect(serviceResource.getId(), defaultLifeCycle);
    }

    if (log.isDebugEnabled()) {
      log.debug("REST Service created at " + pathExpression);
    }
    return pathExpression;
  }