Ejemplo n.º 1
0
  /**
   * Saves a swagger document in the registry.
   *
   * @param contentStream resource content.
   * @param path resource path.
   * @param documentVersion version of the swagger document.
   * @throws RegistryException If fails to add the swagger document to registry.
   */
  private boolean addSwaggerDocumentToRegistry(
      ByteArrayOutputStream contentStream, String path, String documentVersion)
      throws RegistryException {
    Resource resource;
    /*
    Checks if a resource is already exists in the given path.
    If exists,
    	Compare resource contents and if updated, updates the document, if not skip the updating process
    If not exists,
    	Creates a new resource and add to the resource path.
     */
    if (registry.resourceExists(path)) {
      resource = registry.get(path);
      Object resourceContentObj = resource.getContent();
      String resourceContent;
      if (resourceContentObj instanceof String) {
        resourceContent = (String) resourceContentObj;
        resource.setContent(RegistryUtils.encodeString(resourceContent));
      } else if (resourceContentObj instanceof byte[]) {
        resourceContent = RegistryUtils.decodeBytes((byte[]) resourceContentObj);
      } else {
        throw new RegistryException(CommonConstants.INVALID_CONTENT);
      }
      if (resourceContent.equals(contentStream.toString())) {
        log.info("Old content is same as the new content. Skipping the put action.");
        return false;
      }
    } else {
      // If a resource does not exist in the given path.
      resource = new ResourceImpl();
    }

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

    resource.setUUID(resourceId);
    resource.setMediaType(CommonConstants.SWAGGER_MEDIA_TYPE);
    resource.setContent(contentStream.toByteArray());
    resource.addProperty(RegistryConstants.VERSION_PARAMETER_NAME, documentVersion);
    CommonUtil.copyProperties(this.requestContext.getResource(), resource);
    registry.put(path, resource);

    return true;
  }
