Ejemplo n.º 1
0
  public static boolean addDefaultHandlersIfNotAvailable(Registry configSystemRegistry)
      throws RegistryException, FileNotFoundException, XMLStreamException {

    if (!configSystemRegistry.resourceExists(RegistryConstants.HANDLER_CONFIGURATION_PATH)) {
      Collection handlerConfigurationCollection = new CollectionImpl();
      String description = "Handler configurations are stored here.";
      handlerConfigurationCollection.setDescription(description);
      configSystemRegistry.put(
          RegistryConstants.HANDLER_CONFIGURATION_PATH, handlerConfigurationCollection);
      // We don't have any default handler configuration as in lifecycles.
    } else {
      // configue all handlers
      Resource handlerRoot = configSystemRegistry.get(getContextRoot());
      if (!(handlerRoot instanceof Collection)) {
        String msg =
            "Failed to continue as the handler configuration root: "
                + getContextRoot()
                + " is not a collection.";
        log.error(msg);
        throw new RegistryException(msg);
      }
      Collection handlerRootCol = (Collection) handlerRoot;
      String[] handlerConfigPaths = handlerRootCol.getChildren();
      if (handlerConfigPaths != null) {
        for (String handlerConfigPath : handlerConfigPaths) {
          generateHandler(configSystemRegistry, handlerConfigPath);
        }
      }
    }

    return true;
  }
Ejemplo n.º 2
0
  public static boolean addHandler(Registry configSystemRegistry, String payload)
      throws RegistryException, XMLStreamException {
    String name;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      name = element.getAttributeValue(new QName("class"));
    } else return false;

    if (isHandlerNameInUse(name))
      throw new RegistryException("The added handler name is already in use!");

    String path = getContextRoot() + name;
    Resource resource;
    if (!handlerExists(configSystemRegistry, name)) {
      resource = new ResourceImpl();
    } else {
      throw new RegistryException("The added handler name is already in use!");
    }
    resource.setContent(payload);
    try {
      configSystemRegistry.beginTransaction();
      configSystemRegistry.put(path, resource);
      generateHandler(configSystemRegistry, path);
      configSystemRegistry.commitTransaction();
    } catch (Exception e) {
      configSystemRegistry.rollbackTransaction();
      throw new RegistryException("Unable to generate handler", e);
    }
    return true;
  }
Ejemplo n.º 3
0
  public static String[] getHandlerList(Registry configSystemRegistry) throws RegistryException {
    Collection collection;
    try {
      collection = (Collection) configSystemRegistry.get(getContextRoot());
    } catch (Exception e) {
      return null;
    }

    if (collection == null) {
      CollectionImpl handlerCollection = new CollectionImpl();
      configSystemRegistry.put(getContextRoot(), handlerCollection);
      return null;
    } else {
      if (collection.getChildCount() == 0) {
        return null;
      }

      String[] childrenList = collection.getChildren();
      String[] handlerNameList = new String[collection.getChildCount()];
      for (int i = 0; i < childrenList.length; i++) {
        String path = childrenList[i];
        handlerNameList[i] = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
      }
      return handlerNameList;
    }
  }
  private static void addToRegistry(String rootPath, File file, int tenantId) {
    try {
      Registry registry = getRegistry(tenantId);

      // This path is used to store the file resource under registry
      String fileRegistryPath =
          REGISTRY_GADGET_STORAGE_PATH
              + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

      // Adding the file to the Registry
      Resource fileResource = registry.newResource();
      fileResource.setMediaType("application/vnd.wso2-gadget+xml");
      fileResource.setContentStream(new FileInputStream(file));
      registry.put(fileRegistryPath, fileResource);

    } catch (RegistryException e) {
      log.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
      log.error(e.getMessage(), e);
    }
  }
