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");
  }
 @Test(groups = {"wso2.greg"})
 public void addAssociationToResource() throws Exception {
   Resource r2 = registry.newResource();
   String path = "/testk12/testa/testbsp/test.txt";
   r2.setContent(new String("this is the content").getBytes());
   r2.setDescription("this is test desc");
   r2.setMediaType("plain/text");
   r2.setProperty("test2", "value2");
   registry.put(path, r2);
   registry.addAssociation(path, "/vtr2121/test", "testasstype1");
   registry.addAssociation(path, "/vtr2122/test", "testasstype2");
   registry.addAssociation(path, "/vtr2123/test", "testasstype3");
   assertTrue(
       associationPathExists(path, "/vtr2121/test"), "association Destination path not exist");
   assertTrue(
       associationPathExists(path, "/vtr2122/test"), "association Destination path not exist");
   assertTrue(
       associationPathExists(path, "/vtr2123/test"), "association Destination path not exist");
   assertTrue(associationTypeExists(path, "testasstype1"), "association Type not exist");
   assertTrue(associationTypeExists(path, "testasstype2"), "association Type not exist");
   assertTrue(associationTypeExists(path, "testasstype3"), "association Type not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
 }
 @Test(
     groups = {"wso2.greg"},
     dependsOnMethods = {"addAssociationToCollection"})
 public void getCollectionAssociation() throws Exception {
   Resource r2 = registry.newCollection();
   String path = "/getcol1/getcol2/getcol3";
   r2.setDescription("this is test desc");
   r2.setProperty("test2", "value2");
   registry.put(path, r2);
   registry.addAssociation(path, "/vtr2121/test", "testasstype1");
   registry.addAssociation(path, "/vtr2122/test", "testasstype2");
   registry.addAssociation(path, "/vtr2123/test", "testasstype3");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype1", "/vtr2121/test"),
       "association Destination path not exist");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype2", "/vtr2122/test"),
       "association Destination path not exist");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype3", "/vtr2123/test"),
       "association Destination path not exist");
   assertTrue(getAssocitionbyType(path, "testasstype1"), "association Type not exist");
   assertTrue(getAssocitionbyType(path, "testasstype2"), "association Type not exist");
   assertTrue(getAssocitionbyType(path, "testasstype3"), "association Type not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype1"), "association Source path not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype2"), "association Source path not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype3"), "association Source path not exist");
 }
 @Test(
     groups = {"wso2.greg"},
     dependsOnMethods = {"addAssociationToResource"})
 public void getResourceAssociation() throws Exception {
   Resource r2 = registry.newResource();
   String path = "/testk1234/testa/testbsp/test.txt";
   r2.setContent(new String("this is the content").getBytes());
   r2.setDescription("this is test desc");
   r2.setMediaType("plain/text");
   r2.setProperty("test2", "value2");
   registry.addAssociation(path, "/vtr2121/test", "testasstype1");
   registry.addAssociation(path, "/vtr2122/test", "testasstype2");
   registry.addAssociation(path, "/vtr2123/test", "testasstype3");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype1", "/vtr2121/test"),
       "association Destination path not exist");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype2", "/vtr2122/test"),
       "association Destination path not exist");
   assertTrue(
       getAssocitionbyDestinationByType(path, "testasstype3", "/vtr2123/test"),
       "association Destination path not exist");
   assertTrue(getAssocitionbyType(path, "testasstype1"), "association Type not exist");
   assertTrue(getAssocitionbyType(path, "testasstype2"), "association Type not exist");
   assertTrue(getAssocitionbyType(path, "testasstype3"), "association Type not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype1"), "association Source path not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype2"), "association Source path not exist");
   assertTrue(
       getAssocitionbySourceByType(path, "testasstype3"), "association Source path not exist");
 }
  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;
  }
  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);
  }
  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);
  }
 @Test(groups = {"wso2.greg"})
 public void addAssociationToCollection() throws Exception {
   Resource r2 = registry.newCollection();
   String path = "/assocol1/assocol2/assoclo3";
   r2.setDescription("this is test desc");
   r2.setMediaType("plain/text");
   r2.setProperty("test2", "value2");
   registry.put(path, r2);
   registry.addAssociation(path, "/vtr2121/test", "testasstype1");
   registry.addAssociation(path, "/vtr2122/test", "testasstype2");
   registry.addAssociation(path, "/vtr2123/test", "testasstype3");
   assertTrue(
       associationPathExists(path, "/vtr2121/test"), "association Destination path not exist");
   assertTrue(
       associationPathExists(path, "/vtr2122/test"), "association Destination path not exist");
   assertTrue(
       associationPathExists(path, "/vtr2123/test"), "association Destination path not exist");
   assertTrue(associationTypeExists(path, "testasstype1"), "association Type not exist");
   assertTrue(associationTypeExists(path, "testasstype2"), "association Type not exist");
   assertTrue(associationTypeExists(path, "testasstype3"), "association Type not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
   assertTrue(associationSourcepathExists(path, path), "association Source path not exist");
 }
  /**
   * 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;
  }
Beispiel #11
0
  @Test(groups = {"wso2.greg"})
  public void EditComment() throws Exception {
    Resource r1 = registry.newResource();
    byte[] r1content = "R1 content".getBytes();
    r1.setContent(r1content);
    r1.setDescription("this is a resource to edit comment");
    registry.put("/c101/c11/r1", r1);

    Comment c1 = new Comment();
    c1.setResourcePath("/c10/c11/r1");
    c1.setText("This is default comment ");
    c1.setUser("admin");

    registry.addComment("/c101/c11/r1", c1);

    Comment[] comments = registry.getComments("/c101/c11/r1");

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(c1.getText())) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        //                //System.out.println("\n");
        // break;
      }
    }

    assertTrue(
        commentFound,
        "comment:" + c1.getText() + " is not associated with the artifact /c101/c11/r1");

    try {

      Resource commentsResource = registry.get("/c101/c11/r1;comments");

      assertTrue(commentsResource instanceof Collection, "Comment resource should be a directory.");
      comments = (Comment[]) commentsResource.getContent();

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

      assertTrue(
          commentTexts.contains(c1.getText()),
          c1.getText() + " is not associated for resource /c101/c11/r1.");
      registry.editComment(comments[0].getPath(), "This is the edited comment");
      comments = registry.getComments("/c101/c11/r1");
      //            System.out.println(comments);
      Resource resource = registry.get(comments[0].getPath());
      assertEquals(new String((byte[]) resource.getContent()), "This is the edited comment");
    } catch (RegistryException e) {
      e.printStackTrace();
      fail("Failed to get comments form URL:/c101/c11/r1;comments");
    }

    /*Edit comment goes here*/

    registry.editComment("/c101/c11/r1", "This is the edited comment");
  }
