private String getSwaggerRegistryPath(String swaggerDocName, String serviceProvider) {
   String pathExpression =
       Utils.getRxtService().getStoragePath(CommonConstants.SWAGGER_MEDIA_TYPE);
   pathExpression =
       CommonUtil.getPathFromPathExpression(
           pathExpression, requestContext.getResource().getProperties(), null);
   pathExpression =
       CommonUtil.replaceExpressionOfPath(pathExpression, "provider", serviceProvider);
   swaggerResourcesPath = pathExpression;
   pathExpression = CommonUtil.replaceExpressionOfPath(pathExpression, "name", swaggerDocName);
   String swaggerPath = pathExpression;
   /**
    * Fix for the REGISTRY-3052 : validation is to check the whether this invoked by
    * ZIPWSDLMediaTypeHandler Setting the registry and absolute paths to current session to avoid
    * incorrect resource path entry in REG_LOG table
    */
   if (CurrentSession.getLocalPathMap() != null
       && !Boolean.valueOf(
           CurrentSession.getLocalPathMap().get(CommonConstants.ARCHIEVE_UPLOAD))) {
     swaggerPath =
         CommonUtil.getRegistryPath(
             requestContext.getRegistry().getRegistryContext(), pathExpression);
     if (log.isDebugEnabled()) {
       log.debug(
           "Saving current session local paths, key: "
               + swaggerPath
               + " | value: "
               + pathExpression);
     }
     CurrentSession.getLocalPathMap().put(swaggerPath, pathExpression);
   }
   return swaggerPath;
 }
  /**
   * This method used to generate endpoint path
   *
   * @param requestContext Request Context
   * @param endpointElement Endpoint XML element
   * @param endpointPath Current endpoint path
   * @return Updated endpoint path;
   */
  private static String getEndpointPath(
      RequestContext requestContext, OMElement endpointElement, String endpointPath) {
    String pathExpression =
        Utils.getRxtService().getStoragePath(CommonConstants.ENDPOINT_MEDIA_TYPE);
    pathExpression =
        CommonUtil.getPathFromPathExpression(
            pathExpression, endpointElement, requestContext.getResource().getProperties());
    endpointPath = CommonUtil.replaceExpressionOfPath(pathExpression, "name", endpointPath);

    return CommonUtil.getRegistryPath(
        requestContext.getRegistry().getRegistryContext(), endpointPath);
  }
  /**
   * 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);
  }
 @Override
 public void delete(RequestContext requestContext) throws RegistryException {
   if (!CommonUtil.isUpdateLockAvailable()) {
     return;
   }
   CommonUtil.acquireUpdateLock();
   try {
     Registry registry = requestContext.getRegistry();
     ResourcePath resourcePath = requestContext.getResourcePath();
     if (resourcePath == null) {
       throw new RegistryException("The resource path is not available.");
     }
     Resource resource = registry.get(resourcePath.getPath());
   } finally {
     CommonUtil.releaseUpdateLock();
   }
 }
    public void invoke(RequestContext context, String action) throws RegistryException {
      if (!ACTION.equals(action)) {
        throw new RegistryException("Wrong action");
      }

      Resource r = context.getResource();
      String state = r.getProperty(STATE_PROP);
      if (state == null) {
        throw new RegistryException("No state property");
      }

      if (!INIT.equals(state)) {
        throw new RegistryException("Invalid state '" + state + "'");
      }

      r.setProperty(STATE_PROP, FINAL);
      context.getRegistry().put(r.getPath(), r);
    }
    public String[] getAvailableActions(RequestContext context) {
      Resource r = context.getResource();
      String state = r.getProperty(STATE_PROP);

      if (INIT.equals(state)) {
        return actions;
      }

      return null;
    }
 /**
  * Generate REST service path
  *
  * @param requestContext Request Context
  * @param data REST Service content(OMElement)
  * @param serviceName REST Service name
  * @param serviceProvider Service Provider(current user)
  * @return Populated Path
  */
 private static String getRestServicePath(
     RequestContext requestContext, OMElement data, String serviceName, String serviceProvider) {
   String pathExpression =
       Utils.getRxtService().getStoragePath(CommonConstants.REST_SERVICE_MEDIA_TYPE);
   pathExpression = CommonUtil.replaceExpressionOfPath(pathExpression, "name", serviceName);
   pathExpression =
       RegistryUtils.getAbsolutePath(
           requestContext.getRegistryContext(),
           CommonUtil.getPathFromPathExpression(
               pathExpression, data, requestContext.getResource().getProperties()));
   pathExpression =
       CommonUtil.getPathFromPathExpression(
           pathExpression, requestContext.getResource().getProperties(), null);
   pathExpression =
       RegistryUtils.getAbsolutePath(
           requestContext.getRegistryContext(),
           CommonUtil.replaceExpressionOfPath(pathExpression, "provider", serviceProvider));
   return CommonUtil.getRegistryPath(
       requestContext.getRegistry().getRegistryContext(), pathExpression);
 }
  /**
   * Adds the service endpoint element to the registry.
   *
   * @param requestContext current request information.
   * @param endpointElement endpoint metadata element.
   * @param endpointPath endpoint location.
   * @return The resource path of the endpoint.
   * @throws RegistryException If fails to add the endpoint to the registry.
   */
  public static String addEndpointToRegistry(
      RequestContext requestContext, OMElement endpointElement, String endpointPath)
      throws RegistryException {

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

    endpointPath = getEndpointPath(requestContext, endpointElement, endpointPath);

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

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

    endpointResource.setUUID(resourceId);
    // saving the api resource to repository.
    registry.put(endpointPath, endpointResource);
    if (log.isDebugEnabled()) {
      log.debug("Endpoint created at " + endpointPath);
    }
    return endpointPath;
  }
 /**
  * This method used to extract properties from request context
  *
  * @param requestContext Request Context
  * @return Extracted Properties
  */
 private static Properties copyProperties(RequestContext requestContext) {
   Properties properties = requestContext.getResource().getProperties();
   Properties copiedProperties = new Properties();
   if (properties != null) {
     List<String> linkProperties =
         Arrays.asList(
             RegistryConstants.REGISTRY_LINK,
             RegistryConstants.REGISTRY_USER,
             RegistryConstants.REGISTRY_MOUNT,
             RegistryConstants.REGISTRY_AUTHOR,
             RegistryConstants.REGISTRY_MOUNT_POINT,
             RegistryConstants.REGISTRY_TARGET_POINT,
             RegistryConstants.REGISTRY_ACTUAL_PATH,
             RegistryConstants.REGISTRY_REAL_PATH);
     for (Map.Entry<Object, Object> e : properties.entrySet()) {
       String key = (String) e.getKey();
       if (!linkProperties.contains(key)
           && !(key.startsWith("resource") || key.startsWith("registry"))) {
         copiedProperties.put(key, (List<String>) e.getValue());
       }
     }
   }
   return copiedProperties;
 }
  private String saveSchema(String schemaUrl, String version) throws RegistryException {
    if (schemaUrl != null) {
      RequestContext requestContext = new RequestContext(registry, repository, versionRepository);
      Resource local = requestContext.getRegistry().newResource();
      local.setMediaType(xsdMediaType);
      local.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
      requestContext.setSourceURL(schemaUrl);
      requestContext.setResource(local);

      String xsdName = schemaUrl;
      if (xsdName.lastIndexOf("/") != -1) {
        xsdName = xsdName.substring(xsdName.lastIndexOf("/"));
      } else {
        xsdName = "/" + xsdName;
      }
      String path = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + xsdName;
      requestContext.setResourcePath(new ResourcePath(path));
      WSDLValidationInfo validationInfo;
      try {
        validationInfo = SchemaValidator.validate(new XMLInputSource(null, schemaUrl, null));
      } catch (Exception e) {
        throw new RegistryException("Exception occured while validating the schema", e);
      }

      SchemaProcessor schemaProcessor = new SchemaProcessor(requestContext, validationInfo);
      try {
        return schemaProcessor.importSchemaToRegistry(
            requestContext,
            path,
            getChrootedSchemaLocation(requestContext.getRegistryContext()),
            true,
            true);
      } catch (RegistryException e) {
        throw new RegistryException("Failed to import the schema", e);
      }
    }
    return null;
  }
 public WADLProcessor(RequestContext requestContext) {
   registry = requestContext.getRegistry();
   repository = requestContext.getRepository();
   versionRepository = requestContext.getVersionRepository();
 }
 public SwaggerProcessor(RequestContext requestContext) {
   this.parser = new JsonParser();
   this.requestContext = requestContext;
   this.registry = requestContext.getRegistry();
 }
  /**
   * Saves the REST Service registry artifact created from the imported swagger definition.
   *
   * @param requestContext information about current request.
   * @param data service artifact metadata.
   * @throws RegistryException If a failure occurs when adding the api to registry.
   */
  public static String addServiceToRegistry(RequestContext requestContext, OMElement data)
      throws RegistryException {

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

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

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

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

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

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

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

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

    registry.put(pathExpression, serviceResource);

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

    if (log.isDebugEnabled()) {
      log.debug("REST Service created at " + pathExpression);
    }
    return pathExpression;
  }
  public void put(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    Object content = resource.getContent();
    String contentString;
    if (content instanceof String) {
      contentString = (String) content;
    } else {
      contentString = RegistryUtils.decodeBytes((byte[]) content);
    }
    OMElement payload;
    try {
      payload = AXIOMUtil.stringToOM(contentString);
    } catch (XMLStreamException e) {
      String msg = "Unable to serialize resource content";
      log.error(msg, e);
      throw new RegistryException(msg, e);
    }
    OMNamespace namespace = payload.getNamespace();
    String namespaceURI = namespace.getNamespaceURI();
    OMElement definition = payload.getFirstChildWithName(new QName(namespaceURI, "definition"));
    OMElement projectPath =
        definition.getFirstChildWithName(new QName(namespaceURI, "projectPath"));
    String projectMetadataPath = null;
    if (projectPath != null) {
      projectMetadataPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + projectPath.getText();
    }

    Resource metadataResource = requestContext.getRegistry().get(projectMetadataPath);

    String remainingWork = metadataResource.getProperty("Remaining Work");
    String scheduledWork = metadataResource.getProperty("Scheduled Work");
    String actualWork = metadataResource.getProperty("Actual Work");

    String remainingCost = metadataResource.getProperty("Remaining Cost");
    String scheduledCost = metadataResource.getProperty("Scheduled Cost");
    String actualCost = metadataResource.getProperty("Actual Cost");

    String duration = metadataResource.getProperty("Duration");
    String startDate = metadataResource.getProperty("Start Date");
    String endDate = metadataResource.getProperty("Finish Date");

    OMFactory factory = payload.getOMFactory();
    OMElement work = payload.getFirstChildWithName(new QName(namespaceURI, "work"));
    if (work == null) {
      work = factory.createOMElement("work", namespace, payload);
    }
    OMElement remainingWorkElement =
        work.getFirstChildWithName(new QName(namespaceURI, "remaining"));
    if (remainingWorkElement == null) {
      remainingWorkElement = factory.createOMElement("remaining", namespace, work);
    }
    remainingWorkElement.setText(remainingWork);
    OMElement actualWorkElement = work.getFirstChildWithName(new QName(namespaceURI, "actual"));
    if (actualWorkElement == null) {
      actualWorkElement = factory.createOMElement("actual", namespace, work);
    }
    actualWorkElement.setText(remainingWork);
    OMElement scheduledWorkElement =
        work.getFirstChildWithName(new QName(namespaceURI, "scheduled"));
    if (scheduledWorkElement == null) {
      scheduledWorkElement = factory.createOMElement("scheduled", namespace, work);
    }
    scheduledWorkElement.setText(remainingWork);

    OMElement cost = payload.getFirstChildWithName(new QName(namespaceURI, "cost"));
    if (cost == null) {
      cost = factory.createOMElement("cost", namespace, payload);
    }
    OMElement remainingCostElement =
        cost.getFirstChildWithName(new QName(namespaceURI, "remaining"));
    if (remainingCostElement == null) {
      remainingCostElement = factory.createOMElement("remaining", namespace, cost);
    }
    remainingCostElement.setText(remainingCost);
    OMElement actualCostElement = cost.getFirstChildWithName(new QName(namespaceURI, "actual"));
    if (actualCostElement == null) {
      actualCostElement = factory.createOMElement("actual", namespace, cost);
    }
    actualCostElement.setText(remainingCost);
    OMElement scheduledCostElement =
        cost.getFirstChildWithName(new QName(namespaceURI, "scheduled"));
    if (scheduledCostElement == null) {
      scheduledCostElement = factory.createOMElement("scheduled", namespace, cost);
    }
    scheduledCostElement.setText(remainingCost);

    OMElement timeline = payload.getFirstChildWithName(new QName(namespaceURI, "timeline"));
    if (timeline == null) {
      timeline = factory.createOMElement("timeline", namespace, payload);
    }
    OMElement durationElement = timeline.getFirstChildWithName(new QName(namespaceURI, "duration"));
    if (durationElement == null) {
      durationElement = factory.createOMElement("duration", namespace, timeline);
    }
    durationElement.setText(duration);
    OMElement startDateElement =
        timeline.getFirstChildWithName(new QName(namespaceURI, "startDate"));
    if (startDateElement == null) {
      startDateElement = factory.createOMElement("startDate", namespace, timeline);
    }
    startDateElement.setText(startDate);
    OMElement endDateElement = timeline.getFirstChildWithName(new QName(namespaceURI, "endDate"));
    if (endDateElement == null) {
      endDateElement = factory.createOMElement("endDate", namespace, timeline);
    }
    endDateElement.setText(endDate);

    resource.setContent(payload.toString());
  }
  /**
   * Saves the swagger file as a registry artifact.
   *
   * @param inputStream input stream to read content.
   * @param commonLocation root location of the swagger artifacts.
   * @param sourceUrl source URL.
   * @throws RegistryException If a failure occurs when adding the swagger to registry.
   */
  public boolean processSwagger(InputStream inputStream, String commonLocation, String sourceUrl)
      throws RegistryException {
    // create a collection if not exists.
    createCollection(commonLocation);

    // Reading resource content and content details.
    ByteArrayOutputStream swaggerContentStream = CommonUtil.readSourceContent(inputStream);
    JsonObject swaggerDocObject = getSwaggerObject(swaggerContentStream.toString());
    String swaggerVersion = getSwaggerVersion(swaggerDocObject);
    documentVersion =
        requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME);
    if (documentVersion == null) {
      documentVersion = CommonConstants.SWAGGER_DOC_VERSION_DEFAULT_VALUE;
      requestContext
          .getResource()
          .setProperty(RegistryConstants.VERSION_PARAMETER_NAME, documentVersion);
    }
    String swaggerResourcePath = getSwaggerDocumentPath(commonLocation, swaggerDocObject);

    /*
    Switches from the swagger version and process document adding process and the REST Service creation process
    using the relevant documents.
     */
    if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) {
      if (addSwaggerDocumentToRegistry(
          swaggerContentStream, swaggerResourcePath, documentVersion)) {
        List<JsonObject> resourceObjects =
            addResourceDocsToRegistry(swaggerDocObject, sourceUrl, swaggerResourcePath);
        restServiceElement =
            (resourceObjects != null)
                ? RESTServiceUtils.createRestServiceArtifact(
                    swaggerDocObject,
                    swaggerVersion,
                    endpointUrl,
                    resourceObjects,
                    swaggerResourcePath,
                    documentVersion)
                : null;
      } else {
        return false;
      }

    } else if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) {
      if (addSwaggerDocumentToRegistry(
          swaggerContentStream, swaggerResourcePath, documentVersion)) {
        createEndpointElement(swaggerDocObject, swaggerVersion);
        restServiceElement =
            RESTServiceUtils.createRestServiceArtifact(
                swaggerDocObject,
                swaggerVersion,
                endpointUrl,
                null,
                swaggerResourcePath,
                documentVersion);
      } else {
        return false;
      }
    }

    /*
    If REST Service content is not empty, saves the REST service and adds the relevant associations.
     */
    if (restServiceElement != null) {
      String servicePath =
          RESTServiceUtils.addServiceToRegistry(requestContext, restServiceElement);
      registry.addAssociation(servicePath, swaggerResourcePath, CommonConstants.DEPENDS);
      registry.addAssociation(swaggerResourcePath, servicePath, CommonConstants.USED_BY);

      if (endpointUrl != null) {
        String endpointPath =
            RESTServiceUtils.addEndpointToRegistry(
                requestContext, endpointElement, endpointLocation);
        registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS);
        registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY);
      }
    } else {
      log.warn("Service content is null. Cannot create the REST Service artifact.");
    }

    CommonUtil.closeOutputStream(swaggerContentStream);

    return true;
  }
  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();
    }
  }
 public void dissociate(RequestContext context) {
   context.getResource().removeProperty(STATE_PROP);
 }
  public String importWADLToRegistry(
      RequestContext requestContext, String commonLocation, boolean skipValidation)
      throws RegistryException {

    ResourcePath resourcePath = requestContext.getResourcePath();
    String wadlName = RegistryUtils.getResourceName(resourcePath.getPath());
    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);
    }

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

    Registry registry = requestContext.getRegistry();
    Resource resource = registry.newResource();
    if (resource.getUUID() == null) {
      resource.setUUID(UUID.randomUUID().toString());
    }
    resource.setMediaType(wadlMediaType);
    resource.setProperties(requestContext.getResource().getProperties());

    ByteArrayOutputStream outputStream;
    OMElement wadlElement;
    try {
      InputStream inputStream = new URL(uri).openStream();

      outputStream = new ByteArrayOutputStream();
      int nextChar;
      while ((nextChar = inputStream.read()) != -1) {
        outputStream.write(nextChar);
      }
      outputStream.flush();
      wadlElement = AXIOMUtil.stringToOM(new String(outputStream.toByteArray()));
      // to validate XML
      wadlElement.toString();
    } catch (Exception e) {
      // This exception is unexpected because the WADL already validated
      throw new RegistryException(
          "Unexpected error occured " + "while reading the WADL at" + uri, e);
    }

    String wadlNamespace = wadlElement.getNamespace().getNamespaceURI();
    String namespaceSegment =
        CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/");

    OMElement grammarsElement =
        wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars"));
    String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1);
    if (grammarsElement != null) {
      grammarsElement.detach();
      wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version));
    }

    String actualPath;
    if (commonLocation != null) {
      actualPath = commonLocation + namespaceSegment + version + "/" + wadlName;
    } else {
      actualPath =
          RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
              + commonWADLLocation
              + namespaceSegment
              + version
              + "/"
              + wadlName;
    }
    if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) {
      resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
    }

    resource.setContent(wadlElement.toString());
    requestContext.setResourcePath(new ResourcePath(actualPath));
    registry.put(actualPath, resource);
    addImportAssociations(actualPath);
    if (createService) {
      OMElement serviceElement =
          RESTServiceUtils.createRestServiceArtifact(
              wadlElement,
              wadlName,
              version,
              RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath));
      String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement);
      addDependency(servicePath, actualPath);
      String endpointPath = createEndpointElement(requestContext, wadlElement, version);
      if (endpointPath != null) {
        addDependency(servicePath, endpointPath);
      }
    }

    return actualPath;
  }
  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();
  }
  /**
   * Generates the service endpoint element from the swagger object.
   *
   * @param swaggerObject swagger document object.
   * @param swaggerVersion swagger version.
   */
  private void createEndpointElement(JsonObject swaggerObject, String swaggerVersion)
      throws RegistryException {
    /*
    Extracting endpoint url from the swagger document.
     */
    if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) {
      JsonElement endpointUrlElement = swaggerObject.get(SwaggerConstants.BASE_PATH);
      if (endpointUrlElement == null) {
        log.warn(
            "Endpoint url is not specified in the swagger document. Endpoint creation might fail. ");
        return;
      } else {
        endpointUrl = endpointUrlElement.getAsString();
      }
    } else if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) {
      JsonElement transportsElement = swaggerObject.get(SwaggerConstants.SCHEMES);
      JsonArray transports =
          (transportsElement != null) ? transportsElement.getAsJsonArray() : null;
      String transport =
          (transports != null) ? transports.get(0).getAsString() + "://" : DEFAULT_TRANSPORT;
      JsonElement hostElement = swaggerObject.get(SwaggerConstants.HOST);
      String host = (hostElement != null) ? hostElement.getAsString() : null;
      if (host == null) {
        log.warn(
            "Endpoint(host) url is not specified in the swagger document. "
                + "The host serving the documentation is to be used(including the port) as endpoint host");

        if (requestContext.getSourceURL() != null) {
          URL sourceURL = null;
          try {
            sourceURL = new URL(requestContext.getSourceURL());
          } catch (MalformedURLException e) {
            throw new RegistryException("Error in parsing the source URL. ", e);
          }
          host = sourceURL.getAuthority();
        }
      }

      if (host == null) {
        log.warn(
            "Can't derive the endpoint(host) url when uploading swagger from file. "
                + "Endpoint creation might fail. ");
        return;
      }

      JsonElement basePathElement = swaggerObject.get(SwaggerConstants.BASE_PATH);
      String basePath =
          (basePathElement != null) ? basePathElement.getAsString() : DEFAULT_BASE_PATH;

      endpointUrl = transport + host + basePath;
    }
    /*
    Creating endpoint artifact
     */
    OMFactory factory = OMAbstractFactory.getOMFactory();
    endpointLocation = EndpointUtils.deriveEndpointFromUrl(endpointUrl);
    String endpointName = EndpointUtils.deriveEndpointNameWithNamespaceFromUrl(endpointUrl);
    String endpointContent =
        EndpointUtils.getEndpointContentWithOverview(
            endpointUrl, endpointLocation, endpointName, documentVersion);
    try {
      endpointElement = AXIOMUtil.stringToOM(factory, endpointContent);
    } catch (XMLStreamException e) {
      throw new RegistryException("Error in creating the endpoint element. ", e);
    }
  }