Ejemplo n.º 5
0
  /**
   * Simulates a configSystemRegistry operation.
   *
   * <p>Operation criteria: get - path put - path, resourcePath (existing resource), optional :
   * mediaType resourceExists - path delete - path importResource - path, param1 (URL: source URL),
   * optional : mediaType copy - path, param1 (target path) move - path, param1 (target path) rename
   * - path, param1 (target path) removeLink - path createLink - path, param1 (target path),
   * optional : param2 (target sub-path) invokeAspect - path, param1 (aspect name), param2 (action)
   * addAssociation - path, param1 (target path), param2 (association type) removeAssociation -
   * path, param1 (target path), param2 (association type) getAssociations - path, param1
   * (association type) getAllAssociations - path createVersion - path restoreVersion - path
   * getVersions - path applyTag - path, param1 (tag) removeTag - path, param1 (tag) getTags - path
   * getResourcePathsWithTag - param1 (tag) rateResource - path, param1 (Number: rating) getRating -
   * path, param1 (username) getAverageRating - path addComment - path, param1 (comment)
   * removeComment - path editComment - path, param1 (comment) getComments - path searchContent -
   * param1 (keywords) executeQuery - param1 (Map: parameters, ex:- key1:val1,key2:val2,...),
   * optional: path
   *
   * <p>Operations not-supported dump restore
   *
   * @param simulationRequest the simulation request.
   * @throws Exception if an exception occurs while executing any operation, or if an invalid
   *     parameter was entered.
   */
  public static void simulateRegistryOperation(
      Registry rootRegistry, SimulationRequest simulationRequest) throws Exception {
    String operation = simulationRequest.getOperation();
    if (operation == null) {
      return;
    }
    if (operation.toLowerCase().equals("get")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.get(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("resourceexists")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.resourceExists(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("put")) {
      String path = simulationRequest.getPath();
      String resourcePath = simulationRequest.getResourcePath();
      String type = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        type = params[0];
      }

      if (isInvalidateValue(path) || isInvalidateValue(type)) {
        return;
      }
      Resource resource;
      if (!isInvalidateValue(resourcePath) && rootRegistry.resourceExists(resourcePath)) {
        resource = rootRegistry.get(resourcePath);
      } else if (type.toLowerCase().equals("collection")) {
        resource = rootRegistry.newCollection();
      } else {
        resource = rootRegistry.newResource();
      }
      simulationService.setSimulation(true);
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.put(path, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("delete")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.delete(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("importresource")) {
      String path = simulationRequest.getPath();
      String sourceURL = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        sourceURL = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(sourceURL)) {
        return;
      }
      simulationService.setSimulation(true);
      Resource resource = rootRegistry.newResource();
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.importResource(path, sourceURL, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rename")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rename(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("move")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.move(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("copy")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.copy(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removelink")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeLink(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createlink")) {
      String path = simulationRequest.getPath();
      String target = null;
      String targetSubPath = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length > 0) {
        target = params[0];
        if (params.length > 1) {
          targetSubPath = params[1];
        }
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      if (isInvalidateValue(targetSubPath)) {
        rootRegistry.createLink(path, target);
      } else {
        rootRegistry.createLink(path, target, targetSubPath);
      }
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("invokeaspect")) {
      String path = simulationRequest.getPath();
      String aspectName = null;
      String action = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        aspectName = params[0];
        action = params[1];
      }
      if (isInvalidateValue(path) || isInvalidateValue(aspectName) || isInvalidateValue(action)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.invokeAspect(path, aspectName, action);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getassociations")) {
      String path = simulationRequest.getPath();
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        associationType = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAssociations(path, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getallassociations")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAllAssociations(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.createVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("restoreversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.restoreVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getversions")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getVersions(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("applytag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.applyTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removetag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("gettags")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getTags(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getresourcepathswithtag")) {
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getResourcePathsWithTag(tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rateresource")) {
      String path = simulationRequest.getPath();
      int rating = -1;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        try {
          rating = Integer.parseInt(params[0]);
        } catch (NumberFormatException ignored) {
          return;
        }
      }
      if (isInvalidateValue(path) || rating == -1) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rateResource(path, rating);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getrating")) {
      String path = simulationRequest.getPath();
      String username = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        username = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(username)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getRating(path, username);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getaveragerating")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAverageRating(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addComment(path, new Comment(comment));
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("editcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.editComment(path, comment);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeComment")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeComment(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getcomments")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getComments(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("searchcontent")) {
      String keywords = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        keywords = params[0];
      }
      if (isInvalidateValue(keywords)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.searchContent(keywords);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("executequery")) {
      String path = simulationRequest.getPath();
      String queryParams = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        queryParams = params[0];
      }
      Map<String, String> paramMap = new LinkedHashMap<String, String>();
      if (isInvalidateValue(queryParams)) {
        return;
      }
      String[] entries = queryParams.split(",");
      if (entries != null) {
        for (String entry : entries) {
          String[] keyValPair = entry.split(":");
          if (keyValPair != null && keyValPair.length == 2) {
            paramMap.put(keyValPair[0], keyValPair[1]);
          }
        }
      }
      simulationService.setSimulation(true);
      rootRegistry.executeQuery(path, paramMap);
      simulationService.setSimulation(false);
    } else {
      throw new Exception("Unsupported Registry Operation: " + operation);
    }
  }
Ejemplo n.º 6
0
  public static boolean updateHandler(Registry configSystemRegistry, String oldName, String payload)
      throws RegistryException, XMLStreamException {
    if (isHandlerNameInUse(oldName))
      throw new RegistryException("Could not update handler since it is already in use!");

    String newName = null;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      newName = element.getAttributeValue(new QName("class"));
    }

    if (newName == null || newName.equals("")) return false; // invalid configuration

    if (oldName == null || oldName.equals("")) {
      String path = getContextRoot() + newName;
      Resource resource;
      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are adding a new handler
      } else {
        resource = new ResourceImpl();
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(path, resource);
        generateHandler(configSystemRegistry, path);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    }

    if (newName.equals(oldName)) {
      // updating the rest of the content
      String oldPath = getContextRoot() + oldName;
      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.put(oldPath, resource);
        generateHandler(configSystemRegistry, oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    } else {
      String oldPath = getContextRoot() + oldName;
      String newPath = getContextRoot() + newName;

      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are trying to use the name of a existing handler
      }

      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }

      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(newPath, resource);
        generateHandler(configSystemRegistry, newPath);
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.delete(oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to renew handler", e);
      }
      return true;
    }
  }
  private static void transferDirectoryContentToRegistry(
      File rootDirectory, Registry registry, String rootPath, int tenantId) throws Exception {

    try {

      File[] filesAndDirs = rootDirectory.listFiles();
      List<File> filesDirs = Arrays.asList(filesAndDirs);

      for (File file : filesDirs) {

        if (!file.isFile()) {
          // This is a Directory add a new collection
          // This path is used to store the file resource under registry
          String directoryRegistryPath =
              REGISTRY_GADGET_STORAGE_PATH
                  + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

          // If the collection exists no need to create it. If not, create.
          if (!registry.resourceExists(directoryRegistryPath)) {
            Collection newCollection = registry.newCollection();
            registry.put(directoryRegistryPath, newCollection);
          }

          // Set permission for anonymous read. We do it here because it should happen always in
          // order
          // to support mounting a remote registry.
          UserRegistry userRegistry = getRegistry(tenantId);
          AuthorizationManager accessControlAdmin =
              userRegistry.getUserRealm().getAuthorizationManager();

          if (!accessControlAdmin.isRoleAuthorized(
              CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
              RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
              ActionConstants.GET)) {
            accessControlAdmin.authorizeRole(
                CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
                ActionConstants.GET);
          }

          // recurse
          transferDirectoryContentToRegistry(file, registry, rootPath, tenantId);
        } else {
          // Adding gadget to the gadget browser: gadget conf.xml need to be present
          if (file.getName().equals(GADGET_CONF_FILE)) {
            FileInputStream fis = new FileInputStream(file);
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader reader = xif.createXMLStreamReader(fis);

            StAXOMBuilder builder = new StAXOMBuilder(reader);
            OMElement omEle = builder.getDocumentElement();

            String gadgetName = omEle.getFirstChildWithName(new QName("name")).getText();
            String gadgetPath = omEle.getFirstChildWithName(new QName("path")).getText();
            String gadgetDesc = omEle.getFirstChildWithName(new QName("description")).getText();

            Resource res = registry.newResource();
            res.setProperty(DashboardConstants.GADGET_NAME, gadgetName);
            res.setProperty(DashboardConstants.GADGET_DESC, gadgetDesc);
            res.setProperty(DashboardConstants.GADGET_URL, gadgetPath);

            registry.put(
                DashboardConstants.SYSTEM_GADGETREPO_REGISTRY_ROOT
                    + DashboardConstants.GADGETS_COL
                    + "/"
                    + gadgetName,
                res);

          } else {
            // Add this to registry
            addToRegistry(rootPath, file, tenantId);
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new Exception(e);
    }
  }
Ejemplo n.º 8
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.º 9
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;
  }