public void init(ConfigurationContext configurationContext) {

    tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    String artifactPath = CarbonUtils.getCarbonRepository() + "gadgets";
    File artifactsDir = new File(artifactPath);

    // checking whether its the gadget server is so, setting the gadget path
    String serverName = ServerConfiguration.getInstance().getFirstProperty("Name").trim();

    if (serverName.contains(DashboardConstants.PRODUCT_SERVER_NAME)
        || serverName.contains(DashboardConstants.SERVICE_SERVER_NAME)) {
      REGISTRY_GADGET_STORAGE_PATH =
          DashboardConstants.GS_REGISTRY_ROOT + DashboardConstants.GADGET_PATH;
    }

    if (!artifactsDir.exists()) {
      // If the directory is not there create it
      boolean created = artifactsDir.mkdir();
      if (!created) {
        log.debug("Directory could not be created at : " + artifactPath);
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("Initializing Gadget Deployer..");
    }
  }
  /**
   * Deploys a .gar archive to the Registry path in REGISTRY_GADGET_STORAGE_PATH
   *
   * @param deploymentFileData - info about the deployed file
   * @throws DeploymentException - error while deploying .gar archive
   */
  public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
    try {

      //            int tenantId;
      //            try {
      //                tenantId =
      // MultitenantUtils.getTenantId(DashboardContext.getConfigContext());
      //            } catch (Exception e) {
      //                throw new DeploymentException(e);
      //            }

      UserRegistry registry = getRegistry(tenantID);

      // Extracting archive
      String extractedArchiveDir = extractGarArchive(deploymentFileData.getAbsolutePath());

      // Set permission for anonymous read. We do it here because it should happen always in order
      // to support mounting a remote registry.

      if (registry != null) {
        AuthorizationManager accessControlAdmin = registry.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);
        }

        File gadgetsDir = new File(extractedArchiveDir);
        if (gadgetsDir.exists()) {
          beginFileTansfer(gadgetsDir, tenantID);

          log.info(
              "Successfully populated gadgets from archive ."
                  + deploymentFileData.getAbsolutePath()
                  + " to the registry.");
        } else {
          log.info("Couldn't find contents at '" + extractedArchiveDir + "'. Giving up.");
        }
      }

    } catch (RegistryException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    } catch (CarbonException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    } catch (UserStoreException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    }
  }
  public static void beginFileTansfer(File rootDirectory, int tenantId) throws RegistryException {

    // Storing the root path for future reference
    String rootPath = rootDirectory.getAbsolutePath();

    UserRegistry registry = getRegistry(tenantId);

    // Creating the default gadget collection resource
    Collection defaultGadgetCollection = registry.newCollection();
    try {
      registry.beginTransaction();
      registry.put(REGISTRY_GADGET_STORAGE_PATH, defaultGadgetCollection);

      transferDirectoryContentToRegistry(rootDirectory, registry, rootPath, tenantId);
      registry.commitTransaction();
    } catch (Exception e) {
      registry.rollbackTransaction();
      log.error(e.getMessage(), e);
    }
  }
  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);
    }
  }
  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);
    }
  }
  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();
  }
 /**
  * This method try to delete the temporary file, If it fails it will just log a warning msg.
  *
  * @param file
  * @throws IOException
  */
 private void delete(File file) throws IOException {
   if (file != null && file.exists() && !file.delete()) {
     log.warn("Failed to delete file/directory at path: " + file.getAbsolutePath());
   }
 }