Beispiel #12
0
  @Test(groups = {"wso2.greg"})
  public void AddCommentToCollection() throws Exception {
    Resource r1 = registry.newCollection();
    r1.setDescription("this is a collection to add comment");

    registry.put("/d11/d12", r1);

    String comment1 = "this is qa comment 1 for collection d12";
    String comment2 = "this is qa comment 2 for collection d12";

    Comment c1 = new Comment();
    c1.setResourcePath("/d11/d12");
    c1.setText("This is default comment for d12");
    c1.setUser("admin");

    try {
      registry.addComment("/d11/d12", c1);
      registry.addComment("/d11/d12", new Comment(comment1));
      registry.addComment("/d11/d12", new Comment(comment2));
    } catch (RegistryException e) {
      fail("Valid commenting for resources scenario failed");
    }

    Comment[] comments = null;

    try {

      comments = registry.getComments("/d11/d12");
    } catch (RegistryException e) {
      fail("Failed to get comments for the resource /d11/d12");
    }

    boolean commentFound = false;

    for (Comment comment : comments) {
      if (comment.getText().equals(comment1)) {
        commentFound = true;

        //       //System.out.println(comment.getText());
        //       //System.out.println(comment.getResourcePath());
        //       //System.out.println(comment.getUser());
        //       //System.out.println(comment.getTime());
        // break;
      }

      if (comment.getText().equals(comment2)) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        // break;
      }

      if (comment.getText().equals(c1.getText())) {
        commentFound = true;
        //                //System.out.println(comment.getText());
        //                //System.out.println(comment.getResourcePath());
        //                //System.out.println(comment.getUser());
        //                //System.out.println(comment.getTime());
        // break;
      }
    }

    assertTrue(
        commentFound, "comment '" + comment1 + " is not associated with the artifact /d11/d12");

    try {

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

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

      assertTrue(
          commentTexts.contains(comment1), comment1 + " is not associated for resource /d11/d12.");
      assertTrue(
          commentTexts.contains(comment2), comment2 + " is not associated for resource /d11/d12.");

    } catch (RegistryException e) {
      e.printStackTrace();
      fail("Failed to get comments form URL: /d11/d12;comments");
    }
  }
  /**
   * 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);
        }
      }
    }
  }
  public void put(RequestContext requestContext) throws RegistryException {
    WSDLProcessor wsdl = null;

    if (!CommonUtil.isUpdateLockAvailable()) {
      return;
    }
    CommonUtil.acquireUpdateLock();
    try {
      Registry registry = requestContext.getRegistry();
      Resource resource = requestContext.getResource();
      if (resource == null) {
        throw new RegistryException("The resource is not available.");
      }
      String originalServicePath = requestContext.getResourcePath().getPath();
      String resourceName = RegistryUtils.getResourceName(originalServicePath);

      OMElement serviceInfoElement, previousServiceInfoElement = null;
      Object resourceContent = resource.getContent();
      String serviceInfo;
      if (resourceContent instanceof String) {
        serviceInfo = (String) resourceContent;
      } else {
        serviceInfo = RegistryUtils.decodeBytes((byte[]) resourceContent);
      }
      try {
        XMLStreamReader reader =
            XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(serviceInfo));
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        serviceInfoElement = builder.getDocumentElement();
      } catch (Exception e) {
        String msg =
            "Error in parsing the service content of the service. "
                + "The requested path to store the service: "
                + originalServicePath
                + ".";
        log.error(msg);
        throw new RegistryException(msg, e);
      }
      // derive the service path that the service should be saved.
      String serviceName = CommonUtil.getServiceName(serviceInfoElement);
      String serviceNamespace = CommonUtil.getServiceNamespace(serviceInfoElement);

      String servicePath = "";
      if (serviceInfoElement.getChildrenWithLocalName("newServicePath").hasNext()) {
        Iterator OmElementIterator = serviceInfoElement.getChildrenWithLocalName("newServicePath");

        while (OmElementIterator.hasNext()) {
          OMElement next = (OMElement) OmElementIterator.next();
          servicePath = next.getText();
          break;
        }
      } else {
        if (registry.resourceExists(originalServicePath)) {
          // Fixing REGISTRY-1790. Save the Service to the given original
          // service path if there is a service already exists there
          servicePath = originalServicePath;
        } else {
          servicePath =
              RegistryUtils.getAbsolutePath(
                  registry.getRegistryContext(),
                  registry.getRegistryContext().getServicePath()
                      + (serviceNamespace == null
                          ? ""
                          : CommonUtil.derivePathFragmentFromNamespace(serviceNamespace))
                      + serviceName);
        }
      }
      String serviceVersion =
          org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion(serviceInfoElement);

      if (serviceVersion.length() == 0) {
        serviceVersion = defaultServiceVersion;
        CommonUtil.setServiceVersion(serviceInfoElement, serviceVersion);
        resource.setContent(serviceInfoElement.toString());
      }
      // saving the artifact id.
      String serviceId = resource.getUUID();
      if (serviceId == null) {
        // generate a service id
        serviceId = UUID.randomUUID().toString();
        resource.setUUID(serviceId);
      }

      if (registry.resourceExists(servicePath)) {
        Resource oldResource = registry.get(servicePath);
        String oldContent;
        Object content = oldResource.getContent();
        if (content instanceof String) {
          oldContent = (String) content;
        } else {
          oldContent = RegistryUtils.decodeBytes((byte[]) content);
        }
        OMElement oldServiceInfoElement = null;
        if (serviceInfo.equals(oldContent)) {
          // TODO: This needs a better solution. This fix was put in place to avoid
          // duplication of services under /_system/governance, when no changes were made.
          // However, the fix is not perfect and needs to be rethought. Perhaps the logic
          // below can be reshaped a bit, or may be we don't need to compare the
          // difference over here with a little fix to the Governance API end. - Janaka.

          // We have fixed this assuming that the temp path where services are stored is under
          // /_system/governance/[serviceName]
          // Hence if we are to change that location, then we need to change the following code
          // segment as well
          String tempPath =
              RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
                  + RegistryConstants.PATH_SEPARATOR
                  + resourceName;

          if (!originalServicePath.equals(tempPath)) {
            String path =
                RegistryUtils.getRelativePathToOriginal(
                    servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
            ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path);
            return;
          }
          requestContext.setProcessingComplete(true);
          return;
        }
        if ("true".equals(resource.getProperty("registry.DefinitionImport"))) {
          resource.removeProperty("registry.DefinitionImport");
          try {
            XMLStreamReader reader =
                XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(oldContent));
            StAXOMBuilder builder = new StAXOMBuilder(reader);
            oldServiceInfoElement = builder.getDocumentElement();
            CommonUtil.setServiceName(
                oldServiceInfoElement, CommonUtil.getServiceName(serviceInfoElement));
            CommonUtil.setServiceNamespace(
                oldServiceInfoElement, CommonUtil.getServiceNamespace(serviceInfoElement));
            CommonUtil.setDefinitionURL(
                oldServiceInfoElement, CommonUtil.getDefinitionURL(serviceInfoElement));
            CommonUtil.setEndpointEntries(
                oldServiceInfoElement, CommonUtil.getEndpointEntries(serviceInfoElement));
            CommonUtil.setServiceVersion(
                oldServiceInfoElement,
                org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion(
                    serviceInfoElement));
            serviceInfoElement = oldServiceInfoElement;
            resource.setContent(serviceInfoElement.toString());
            resource.setDescription(oldResource.getDescription());
          } catch (Exception e) {
            String msg =
                "Error in parsing the service content of the service. "
                    + "The requested path to store the service: "
                    + originalServicePath
                    + ".";
            log.error(msg);
            throw new RegistryException(msg, e);
          }
        }

        try {
          previousServiceInfoElement = AXIOMUtil.stringToOM(oldContent);
        } catch (XMLStreamException e) {
          String msg =
              "Error in parsing the service content of the service. "
                  + "The requested path to store the service: "
                  + originalServicePath
                  + ".";
          log.error(msg);
          throw new RegistryException(msg, e);
        }
      } else if ("true".equals(resource.getProperty("registry.DefinitionImport"))) {
        resource.removeProperty("registry.DefinitionImport");
      }
      //            CommonUtil.addGovernanceArtifactEntryWithAbsoluteValues(
      //                    CommonUtil.getUnchrootedSystemRegistry(requestContext),
      //                    serviceId, servicePath);

      String definitionURL = CommonUtil.getDefinitionURL(serviceInfoElement);
      if (previousServiceInfoElement != null) {
        String oldDefinition = CommonUtil.getDefinitionURL(previousServiceInfoElement);
        if ((!"".equals(oldDefinition) && "".equals(definitionURL))
            || (!"".endsWith(oldDefinition) && !oldDefinition.equals(definitionURL))) {
          try {
            registry.removeAssociation(servicePath, oldDefinition, CommonConstants.DEPENDS);
            registry.removeAssociation(oldDefinition, servicePath, CommonConstants.USED_BY);
            EndpointUtils.removeEndpointEntry(oldDefinition, serviceInfoElement, registry);
            resource.setContent(
                RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes()));
          } catch (RegistryException e) {
            throw new RegistryException(
                "Failed to remove endpoints from Service UI : " + serviceName, e);
          }
        }
      }

      boolean alreadyAdded = false;
      if (definitionURL != null
          && (definitionURL.startsWith("http://") || definitionURL.startsWith("https://"))) {
        String definitionPath;
        if (definitionURL.toLowerCase().endsWith("wsdl")) {
          wsdl = buildWSDLProcessor(requestContext);
          RequestContext context =
              new RequestContext(
                  registry, requestContext.getRepository(), requestContext.getVersionRepository());
          context.setResourcePath(
              new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wsdl"));
          context.setSourceURL(definitionURL);
          context.setResource(new ResourceImpl());
          definitionPath =
              wsdl.addWSDLToRegistry(
                  context,
                  definitionURL,
                  null,
                  false,
                  false,
                  disableWSDLValidation,
                  disableSymlinkCreation);

        } else if (definitionURL.toLowerCase().endsWith("wadl")) {
          WADLProcessor wadlProcessor = buildWADLProcessor(requestContext);
          wadlProcessor.setCreateService(false);
          RequestContext context =
              new RequestContext(
                  registry, requestContext.getRepository(), requestContext.getVersionRepository());
          context.setResourcePath(
              new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wadl"));
          context.setSourceURL(definitionURL);
          context.setResource(new ResourceImpl());
          definitionPath = wadlProcessor.importWADLToRegistry(context, null, disableWADLValidation);
        } else {
          throw new RegistryException(
              "Invalid service definition found. " + "Please enter a valid WSDL/WADL URL");
        }

        if (definitionPath == null) {
          return;
        }
        definitionURL =
            RegistryUtils.getRelativePath(requestContext.getRegistryContext(), definitionPath);
        CommonUtil.setDefinitionURL(serviceInfoElement, definitionURL);
        resource.setContent(RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes()));
        // updating the wsdl/wadl url
        ((ResourceImpl) resource).prepareContentForPut();
        persistServiceResource(registry, resource, servicePath);
        alreadyAdded = true;
        // and make the associations
        registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS);
        registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY);

      } else if (definitionURL != null && definitionURL.startsWith(RegistryConstants.ROOT_PATH)) {
        // it seems definitionUrl is a registry path..
        String definitionPath =
            RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(), definitionURL);
        if (!definitionPath.startsWith(
            RegistryUtils.getAbsolutePath(
                requestContext.getRegistryContext(),
                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH))) {

          definitionPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + definitionPath;
        }
        boolean addItHere = false;
        if (!registry.resourceExists(definitionPath)) {
          String msg =
              "Associating service to a non-existing WSDL. wsdl url: "
                  + definitionPath
                  + ", "
                  + "service path: "
                  + servicePath
                  + ".";
          log.error(msg);
          throw new RegistryException(msg);
        }
        if (!registry.resourceExists(servicePath)) {
          addItHere = true;
        } else {
          Association[] dependencies =
              registry.getAssociations(servicePath, CommonConstants.DEPENDS);
          boolean dependencyFound = false;
          if (dependencies != null) {
            for (Association dependency : dependencies) {
              if (definitionPath.equals(dependency.getDestinationPath())) {
                dependencyFound = true;
              }
            }
          }
          if (!dependencyFound) {
            addItHere = true;
          }
        }
        if (addItHere) { // add the service right here..
          ((ResourceImpl) resource).prepareContentForPut();
          persistServiceResource(registry, resource, servicePath);
          alreadyAdded = true;
          // and make the associations

          registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS);
          registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY);
        }
      }

      if (!alreadyAdded) {
        // we are adding the resource anyway.
        ((ResourceImpl) resource).prepareContentForPut();
        persistServiceResource(registry, resource, servicePath);
      }

      /*
                  if (!servicePath.contains(registry.getRegistryContext().getServicePath())) {
                      if (defaultEnvironment == null) {
                          String serviceDefaultEnvironment = registry.getRegistryContext().getServicePath();
                          String relativePath = serviceDefaultEnvironment.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH, "");
                          relativePath = relativePath.replace(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace),"");
                          defaultEnvironment = relativePath;
                      }

                      String currentRelativePath = servicePath.substring(0, servicePath.indexOf(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace)));
                      currentRelativePath = currentRelativePath.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH,"");

                      String endpointEnv = EndpointUtils.getEndpointLocation();

                      String[] pathSegments = defaultEnvironment.split(RegistryConstants.PATH_SEPARATOR);

                      for (String pathSegment : pathSegments) {
                          endpointEnv = endpointEnv.replace(pathSegment,"");
                          currentRelativePath = currentRelativePath.replace(pathSegment,"");
                      }

                      while(endpointEnv.startsWith(RegistryConstants.PATH_SEPARATOR)){
                          endpointEnv = endpointEnv.replaceFirst(RegistryConstants.PATH_SEPARATOR,"");
                      }

                      environment = currentRelativePath + endpointEnv;
                  }
      */

      EndpointUtils.saveEndpointsFromServices(
          servicePath,
          serviceInfoElement,
          registry,
          CommonUtil.getUnchrootedSystemRegistry(requestContext));

      String symlinkLocation =
          RegistryUtils.getAbsolutePath(
              requestContext.getRegistryContext(),
              requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME));
      if (!servicePath.equals(originalServicePath)) {
        // we are creating a sym link from service path to original service path.
        Resource serviceResource =
            requestContext.getRegistry().get(RegistryUtils.getParentPath(originalServicePath));
        String isLink = serviceResource.getProperty("registry.link");
        String mountPoint = serviceResource.getProperty("registry.mountpoint");
        String targetPoint = serviceResource.getProperty("registry.targetpoint");
        String actualPath = serviceResource.getProperty("registry.actualpath");
        if (isLink != null && mountPoint != null && targetPoint != null) {
          symlinkLocation = actualPath + RegistryConstants.PATH_SEPARATOR;
        }
        if (symlinkLocation != null) {
          requestContext
              .getSystemRegistry()
              .createLink(symlinkLocation + resourceName, servicePath);
        }
      }
      // in this flow the resource is already added. marking the process completed..
      requestContext.setProcessingComplete(true);

      if (wsdl != null
          && CommonConstants.ENABLE.equals(
              System.getProperty(CommonConstants.UDDI_SYSTEM_PROPERTY))) {
        AuthToken authToken = UDDIUtil.getPublisherAuthToken();
        if (authToken == null) {
          return;
        }

        // creating the business service info bean
        BusinessServiceInfo businessServiceInfo = new BusinessServiceInfo();
        // Following lines removed  for fixing REGISTRY-1898.
        //              businessServiceInfo.setServiceName(serviceName.trim());
        //              businessServiceInfo.setServiceNamespace(serviceNamespace.trim());
        //
        // businessServiceInfo.setServiceEndpoints(CommonUtil.getEndpointEntries(serviceInfoElement));
        //
        // businessServiceInfo.setDocuments(CommonUtil.getDocLinks(serviceInfoElement));

        businessServiceInfo.setServiceDescription(
            CommonUtil.getServiceDescription(serviceInfoElement));
        WSDLInfo wsdlInfo = wsdl.getMasterWSDLInfo();
        businessServiceInfo.setServiceWSDLInfo(wsdlInfo);
        UDDIPublisher publisher = new UDDIPublisher();
        publisher.publishBusinessService(authToken, businessServiceInfo);
      }

      String path =
          RegistryUtils.getRelativePathToOriginal(
              servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
      ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path);
    } finally {
      CommonUtil.releaseUpdateLock();
    }
  }