Ejemplo n.º 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;
 }
Ejemplo n.º 2
0
  public static boolean removeHandler(Registry configSystemRegistry, String handlerName)
      throws RegistryException, XMLStreamException {
    String handlerConfiguration = getHandlerConfiguration(configSystemRegistry, handlerName);
    if (handlerConfiguration != null) {
      OMElement element = AXIOMUtil.stringToOM(handlerConfiguration);
      try {
        try {
          configSystemRegistry.beginTransaction();
          RegistryConfigurationProcessor.HandlerDefinitionObject handlerDefinitionObject =
              new RegistryConfigurationProcessor.HandlerDefinitionObject(null, element).invoke();
          String[] methods = handlerDefinitionObject.getMethods();
          Filter filter = handlerDefinitionObject.getFilter();
          Handler handler = handlerDefinitionObject.getHandler();
          if (handlerDefinitionObject.getTenantId() != -1) {
            CurrentSession.setCallerTenantId(handlerDefinitionObject.getTenantId());
            // We need to swap the tenant id for this call, if the handler has overriden the
            // default value.
            configSystemRegistry
                .getRegistryContext()
                .getHandlerManager()
                .removeHandler(
                    methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
            CurrentSession.removeCallerTenantId();
          } else {
            configSystemRegistry
                .getRegistryContext()
                .getHandlerManager()
                .removeHandler(
                    methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
          }

          configSystemRegistry.commitTransaction();
          return true;
        } catch (Exception e) {
          configSystemRegistry.rollbackTransaction();
          throw e;
        }
      } catch (Exception e) {
        if (e instanceof RegistryException) {
          throw (RegistryException) e;
        } else if (e instanceof XMLStreamException) {
          throw (XMLStreamException) e;
        }
        throw new RegistryException("Unable to build handler configuration", e);
      }
    }
    return false;
  }
Ejemplo n.º 3
0
  /**
   * Configures the swagger resource path form its content and returns the swagger document path.
   *
   * @param rootLocation root location of the swagger files.
   * @param content swagger content.
   * @return Common resource path.
   */
  private String getSwaggerDocumentPath(String rootLocation, JsonObject content)
      throws RegistryException {

    String swaggerDocPath = requestContext.getResourcePath().getPath();
    String swaggerDocName =
        swaggerDocPath.substring(swaggerDocPath.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
    JsonElement infoElement = content.get(SwaggerConstants.INFO);
    JsonObject infoObject = (infoElement != null) ? infoElement.getAsJsonObject() : null;

    if (infoObject == null || infoElement.isJsonNull()) {
      throw new RegistryException("Invalid swagger document.");
    }
    String serviceName = infoObject.get(SwaggerConstants.TITLE).getAsString().replaceAll("\\s", "");
    String serviceProvider = CarbonContext.getThreadLocalCarbonContext().getUsername();

    swaggerResourcesPath =
        rootLocation
            + serviceProvider
            + RegistryConstants.PATH_SEPARATOR
            + serviceName
            + RegistryConstants.PATH_SEPARATOR
            + documentVersion;

    String pathExpression = getSwaggerRegistryPath(swaggerDocName, serviceProvider);

    return RegistryUtils.getAbsolutePath(registry.getRegistryContext(), pathExpression);
  }
Ejemplo n.º 4
0
  /**
   * 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;
  }
Ejemplo n.º 5
0
  /**
   * Adds swagger 1.2 api resource documents to registry and returns a list of resource documents as
   * JSON objects.
   *
   * @param swaggerDocObject swagger document JSON object.
   * @param sourceUrl source url of the swagger document.
   * @param swaggerDocPath swagger document path. (path of the registry)
   * @return List of api resources.
   * @throws RegistryException If fails to import or save resource docs to the registry.
   */
  private List<JsonObject> addResourceDocsToRegistry(
      JsonObject swaggerDocObject, String sourceUrl, String swaggerDocPath)
      throws RegistryException {

    if (sourceUrl == null) {
      log.debug(CommonConstants.EMPTY_URL);
      log.warn("Resource paths cannot be read. Creating the REST service might fail.");
      return null;
    } else if (sourceUrl.startsWith("file")) {
      sourceUrl = sourceUrl.substring(0, sourceUrl.lastIndexOf("/"));
    }

    List<JsonObject> resourceObjects = new ArrayList<>();
    // Adding Resource documents to registry.
    JsonArray pathResources = swaggerDocObject.get(SwaggerConstants.APIS).getAsJsonArray();
    ByteArrayOutputStream resourceContentStream = null;
    InputStream resourceInputStream = null;
    String path;

    /*
    Loops through apis array of the swagger 1.2 api-doc and reads all the resource documents and saves them in to
    the registry.
     */
    for (JsonElement pathResource : pathResources) {
      JsonObject resourceObj = pathResource.getAsJsonObject();
      path = resourceObj.get(SwaggerConstants.PATH).getAsString();
      try {
        resourceInputStream = new URL(sourceUrl + path).openStream();
      } catch (IOException e) {
        throw new RegistryException("The URL " + sourceUrl + path + " is incorrect.", e);
      }
      resourceContentStream = CommonUtil.readSourceContent(resourceInputStream);
      JsonObject resourceObject = parser.parse(resourceContentStream.toString()).getAsJsonObject();
      resourceObjects.add(resourceObject);
      if (endpointElement == null) {
        createEndpointElement(resourceObject, SwaggerConstants.SWAGGER_VERSION_12);
      }
      // path = swaggerResourcesPath + path;
      path = path.replace("/", "");
      path = CommonUtil.replaceExpressionOfPath(swaggerResourcesPath, "name", path);
      path = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), path);
      // Save Resource document to registry
      if (addSwaggerDocumentToRegistry(resourceContentStream, path, documentVersion)) {
        // Adding an dependency to API_DOC
        registry.addAssociation(swaggerDocPath, path, CommonConstants.DEPENDS);
      }
    }

    CommonUtil.closeOutputStream(resourceContentStream);
    CommonUtil.closeInputStream(resourceInputStream);
    return resourceObjects;
  }
  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);
  }
