Beispiel #1
0
 public static boolean generateHandler(Registry configSystemRegistry, String resourceFullPath)
     throws RegistryException, XMLStreamException {
   RegistryContext registryContext = configSystemRegistry.getRegistryContext();
   if (registryContext == null) {
     return false;
   }
   Resource resource = configSystemRegistry.get(resourceFullPath);
   if (resource != null) {
     String content = null;
     if (resource.getContent() != null) {
       content = RegistryUtils.decodeBytes((byte[]) resource.getContent());
     }
     if (content != null) {
       OMElement handler = AXIOMUtil.stringToOM(content);
       if (handler != null) {
         OMElement dummy = OMAbstractFactory.getOMFactory().createOMElement("dummy", null);
         dummy.addChild(handler);
         try {
           configSystemRegistry.beginTransaction();
           boolean status =
               RegistryConfigurationProcessor.updateHandler(
                   dummy,
                   configSystemRegistry.getRegistryContext(),
                   HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
           configSystemRegistry.commitTransaction();
           return status;
         } catch (Exception e) {
           configSystemRegistry.rollbackTransaction();
           throw new RegistryException("Unable to add handler", e);
         }
       }
     }
   }
   return false;
 }
  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");
  }
Beispiel #3
0
 public static String getHandlerConfiguration(Registry configSystemRegistry, String name)
     throws RegistryException, XMLStreamException {
   String path = getContextRoot() + name;
   Resource resource;
   if (handlerExists(configSystemRegistry, name)) {
     resource = configSystemRegistry.get(path);
     return RegistryUtils.decodeBytes((byte[]) resource.getContent());
   }
   return null;
 }
Beispiel #4
0
 private Scriptable parseJsonResource(Resource resource) throws IOException {
   JsonParser parser = new JsonParser(Context.getCurrentContext(), globalScope);
   try {
     Object result = parser.parseValue(resource.getContent());
     if (!(result instanceof Scriptable)) {
       throw new RuntimeException("Expected Object from package.json, got " + result);
     }
     return (Scriptable) result;
   } catch (JsonParser.ParseException px) {
     throw new RuntimeException(px);
   }
 }
Beispiel #5
0
 public String insertContent(Resource rsce, String contUrl) {
   String descr = "";
   for (String term : rsce.getContent()) {
     descr += "   rdf:type  \"" + term + "\" ; ";
   }
   return "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
       + "INSERT  "
       + " { <"
       + contUrl
       + "> "
       + descr
       + " }";
 }
Beispiel #6
0
  /**
   * @param rsce A resource
   * @return All content description containing rsce content description
   */
  public String listContent(Resource rsce) {
    String query =
        "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
            + "SELECT DISTINCT ?r  "
            + "WHERE { ";
    for (int i = 0; i < rsce.getContent().size(); i++) {
      query +=
          "?r rdf:type ?o"
              + i
              + " . FILTER(STR(?o"
              + i
              + ")= \""
              + rsce.getVoc().getUrl()
              + "#"
              + rsce.getContent().get(i)
              + "\") . ";
    }

    query += " }";

    return query;
  }
  @Override
  public void processExcption(BeetlException ex, Writer writer) {

    ErrorInfo error = new ErrorInfo(ex);
    int line = error.getErrorTokenLine();
    StringBuilder sb =
        new StringBuilder(">>")
            .append(error.getType())
            .append(":")
            .append(error.getErrorTokenText())
            .append(" 位于")
            .append(line)
            .append("行")
            .append(" 资源:")
            .append(getResourceName(ex.resourceId));
    ;
    println(writer, sb.toString());
    if (error.getErrorCode().equals(BeetlException.TEMPLATE_LOAD_ERROR)) {
      printCause(error, writer);
      return;
    }

    ResourceLoader resLoader = ex.gt.getResourceLoader();
    // 潜在问题,此时可能得到是一个新的模板,不过可能性很小,忽略!

    String content = null;
    ;
    try {
      Resource res = resLoader.getResource(ex.resourceId);
      // 显示前后三行的内容
      int[] range = this.getRange(line);
      content = res.getContent(range[0], range[1]);
      if (content != null) {
        String[] strs = content.split(ex.cr);
        int lineNumber = range[0];
        for (int i = 0; i < strs.length; i++) {
          print(writer, "" + lineNumber);
          print(writer, "|");
          println(writer, strs[i]);
          lineNumber++;
        }
      }
    } catch (IOException e) {

      // ingore

    }

    printCause(error, writer);
  }
  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"));
  }
  /**
   * Main method of the example class.
   *
   * @param args (ignored) command-line arguments
   * @throws Exception exception
   */
  public static void main(final String[] args) throws Exception {

    System.out.println("=== XMLDBQuery ===\n");

    System.out.println("* Run query via XML:DB:");

    // Collection instance
    Collection coll = null;

    try {
      // Register the database
      Class<?> c = Class.forName(DRIVER);
      Database db = (Database) c.newInstance();
      DatabaseManager.registerDatabase(db);

      // Receive the database
      coll = DatabaseManager.getCollection(DBNAME);

      // Receive the XPath query service
      XPathQueryService service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

      // Execute the query and receives all results
      ResourceSet set = service.query(QUERY);

      // Create a result iterator
      ResourceIterator iter = set.getIterator();

      // Loop through all result items
      while (iter.hasMoreResources()) {
        // Receive the next results
        Resource res = iter.nextResource();

        // Write the result to the console
        System.out.println(res.getContent());
      }
    } catch (final XMLDBException ex) {
      // Handle exceptions
      System.err.println("XML:DB Exception occured " + ex.errorCode);
    } finally {
      // Close the collection
      if (coll != null) coll.close();
    }
  }