Ejemplo n.º 2
0
  /**
   * 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;
  }
Ejemplo n.º 3
0
  /**
   * 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;
  }
Ejemplo n.º 4
0
  /**
   * Adds the given WSDL artifact to the registry.
   *
   * @param wsdl the WSDL artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void addWsdl(Wsdl wsdl) throws GovernanceException {
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      String url = wsdl.getUrl();
      Resource wsdlResource = registry.newResource();
      wsdlResource.setMediaType(GovernanceConstants.WSDL_MEDIA_TYPE);

      // setting the wsdl content
      setContent(wsdl, wsdlResource);
      wsdlResource.setUUID(wsdl.getId());

      String tmpPath;
      if (wsdl.getQName() != null) {
        tmpPath = "/" + wsdl.getQName().getLocalPart();
      } else if (url != null && !url.startsWith("name://")) {
        tmpPath = RegistryUtils.getResourceName(new URL(url).getFile().replace("~", ""));
      } else if (url != null) {
        tmpPath = url.substring("name://".length());
      } else {
        tmpPath = wsdl.getId() + ".wsdl";
      }
      // OK this is a hack to get the UUID of the newly added artifact. This needs to be fixed
      // properly with the fix for UUID support at Kernel-level - Janaka.
      //            Resource resource;
      if (url == null || url.startsWith("name://")) {
        //                resource = registry.get(registry.put("/" + tmpPath, wsdlResource));
        registry.put("/" + tmpPath, wsdlResource);
      } else {
        //                resource = registry.get(registry.importResource(tmpPath, url,
        // wsdlResource));
        registry.importResource(tmpPath, url, wsdlResource);
      }
      //            wsdl.setId(resource.getUUID());
      wsdl.updatePath();
      //    wsdl.loadWsdlDetails();
      succeeded = true;
    } catch (RegistryException e) {
      String msg = "Error in adding the wsdl. wsdl id: " + wsdl.getId() + ".";
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } catch (MalformedURLException e) {
      String msg = "Malformed policy url provided. url: " + wsdl.getUrl() + ".";
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in committing transactions. Add wsdl failed: wsdl id: "
                  + wsdl.getId()
                  + ", path: "
                  + wsdl.getPath()
                  + ".";
          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Add wsdl failed: wsdl id: "
                  + wsdl.getId()
                  + ", path: "
                  + wsdl.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
Ejemplo n.º 5
0
 /**
  * Sets content of the given WSDL artifact to the given resource on the registry.
  *
  * @param wsdl the WSDL artifact.
  * @param wsdlResource the content resource.
  * @throws GovernanceException if the operation failed.
  */
 protected void setContent(Wsdl wsdl, Resource wsdlResource) throws GovernanceException {
   if (wsdl.getWsdlElement() != null) {
     OMElement contentElement = wsdl.getWsdlElement().cloneOMElement();
     try {
       for (String importType : new String[] {"import", "include"}) {
         List<OMElement> wsdlImports =
             GovernanceUtils.evaluateXPathToElements("//wsdl:" + importType, contentElement);
         for (OMElement wsdlImport : wsdlImports) {
           OMAttribute location = wsdlImport.getAttribute(new QName("location"));
           if (location != null) {
             String path = location.getAttributeValue();
             if (path.indexOf(";version:") > 0) {
               location.setAttributeValue(path.substring(0, path.lastIndexOf(";version:")));
             }
           }
         }
       }
       for (String importType : new String[] {"import", "include", "redefine"}) {
         List<OMElement> schemaImports =
             GovernanceUtils.evaluateXPathToElements("//xsd:" + importType, contentElement);
         for (OMElement schemaImport : schemaImports) {
           OMAttribute location = schemaImport.getAttribute(new QName("schemaLocation"));
           if (location != null) {
             String path = location.getAttributeValue();
             if (path.indexOf(";version:") > 0) {
               location.setAttributeValue(path.substring(0, path.lastIndexOf(";version:")));
             }
           }
         }
       }
     } catch (JaxenException ignore) {
     }
     String wsdlContent = contentElement.toString();
     try {
       wsdlResource.setContent(wsdlContent);
     } catch (RegistryException e) {
       String msg =
           "Error in setting the content from wsdl, wsdl id: "
               + wsdl.getId()
               + ", wsdl path: "
               + wsdl.getPath()
               + ".";
       log.error(msg, e);
       throw new GovernanceException(msg, e);
     }
   }
   // and set all the attributes as properties.
   String[] attributeKeys = wsdl.getAttributeKeys();
   if (attributeKeys != null) {
     Properties properties = new Properties();
     for (String attributeKey : attributeKeys) {
       String[] attributeValues = wsdl.getAttributes(attributeKey);
       if (attributeValues != null) {
         // The list obtained from the Arrays#asList method is
         // immutable. Therefore,
         // we create a mutable object out of it before adding it as
         // a property.
         properties.put(attributeKey, new ArrayList<String>(Arrays.asList(attributeValues)));
       }
     }
     wsdlResource.setProperties(properties);
   }
   wsdlResource.setUUID(wsdl.getId());
 }