Ejemplo n.º 7
0
  /**
   * 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;
  }
  private void setupHandlers() {
    if (Boolean.toString(Boolean.TRUE).equals(System.getProperty("disable.event.handlers"))) {
      initialized = true;
      log.debug(
          "Default Eventing Handlers have been disabled. Events will not be "
              + "generated unless a custom handler has been configured.");
      return;
    }
    RegistryService registryService = EventingDataHolder.getInstance().getRegistryService();
    if (registryService instanceof RemoteRegistryService && !initialized) {
      initialized = true;
      log.warn("Eventing is not available on Remote Registry");
      return;
    }
    if (!initialized && listenerManager != null && registryService != null) {
      initialized = true;
      try {
        // We can't get Registry from Utils, as the MessageContext is not available at
        // activation time.
        Registry systemRegistry = registryService.getConfigSystemRegistry();
        if (registry != null && registry == systemRegistry) {
          return;
        }
        registry = systemRegistry;
        if (registry == null
            || registry.getRegistryContext() == null
            || registry.getRegistryContext().getHandlerManager() == null) {
          String msg = "Error Initializing Registry Eventing Handler";
          log.error(msg);
        } else {
          URLMatcher filter = new URLMatcher();
          filter.setDeletePattern(".*");
          filter.setPutPattern(".*");
          filter.setPutChildPattern(".*");
          filter.setMovePattern(".*");
          filter.setCopyPattern(".*");
          filter.setRenamePattern(".*");
          filter.setCreateVersionPattern(".*");
          filter.setApplyTagPattern(".*");
          filter.setRemoveTagPattern(".*");
          filter.setAddCommentPattern(".*");
          filter.setAddAssociationPattern(".*");
          filter.setRemoveAssociationPattern(".*");
          filter.setRateResourcePattern(".*");
          filter.setCreateLinkPattern(".*");
          filter.setRemoveLinkPattern(".*");
          filter.setRestorePattern(".*");
          RegistryEventingHandler handler = new RegistryEventingHandler();
          registry
              .getRegistryContext()
              .getHandlerManager()
              .addHandler(
                  null, filter, handler, HandlerLifecycleManager.DEFAULT_REPORTING_HANDLER_PHASE);
          registry.setEventingServiceURL(null, endpoint);
          EventingDataHolder.getInstance().setDefaultEventingServiceURL(endpoint);
          log.debug("Successfully Initialized the Registry Eventing Handler");

          /*URLMatcher erbSubManagerMountFilter = new URLMatcher();
          erbSubManagerMountFilter.setPutPattern(
                  eventingRoot + "/.*");
          SubscriptionManagerHandler erbSubManagerMountHanlder =
                  new EmbeddedRegistryBasedSubscriptionManagerMountHandler();
          registry.getRegistryContext().getHandlerManager().addHandler(null,
                  erbSubManagerMountFilter, erbSubManagerMountHanlder);
          erbSubManagerMountHanlder.init(registry.getRegistryContext(), eventingRoot);
          log.debug("Successfully Initialized the Subscription Manager Mount Handler");*/

          URLMatcher erbSubManagerRRFilter = new URLMatcher();
          erbSubManagerRRFilter.setCopyPattern(".*");
          erbSubManagerRRFilter.setRenamePattern(".*");
          erbSubManagerRRFilter.setMovePattern(".*");
          erbSubManagerRRFilter.setDeletePattern(".*");
          SubscriptionManagerHandler erbSubManagerRRHanlder =
              new EmbeddedRegistryBasedSubscriptionManagerResourceRelocateHandler();
          registry
              .getRegistryContext()
              .getHandlerManager()
              .addHandler(
                  null,
                  erbSubManagerRRFilter,
                  erbSubManagerRRHanlder,
                  HandlerLifecycleManager.DEFAULT_REPORTING_HANDLER_PHASE);
          erbSubManagerRRHanlder.init(registry.getRegistryContext(), eventingRoot);
          log.debug("Successfully Initialized the Subscription Manager Resource Relocate Handler");
          log.info("Successfully Initialized Eventing on Registry");
        }
      } catch (Exception e) {
        String msg = "Error Initializing Eventing on Registry";
        log.error(msg, e);
        throw new RuntimeException(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();
    }
  }