Beispiel #10
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);
  }
  /**
   * This method performs an XPath query to the database and returns the results as a Vector of
   * Strings.
   *
   * @param collection The name of the collection to look for the document.
   * @param query A string containing an XPath expression which shall act as a query against the
   *     database.
   * @param username The identifier of the user calling the method used for authentication.
   * @param password The password of the user calling the method used for authentication.
   * @return A Vector containing the answers to the query as Strings.
   */
  public Vector query(String collection, String query, String username, String password) {
    Vector response = new Vector();
    try {
      Class cl = Class.forName(_driver);
      Database database = (Database) cl.newInstance();
      DatabaseManager.registerDatabase(database);

      Collection col = DatabaseManager.getCollection(_URI + collection, username, password);
      XPathQueryService service = (XPathQueryService) col.getService("XPathQueryService", "1.0");
      service.setProperty("indent", "yes");

      ResourceSet result = service.query(query);
      ResourceIterator i = result.getIterator();
      while (i.hasMoreResources()) {
        Resource r = i.nextResource();
        response.add((String) r.getContent());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return response;
  }
Beispiel #12
0
 public String insert(Resource rsce) {
   String descr = "";
   for (String term : rsce.getContent()) {
     descr += "  ;  res:content  \"" + term + "\"  ";
   }
   return "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
       + "PREFIX res:<"
       + this.getRes()
       + "s#>"
       + "INSERT  "
       + " { <"
       + rsce.getUrl()
       + "> res:submitter  \""
       + rsce.getSubmitter().getLogin()
       + "\" ; "
       + "                       res:state  \""
       + rsce.getState()
       + "\" ; "
       + "                       res:vocname  \""
       + rsce.getVoc().getName()
       + "\" ; "
       + "                       res:type  \""
       + rsce.getType()
       + "\" ; "
       + "                       res:language  \""
       + rsce.getLanguage()
       + "\" ; "
       + "                       res:format  \""
       + rsce.getFormat()
       + "\" ; "
       + "                       res:author  \""
       + rsce.getAuthor()
       + "\"  "
       + descr
       + "               }";
 }
  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));
  }
  public String addWadlToRegistry(
      RequestContext requestContext, Resource resource, String resourcePath, boolean skipValidation)
      throws RegistryException {
    String wadlName = RegistryUtils.getResourceName(resourcePath);
    String version =
        requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME);

    if (version == null) {
      version = CommonConstants.WADL_VERSION_DEFAULT_VALUE;
      requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version);
    }

    OMElement wadlElement;
    String wadlContent;
    Object resourceContent = resource.getContent();
    if (resourceContent instanceof String) {
      wadlContent = (String) resourceContent;
    } else {
      wadlContent = new String((byte[]) resourceContent);
    }

    try {
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(wadlContent));
      StAXOMBuilder builder = new StAXOMBuilder(reader);
      wadlElement = builder.getDocumentElement();
    } catch (XMLStreamException e) {
      // This exception is unexpected because the WADL already validated
      String msg = "Unexpected error occured " + "while reading the WADL at " + resourcePath + ".";
      log.error(msg);
      throw new RegistryException(msg, e);
    }

    String wadlNamespace = wadlElement.getNamespace().getNamespaceURI();
    String namespaceSegment =
        CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/");
    String actualPath =
        getChrootedWadlLocation(requestContext.getRegistryContext())
            + namespaceSegment
            + version
            + "/"
            + wadlName;

    OMElement grammarsElement =
        wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars"));

    if (StringUtils.isNotBlank(requestContext.getSourceURL())) {
      String uri = requestContext.getSourceURL();
      if (!skipValidation) {
        validateWADL(uri);
      }

      if (resource.getUUID() == null) {
        resource.setUUID(UUID.randomUUID().toString());
      }

      String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1);
      if (grammarsElement != null) {
        // This is to avoid evaluating the grammars import when building AST
        grammarsElement.detach();
        wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version));
      }
    } else {
      if (!skipValidation) {
        File tempFile = null;
        BufferedWriter bufferedWriter = null;
        try {
          tempFile = File.createTempFile(wadlName, null);
          bufferedWriter = new BufferedWriter(new FileWriter(tempFile));
          bufferedWriter.write(wadlElement.toString());
          bufferedWriter.flush();
        } catch (IOException e) {
          String msg = "Error occurred while reading the WADL File";
          log.error(msg, e);
          throw new RegistryException(msg, e);
        } finally {
          if (bufferedWriter != null) {
            try {
              bufferedWriter.close();
            } catch (IOException e) {
              String msg = "Error occurred while closing File writer";
              log.warn(msg, e);
            }
          }
        }
        validateWADL(tempFile.toURI().toString());
        try {
          delete(tempFile);
        } catch (IOException e) {
          String msg =
              "An error occurred while deleting the temporary files from local file system.";
          log.warn(msg, e);
          throw new RegistryException(msg, e);
        }
      }

      if (grammarsElement != null) {
        grammarsElement = resolveImports(grammarsElement, null, version);
        wadlElement.addChild(grammarsElement);
      }
    }

    requestContext.setResourcePath(new ResourcePath(actualPath));
    if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) {
      resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
    }
    registry.put(actualPath, resource);
    addImportAssociations(actualPath);
    if (getCreateService()) {
      OMElement serviceElement =
          RESTServiceUtils.createRestServiceArtifact(
              wadlElement,
              wadlName,
              version,
              RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath));
      String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement);
      registry.addAssociation(servicePath, actualPath, CommonConstants.DEPENDS);
      registry.addAssociation(actualPath, servicePath, CommonConstants.USED_BY);
      String endpointPath = createEndpointElement(requestContext, wadlElement, version);
      if (endpointPath != null) {
        registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS);
        registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY);
      }
    }

    return resource.getPath();
  }
  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();
    }
  }