Ejemplo n.º 6
0
  /**
   * Updates the given WSDL artifact on the registry.
   *
   * @param wsdl the WSDL artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void updateWsdl(Wsdl wsdl) throws GovernanceException {
    if (wsdl.getWsdlElement() == null) {
      // there won't be any updates
      String msg =
          "Updates are only accepted if the wsdlElement available. "
              + "So no updates will be done. "
              + "wsdl id: "
              + wsdl.getId()
              + ", wsdl path: "
              + wsdl.getPath()
              + ".";
      log.error(msg);
      throw new GovernanceException(msg);
    }
    boolean succeeded = false;
    try {
      registry.beginTransaction();

      // getting the old wsdl.
      Wsdl oldWsdl = getWsdl(wsdl.getId());
      if (oldWsdl == null) {
        addWsdl(wsdl);
        return;
      }
      // we are expecting only the OMElement to be different.
      Resource wsdlResource = registry.newResource();
      wsdlResource.setMediaType(GovernanceConstants.WSDL_MEDIA_TYPE);

      // setting the wsdl content
      setContent(wsdl, wsdlResource);

      // remove the old wsdl resource.
      String tmpPath = oldWsdl.getPath();
      wsdlResource.setUUID(wsdl.getId());
      registry.put(tmpPath, wsdlResource);
      //            wsdl.setId(wsdlResource.getUUID());
      wsdl.updatePath();
      //            wsdl.loadWsdlDetails();

      succeeded = true;
    } catch (RegistryException e) {
      String msg =
          "Error in updating the wsdl, wsdl id: "
              + wsdl.getId()
              + ", wsdl path: "
              + wsdl.getPath()
              + ".";
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in committing transactions. Update wsdl failed: wsdl id: "
                  + wsdl.getId()
                  + ", path: "
                  + wsdl.getPath()
                  + ".";
          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Update wsdl failed: wsdl id: "
                  + wsdl.getId()
                  + ", path: "
                  + wsdl.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
  /**
   * Updates the given artifact on the registry.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void updateGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    boolean succeeded = false;
    try {
      registry.beginTransaction();
      validateArtifact(artifact);
      GovernanceArtifact oldArtifact = getGovernanceArtifact(artifact.getId());
      // first check for the old artifact and remove it.
      String oldPath = null;
      if (oldArtifact != null) {
        QName oldName = oldArtifact.getQName();
        if (!oldName.equals(artifact.getQName())) {
          String temp = oldArtifact.getPath();
          // then it is analogue to moving the resource for the new location
          // so just delete the old path
          registry.delete(temp);

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

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

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

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

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

          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Update artifact failed: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
  /**
   * Adds the given artifact to the registry. Please do not use this method to update an existing
   * artifact use the update method instead. If this method is used to update an existing artifact,
   * all existing properties (such as lifecycle details) will be removed from the existing artifact.
   *
   * @param artifact the artifact.
   * @throws GovernanceException if the operation failed.
   */
  public void addGovernanceArtifact(GovernanceArtifact artifact) throws GovernanceException {
    // adding the attributes for name, namespace + artifact
    if (artifact.getQName() == null || artifact.getQName().getLocalPart() == null) {
      String msg = "A valid qualified name was not set for this artifact";
      log.error(msg);
      throw new GovernanceException(msg);
    }
    validateArtifact(artifact);
    String artifactName = artifact.getQName().getLocalPart();
    artifact.setAttributes(artifactNameAttribute, new String[] {artifactName});
    // namespace can be null
    String namespace = artifact.getQName().getNamespaceURI();
    if (artifactNamespaceAttribute != null) {
      artifact.setAttributes(artifactNamespaceAttribute, new String[] {namespace});
    }

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

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

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

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

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

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

      succeeded = true;
    } catch (RegistryException e) {
      String msg;
      if (artifact.getPath() != null) {
        msg =
            "Failed to add artifact: artifact id: "
                + artifact.getId()
                + ", path: "
                + artifact.getPath()
                + ". "
                + e.getMessage();
      } else {
        msg = "Failed to add artifact: artifact id: " + artifact.getId() + ". " + e.getMessage();
      }
      log.error(msg, e);
      throw new GovernanceException(msg, e);
    } finally {
      if (succeeded) {
        try {
          registry.commitTransaction();
        } catch (RegistryException e) {
          String msg;
          if (artifact.getPath() != null) {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ", path: "
                    + artifact.getPath()
                    + ".";
          } else {
            msg =
                "Error in committing transactions. Failed to add artifact: artifact "
                    + "id: "
                    + artifact.getId()
                    + ".";
          }
          log.error(msg, e);
        }
      } else {
        try {
          registry.rollbackTransaction();
        } catch (RegistryException e) {
          String msg =
              "Error in rolling back transactions. Failed to add artifact: "
                  + "artifact id: "
                  + artifact.getId()
                  + ", path: "
                  + artifact.getPath()
                  + ".";
          log.error(msg, e);
        }
      }
    }
  }
Ejemplo n.º 9
0
  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();
  }
Ejemplo n.º 10
0
  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 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();
    }
  }