Example #1
0
  private void multiValuedProperties() {
    String path = "/propTest/r1";
    Resource r1 = registry.newResource();

    try {
      r1.setContent("Some content for r1");

      r1.addProperty("p1", "p1v1");
      r1.addProperty("p1", "p1v2");
      registry.put(path, r1);

      Resource r1b = registry.get(path);
      List propValues = r1b.getPropertyValues("p1");

      assertTrue(
          "Property p1 of /propTest/r1 should contain the value p1v1", propValues.contains("p1v1"));

      assertTrue(
          "Property p1 of /propTest/r1 should contain the value p1v2", propValues.contains("p1v2"));

      deleteResources("/propTest");
      log.info("multiValuedProperties - Passed");
    } catch (RegistryException e) {

      log.error("multiValuedProperties RegistryException thrown :" + e.getMessage());
      Assert.fail("multiValuedProperties RegistryException thrown :" + e.getMessage());
    }
  }
Example #2
0
  private void editingMultivaluedProperties() {
    String path = "/props/t3/r1";
    Resource r1 = registry.newResource();
    try {
      r1.setContent("r1 content");

      r1.addProperty("p1", "v1");
      r1.addProperty("p1", "v2");
      r1.setProperty("test", "value2");
      r1.setProperty("test2", "value2");
      registry.put(path, r1);

      Resource r1e1 = registry.get(path);
      r1e1.setContent("r1 content");
      r1e1.editPropertyValue("p1", "v1", "v3");

      registry.put(path, r1e1);

      Resource r1e2 = registry.get(path);
      assertFalse("Property is not edited.", r1e2.getPropertyValues("p1").contains("v1"));
      assertTrue("Property is not edited.", r1e2.getPropertyValues("p1").contains("v3"));
      assertTrue("Wrong property is removed.", r1e2.getPropertyValues("p1").contains("v2"));

      deleteResources("/props");
      log.info("editingMultivaluedProperties- Passed");
    } catch (RegistryException e) {

      log.error("editingMultivaluedProperties RegistryException thrown :" + e.getMessage());
      Assert.fail("editingMultivaluedProperties RegistryException thrown :" + e.getMessage());
    }
  }
Example #3
0
  private void removingProperties() {
    String path = "/props/t1/r1";
    Resource r1 = registry.newResource();
    try {
      r1.setContent("r1 content");

      r1.setProperty("p1", "v1");
      r1.setProperty("p2", "v2");
      registry.put(path, r1);

      Resource r1e1 = registry.get(path);
      r1e1.setContent("r1 content");
      r1e1.removeProperty("p1");
      registry.put(path, r1e1);

      Resource r1e2 = registry.get(path);

      assertEquals("Property is not removed.", r1e2.getProperty("p1"), null);
      assertNotNull("Wrong property is removed.", r1e2.getProperty("p2"));

      deleteResources("/props");
      log.info("removingProperties - Passed");
    } catch (RegistryException e) {

      log.error("removingProperties RegistryException thrown :" + e.getMessage());
      Assert.fail("removingProperties RegistryException thrown :" + e.getMessage());
    }
  }
Example #4
0
 public void deleteResources(String resourceName) {
   try {
     if (registry.resourceExists(resourceName)) {
       registry.delete(resourceName);
     }
   } catch (RegistryException e) {
     log.error("deleteResources RegistryException thrown:" + e.getMessage());
     Assert.fail("deleteResources RegistryException thrown:" + e.getMessage());
   }
 }
  /**
   * Artifact is either retrieved or prepared for later addition to registry
   *
   * @param ga
   * @return
   */
  private GovernanceArtifact addArtifact(RBGGovernanceArtifact ga) {
    boolean checkChanged = false;
    boolean isNewer = false;
    GenericArtifactManager gam = registryFactory.getManagerForArtifactType(ga.getRegistryType());
    GenericArtifact fa = (GenericArtifact) findMatchingArtifact(ga);
    log.info("working on: " + ga.getName());
    try {
      if (fa != null) {
        isNewer = isVersionNewer(ga.getVersion(), fa.getAttribute("details_version"));
        checkChanged = updateAttributes(ga, fa);
      } else {
        fa = gam.newGovernanceArtifact(new QName(ga.getName())); // artifactname
        fa.setAttribute("details_version", ga.getVersion());
        updateAttributes(ga, fa);
        gam.addGenericArtifact(fa);
        handleLifeCycle(ga, fa);
      }
      if (isNewer) {
        if (checkChanged) {
          gam.updateGenericArtifact(fa);
          log.info("updated: " + ga.getName());
        }
        handleLifeCycle(ga, fa);
      }
    } catch (GovernanceException e) {
      log.error(e.getMessage());
    } catch (RegistryException e) {
      log.error(e.getMessage());
    }

    return fa;
  }
