Пример #1
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;
  }
Пример #2
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;
  }
  /**
   * 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);
        }
      }
    }
  }
Пример #4
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());
 }
Пример #5
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;
  }