Example #6
0
  /**
   * This method add array of tags to the specified resource
   *
   * @param resourcePath - Resource path
   * @return HTTP 204 No Content if success
   */
  @POST
  @Consumes("application/json")
  @Produces("application/json")
  public Response addTag(
      @QueryParam("path") String resourcePath,
      @QueryParam("name") String tagText,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {

    RestAPIAuthContext authContext =
        RestAPISecurityUtils.getAuthContext(
            PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    try {
      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      if (!registry.resourceExists(resourcePath)) {
        return Response.status(Response.Status.NOT_FOUND)
            .entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath)
            .build();
      }
      registry.applyTag(resourcePath, tagText);
      return Response.status(Response.Status.NO_CONTENT).build();

    } catch (RegistryException e) {
      log.error("user doesn't have permission to put the tags for the given resource", e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
Example #7
0
  /**
   * This method retrieves the resource paths for a given tag name
   *
   * @param tagName - Name of the tag
   * @param start - Page start number
   * @param size - Number of records to be fetched
   * @return JSON object eg: {"path":[<array of resource paths tagged by the tagname>]}protected
   *     HTTP 200 OK.
   */
  @GET
  @Produces("application/json")
  public Response getTaggedResources(
      @QueryParam("name") String tagName,
      @QueryParam("start") int start,
      @QueryParam("size") int size,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {
    RestAPIAuthContext authContext =
        RestAPISecurityUtils.getAuthContext(
            PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    try {

      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      TaggedResourcePath[] resourcePaths = registry.getResourcePathsWithTag(tagName);
      return getPaginatedResults(resourcePaths, start, size, "", "");

    } catch (RegistryException e) {
      log.error("Failed to get resource path having tag : " + tagName, e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
 /**
  * Building the topic tree
  *
  * @param topicNode node of the topic
  * @param resource the resource that holds child topics
  * @param userRegistry user registry
  * @throws EventBrokerException
  */
 private void buildTopicTree(TopicNode topicNode, Collection resource, UserRegistry userRegistry)
     throws EventBrokerException {
   try {
     String[] children = resource.getChildren();
     if (children != null) {
       List<TopicNode> nodes = new ArrayList<TopicNode>();
       for (String childTopic : children) {
         Resource childResource = userRegistry.get(childTopic);
         if (childResource instanceof Collection) {
           if (childTopic.endsWith("/")) {
             childTopic = childTopic.substring(0, childTopic.length() - 2);
           }
           String nodeName = childTopic.substring(childTopic.lastIndexOf("/") + 1);
           if (!nodeName.equals(EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME)
               && !nodeName.equals(
                   EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME)) {
             childTopic =
                 childTopic.substring(
                     childTopic.indexOf(this.topicStoragePath)
                         + this.topicStoragePath.length()
                         + 1);
             TopicNode childNode = new TopicNode(nodeName, childTopic);
             nodes.add(childNode);
             buildTopicTree(childNode, (Collection) childResource, userRegistry);
           }
         }
       }
       topicNode.setChildren(nodes.toArray(new TopicNode[nodes.size()]));
     }
   } catch (RegistryException e) {
     throw new EventBrokerException(e.getMessage(), e);
   }
 }
Example #9
0
  private void rootLevelProperties() {
    Resource root;
    try {
      root = registry.get("/");
      root.addProperty("p1", "v1");
      registry.put("/", root);

      Resource rootb = registry.get("/");
      assertEquals(
          "Root should have a property named p1 with value v1", rootb.getProperty("p1"), "v1");
      log.info("rootLevelProperties() -Passed");

    } catch (RegistryException e) {
      log.error("rootLevelProperties RegistryException thrown :" + e.getMessage());
      Assert.fail("rootLevelProperties RegistryException thrown :" + e.getMessage());
    }
  }
Example #10
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());
   }
 }
 /**
  * Return a embedded registry service. If there is no registry service existing, this will create
  * a registry service an return
  *
  * @return the newly create registry service.
  * @throws RegistryException throws if the retrieval of the embedded registry service is failed.
  */
 public EmbeddedRegistryService getEmbeddedRegistryService() throws RegistryException {
   if (embeddedRegistryService == null) {
     try {
       embeddedRegistryService = new EmbeddedRegistryService(this);
     } catch (RegistryException e) {
       String msg = "Couldn't initialize EmbeddedRegistryService. " + e.getMessage();
       log.error(msg, e);
       throw new RegistryException(msg, e);
     }
   }
   return embeddedRegistryService;
 }
 /**
  * This method checks the existance of a keystore
  *
  * @param tenantId
  * @return
  * @throws KeyStoreMgtException
  */
 public boolean isKeyStoreExists(int tenantId) throws KeyStoreMgtException {
   String keyStoreName = generateKSNameFromDomainName();
   boolean isKeyStoreExists = false;
   try {
     isKeyStoreExists =
         govRegistry.resourceExists(
             RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName);
   } catch (RegistryException e) {
     String msg = "Error while checking the existance of keystore.  ";
     log.error(msg + e.getMessage());
   }
   return isKeyStoreExists;
 }
Example #13
0
  private void singleValuedProperties() {
    String path = "/propTest/r2";
    Resource r2 = registry.newResource();
    try {
      r2.setContent("Some content for r2");

      r2.addProperty("p1", "p1v1");
      registry.put(path, r2);

      Resource r2b = registry.get(path);
      String p1Value = r2b.getProperty("p1");

      assertEquals("Property p1 of /propTest/r2 should contain the value p1v1", p1Value, "p1v1");

      deleteResources("/propTest");
      log.info("singleValuedProperties - Passed");
    } catch (RegistryException e) {

      log.error("singleValuedProperties RegistryException thrown :" + e.getMessage());
      Assert.fail("singleValuedProperties RegistryException thrown :" + e.getMessage());
    }
  }
 private GovernanceArtifact findMatchingArtifact(RBGGovernanceArtifact ga) {
   GovernanceArtifact ret = null;
   String matcher = getArtifactPath(ga);
   try {
     if (registryFactory.getRemoteRegistryInstance().resourceExists(matcher)) {
       ret =
           GovernanceUtils.retrieveGovernanceArtifactByPath(
               registryFactory.getRemoteRegistryInstance(), matcher);
     }
   } catch (RegistryException e) {
     log.error(e.getMessage());
   }
   return ret;
 }
Example #15
0
  /**
   * This method tags associated with the given resource
   *
   * @param resourcePath resource path
   * @param start starting page number
   * @param size number of tags to be fetched
   * @return JSON tag model eg: {"tags":[<array of tag names]}
   */
  @GET
  @Produces("application/json")
  @ApiOperation(
      value = "Get all tags on a resource",
      httpMethod = "GET",
      notes = "Fetch all tags on a resource",
      response = TagModel.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Found the tags and returned in body"),
        @ApiResponse(code = 401, message = "Invalid credentials provided"),
        @ApiResponse(code = 404, message = "Given specific resource not found"),
        @ApiResponse(code = 500, message = "Internal server error occurred")
      })
  public Response getTags(
      @QueryParam("path") String resourcePath,
      @QueryParam("start") int start,
      @QueryParam("size") int size,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {

    RestAPIAuthContext authContext =
        RestAPISecurityUtils.getAuthContext(
            PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    if (resourcePath == null || "".equals(resourcePath)) {
      // Return tagsCloud, therefore no need pagination.
      return getAllTags();
    }
    org.wso2.carbon.registry.core.Tag[] tags = new org.wso2.carbon.registry.core.Tag[0];
    try {
      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      if (!registry.resourceExists(resourcePath)) {
        return Response.status(Response.Status.NOT_FOUND)
            .entity(RestAPIConstants.RESOURCE_NOT_FOUND)
            .build();
      }

      tags = registry.getTags(resourcePath);

    } catch (RegistryException e) {
      log.error("Failed to get tags on resource " + resourcePath, e);
      Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    // Need paginate, because it return tags of a resource
    return getPaginatedResults(tags, start, size, "", "");
  }
 /** {@inheritDoc} */
 @Override
 public TopicNode getTopicTree() throws EventBrokerException {
   try {
     UserRegistry userRegistry =
         this.registryService.getGovernanceSystemRegistry(
             EventBrokerHolder.getInstance().getTenantId());
     if (!userRegistry.resourceExists(topicStoragePath)) {
       userRegistry.put(topicStoragePath, userRegistry.newCollection());
     }
     Resource root = userRegistry.get(this.topicStoragePath);
     TopicNode rootTopic = new TopicNode("/", "/");
     buildTopicTree(rootTopic, (Collection) root, userRegistry);
     return rootTopic;
   } catch (RegistryException e) {
     throw new EventBrokerException(e.getMessage(), e);
   }
 }
Example #17
0
  /**
   * This method deletes the specified tag on the given resource
   *
   * @param resourcePath - Path of the resource.
   * @param tagName - Name of the tag
   * @return HTTP 204 No Content response, if success.
   */
  @DELETE
  @Produces("application/json")
  public Response deleteTag(
      @QueryParam("path") String resourcePath,
      @QueryParam("name") String tagName,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {

    RestAPIAuthContext authContext =
        RestAPISecurityUtils.getAuthContext(
            PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    try {

      boolean tagFound = false;
      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      if (!registry.resourceExists(resourcePath)) {
        return Response.status(Response.Status.NOT_FOUND)
            .entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath)
            .build();
      }
      org.wso2.carbon.registry.core.Tag[] tags = registry.getTags(resourcePath);
      for (org.wso2.carbon.registry.core.Tag tag1 : tags) {
        // if tag has been found remove the tag,set the tag found
        // variable to true
        if (tagName.equals(tag1.getTagName())) {
          registry.removeTag(resourcePath, tagName);
          tagFound = true;
        }
      }
      if (tagFound) {
        // if tag deleted
        return Response.status(Response.Status.NO_CONTENT).build();
      } else {
        log.debug("tag not found");
        // if the specified tag is not found,returns http 404
        return Response.status(Response.Status.NOT_FOUND).build();
      }

    } catch (RegistryException e) {
      log.error("Failed to  delete a tag " + tagName + " " + "on resource " + resourcePath, e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
Example #18
0
  /**
   * This method add array of tags to the specified resource
   *
   * @param resourcePath - Resource path
   * @param tags - eg:{"tags":[<array of tag names>]}
   * @return HTTP 204 No Content ,if success.
   */
  @POST
  @Consumes("application/json")
  @Produces("application/json")
  @ApiOperation(
      value = "Add an array of tags to a resource",
      httpMethod = "POST",
      notes = "Add an array of tags to a resource")
  @ApiResponses(
      value = {
        @ApiResponse(code = 204, message = "Resource tagged successfully"),
        @ApiResponse(code = 401, message = "Invalid credentials provided"),
        @ApiResponse(code = 404, message = "Specified resource not found"),
        @ApiResponse(code = 500, message = "Internal server error occurred")
      })
  public Response addTags(
      @QueryParam("path") String resourcePath,
      TagModel tags,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {

    RestAPIAuthContext authContext =
        RestAPISecurityUtils.getAuthContext(
            PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    try {
      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      if (!registry.resourceExists(resourcePath)) {
        return Response.status(Response.Status.NOT_FOUND)
            .entity(RestAPIConstants.RESOURCE_NOT_FOUND)
            .build();
      }

      String[] tagsOnResource = tags.getTags();
      for (String aTagsOnResource : tagsOnResource) {
        registry.applyTag(resourcePath, aTagsOnResource);
      }
      return Response.status(Response.Status.NO_CONTENT).build();

    } catch (RegistryException e) {
      log.error("user doesn't have permission to put the tags for the given resource", e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
 private void removePersistedDataSource(String dsName) throws DataSourceException {
   try {
     this.getRegistry().beginTransaction();
     String path = DataSourceConstants.DATASOURCES_REPOSITORY_BASE_PATH + "/" + dsName;
     if (this.getRegistry().resourceExists(path)) {
       this.getRegistry().delete(path);
     }
     this.getRegistry().commitTransaction();
   } catch (Exception e) {
     try {
       this.getRegistry().rollbackTransaction();
     } catch (RegistryException e1) {
       log.error("Error in rollback transaction in removing data source:" + e1.getMessage(), e1);
     }
     throw new DataSourceException(
         "Error in removing data source: " + dsName + " - " + e.getMessage(), e);
   }
 }
  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 void setUp() {
   super.setUp();
   if (embeddedRegistryService != null) {
     return;
   }
   try {
     embeddedRegistryService = ctx.getEmbeddedRegistryService();
     RealmUnawareRegistryCoreServiceComponent comp =
         new RealmUnawareRegistryCoreServiceComponent();
     comp.setRealmService(ctx.getRealmService());
     comp.registerBuiltInHandlers(embeddedRegistryService);
     // get the realm config to retrieve admin username, password
     RealmConfiguration realmConfig = ctx.getRealmService().getBootstrapRealmConfiguration();
     registry =
         embeddedRegistryService.getConfigUserRegistry(
             realmConfig.getAdminUserName(), realmConfig.getAdminPassword());
     systemRegistry = embeddedRegistryService.getConfigSystemRegistry();
   } catch (RegistryException e) {
     fail("Failed to initialize the registry. Caused by: " + e.getMessage());
   }
 }
Example #22
0
  /**
   * This method to move the registry resource.
   *
   * @param resourcePath - Source path of the resource.
   * @param destinationPath - Destination path of the resource.
   * @param JWTToken - Access token.
   * @return - HTTP 204 No Content
   */
  @POST
  @ApiOperation(
      value = "Move source resource to target path",
      httpMethod = "POST",
      notes = "Move source resource to target path")
  @ApiResponses(
      value = {
        @ApiResponse(code = 204, message = "Resource moved successfully"),
        @ApiResponse(code = 401, message = "Invalid credentials provided"),
        @ApiResponse(code = 404, message = "Specified resource not found"),
        @ApiResponse(code = 500, message = "Internal server error occurred")
      })
  public Response moveResource(
      @QueryParam("path") String resourcePath,
      @QueryParam("destination") String destinationPath,
      @HeaderParam("X-JWT-Assertion") String JWTToken) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext(carbonContext, JWTToken);

    if (!authContext.isAuthorized()) {
      return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    try {

      Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
      if (!registry.resourceExists(resourcePath)) {
        return Response.status(Response.Status.NOT_FOUND)
            .entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath)
            .build();
      }
      registry.move(resourcePath, destinationPath);
      return Response.status(Response.Status.NO_CONTENT).build();

    } catch (RegistryException e) {
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
  /**
   * Adds the given artifact to the registry. Please do not use this method to update an existing
   * artifact use the update method instead. If this method is used to update an existing artifact,
   * all existing properties (such as lifecycle details) will be removed from the existing artifact.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void addGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    // adding the attributes for name, namespace + artifact
    if (artifact.getQName() == null || artifact.getQName().getLocalPart() == null) {
      String msg = "A valid qualified name was not set for this artifact";
      log.error(msg);
      throw new GovernanceException(msg);
    }
    validateArtifact(artifact);
    String artifactName = artifact.getQName().getLocalPart();
    artifact.setAttributes(artifactNameAttribute, new String[] {artifactName});
    // namespace can be null
    String namespace = artifact.getQName().getNamespaceURI();
    if (artifactNamespaceAttribute != null) {
      artifact.setAttributes(artifactNamespaceAttribute, new String[] {namespace});
    }

    ((GovernanceArtifactImpl) artifact).associateRegistry(registry);
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      Resource resource = registry.newResource();

      resource.setMediaType(mediaType);
      setContent(artifact, resource);
      // the artifact will not actually stored in the tmp path.
      String path = GovernanceUtils.getPathFromPathExpression(pathExpression, artifact);

      if (registry.resourceExists(path)) {
        throw new GovernanceException(
            "Governance artifact " + artifactName + " already exists at " + path);
      }

      String artifactId = artifact.getId();
      resource.setUUID(artifactId);
      registry.put(path, resource);

      if (lifecycle != null) {
        registry.associateAspect(path, lifecycle);
      }

      ((GovernanceArtifactImpl) artifact).updatePath();
      //            artifact.setId(resource.getUUID()); //This is done to get the UUID of a existing
      // resource.
      addRelationships(path, artifact);

      succeeded = true;
    } catch (RegistryException e) {
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Failed to add artifact: artifact id: "
                + artifact.getId()
                + ", path: "
                + artifact.getPath()
                + ". "
                + e.getMessage();
      } else {
        msg = "Failed to add artifact: artifact id: " + artifact.getId() + ". " + e.getMessage();
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg;
          if (artifact.getPath() != null) {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ", path: "
                    + artifact.getPath()
                    + ".";
          } else {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ".";
          }
          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Failed to add artifact: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
  private TenantRegistrationConfig getTenantSignUpConfig(int tenantId) throws IdentityException {
    TenantRegistrationConfig config;
    NodeList nodes;
    try {
      // start tenant flow to load tenant registry
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
      PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
      Registry registry =
          (Registry)
              PrivilegedCarbonContext.getThreadLocalCarbonContext()
                  .getRegistry(RegistryType.SYSTEM_GOVERNANCE);
      if (registry.resourceExists(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH)) {
        Resource resource = registry.get(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH);
        // build config from tenant registry resource
        DocumentBuilder builder = getSecuredDocumentBuilder();
        String configXml = new String((byte[]) resource.getContent());
        InputSource configInputSource = new InputSource();
        configInputSource.setCharacterStream(new StringReader(configXml.trim()));
        Document doc = builder.parse(configInputSource);
        nodes = doc.getElementsByTagName(SelfRegistrationConstants.SELF_SIGN_UP_ELEMENT);
        if (nodes.getLength() > 0) {
          config = new TenantRegistrationConfig();
          config.setSignUpDomain(
              ((Element) nodes.item(0))
                  .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_DOMAIN_ELEMENT)
                  .item(0)
                  .getTextContent());
          // there can be more than one <SignUpRole> elements, iterate through all elements
          NodeList rolesEl =
              ((Element) nodes.item(0))
                  .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_ROLE_ELEMENT);
          for (int i = 0; i < rolesEl.getLength(); i++) {
            Element tmpEl = (Element) rolesEl.item(i);
            String tmpRole =
                tmpEl
                    .getElementsByTagName(SelfRegistrationConstants.ROLE_NAME_ELEMENT)
                    .item(0)
                    .getTextContent();
            boolean tmpIsExternal =
                Boolean.parseBoolean(
                    tmpEl
                        .getElementsByTagName(SelfRegistrationConstants.IS_EXTERNAL_ELEMENT)
                        .item(0)
                        .getTextContent());
            config.getRoles().put(tmpRole, tmpIsExternal);
          }
          return config;
        } else {
          return null;
        }
      }
    } catch (RegistryException e) {
      throw new IdentityException(
          "Error retrieving sign up config from registry " + e.getMessage(), e);
    } catch (ParserConfigurationException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (SAXException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (IOException e) {
      throw new IdentityException(
          "Error parsing tenant sign up configuration " + e.getMessage(), e);
    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }

    return null;
  }
  /**
   * Updates the given artifact on the registry.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void updateGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      validateArtifact(artifact);
      GovernanceArtifact oldArtifact = getGovernanceArtifact(artifact.getId());
      // first check for the old artifact and remove it.
      String oldPath = null;
      if (oldArtifact != null) {
        QName oldName = oldArtifact.getQName();
        if (!oldName.equals(artifact.getQName())) {
          String temp = oldArtifact.getPath();
          // then it is analogue to moving the resource for the new location
          // so just delete the old path
          registry.delete(temp);

          String artifactName = artifact.getQName().getLocalPart();
          artifact.setAttributes(artifactNameAttribute, new String[] {artifactName});
          String namespace = artifact.getQName().getNamespaceURI();
          if (artifactNamespaceAttribute != null) {
            artifact.setAttributes(artifactNamespaceAttribute, new String[] {namespace});
          }
        } else {
          oldPath = oldArtifact.getPath();
        }
      } else {
        throw new GovernanceException(
            "No artifact found for the artifact id :" + artifact.getId() + ".");
      }

      String artifactId = artifact.getId();
      Resource resource = registry.newResource();
      resource.setMediaType(mediaType);
      setContent(artifact, resource);
      String path = GovernanceUtils.getPathFromPathExpression(pathExpression, artifact);

      if (oldPath != null) {
        path = oldPath;
      }
      if (registry.resourceExists(path)) {
        Resource oldResource = registry.get(path);
        Properties properties = (Properties) oldResource.getProperties().clone();
        resource.setProperties(properties);

        // persisting resource description at artifact update
        String description = oldResource.getDescription();
        if (description != null) {
          resource.setDescription(description);
        }

        String oldContent;
        Object content = oldResource.getContent();
        if (content instanceof String) {
          oldContent = (String) content;
        } else {
          oldContent = new String((byte[]) content);
        }
        String newContent;
        content = resource.getContent();
        if (content instanceof String) {
          newContent = (String) content;
        } else {
          newContent = new String((byte[]) content);
        }
        if (newContent.equals(oldContent)) {
          artifact.setId(oldResource.getUUID());
          addRelationships(path, artifact);
          succeeded = true;
          return;
        }
      }
      resource.setUUID(artifactId);
      registry.put(path, resource);
      //            artifact.setId(resource.getUUID()); //This is done to get the UUID of a existing
      // resource.
      addRelationships(oldPath, artifact);
      ((GovernanceArtifactImpl) artifact).updatePath(artifactId);
      succeeded = true;
    } catch (RegistryException e) {
      if (e instanceof GovernanceException) {
        throw (GovernanceException) e;
      }
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Error in updating the artifact, artifact id: "
                + artifact.getId()
                + ", artifact path: "
                + artifact.getPath()
                + "."
                + e.getMessage()
                + ".";
      } else {
        msg =
            "Error in updating the artifact, artifact id: "
                + artifact.getId()
                + "."
                + e.getMessage()
                + ".";
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg;
          if (artifact.getPath() != null) {
            msg =
                "Error in committing transactions. Update artifact failed: artifact "
                    + "id: "
                    + artifact.getId()
                    + ", path: "
                    + artifact.getPath()
                    + ".";
          } else {
            msg =
                "Error in committing transactions. Update artifact failed: artifact "
                    + "id: "
                    + artifact.getId()
                    + ".";
          }

          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Update artifact failed: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }