@Before
  public void setUp() throws Exception {
    repository = mock(IUnifiedRepository.class);

    session = mock(IPentahoSession.class);
    when(session.getName()).thenReturn("test");
    PentahoSessionHolder.setSession(session);

    userSettings =
        new HashMap<String, Serializable>() {
          {
            put(USER_SETTING_NAME_1, USER_SETTING_VALUE_1);
            put(UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME, COMMON_USER_SETTING_VALUE);
            put(USER_SETTING_NAME_2, USER_SETTING_VALUE_2);
            put(UserSettingService.SETTING_PREFIX + USER_SETTING_NAME_3, USER_SETTING_VALUE_3);
          }
        };
    globalSettings =
        new HashMap<String, Serializable>() {
          {
            put(GLOBAL_SETTING_NAME_1, GLOBAL_SETTING_VALUE_1);
            put(
                UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME,
                COMMON_GLOBAL_SETTING_VALUE);
            put(GLOBAL_SETTING_NAME_2, GLOBAL_SETTING_VALUE_2);
            put(UserSettingService.SETTING_PREFIX + GLOBAL_SETTING_NAME_3, GLOBAL_SETTING_VALUE_3);
          }
        };

    when(repository.getFileMetadata(eq(USER_FOLDER_ID))).thenReturn(userSettings);
    when(repository.getFileMetadata(eq(TENANT_FOLDER_ID))).thenReturn(globalSettings);

    final RepositoryFile tenantRepositoryFile = mock(RepositoryFile.class);
    when(tenantRepositoryFile.getId()).thenReturn(TENANT_FOLDER_ID);
    when(repository.getFile(eq(ClientRepositoryPaths.getEtcFolderPath())))
        .thenReturn(tenantRepositoryFile);

    final RepositoryFile userRepositoryFile = mock(RepositoryFile.class);
    when(userRepositoryFile.getId()).thenReturn(USER_FOLDER_ID);
    when(repository.getFile(eq(ClientRepositoryPaths.getUserHomeFolderPath(session.getName()))))
        .thenReturn(userRepositoryFile);

    securityHelper = mock(ISecurityHelper.class);
    when(securityHelper.runAsSystem(any(Callable.class)))
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                final Callable callable = (Callable) invocation.getArguments()[0];
                if (callable != null) {
                  return callable.call();
                }
                return null;
              }
            });
    SecurityHelper.setMockInstance(securityHelper);

    userSettingService = new UserSettingService(repository);
    userSettingService.init(session);
  }
 @Override
 public void createContent() throws Exception {
   this.session = PentahoSessionHolder.getSession();
   this.repository = PentahoSystem.get(IUnifiedRepository.class, session);
   final RepositoryFile BIRTfile =
       (RepositoryFile) parameterProviders.get("path").getParameter("file");
   final String ExecBIRTFilePath = "../webapps/birt/" + BIRTfile.getId() + ".rptdocument";
   /*
    * Get BIRT report design from repository
    */
   final File ExecBIRTFile = new File(ExecBIRTFilePath);
   if (!ExecBIRTFile.exists()) {
     final FileOutputStream fos = new FileOutputStream(ExecBIRTFilePath);
     try {
       final SimpleRepositoryFileData data =
           repository.getDataForRead(BIRTfile.getId(), SimpleRepositoryFileData.class);
       final InputStream inputStream = data.getInputStream();
       final byte[] buffer = new byte[0x1000];
       int bytesRead = inputStream.read(buffer);
       while (bytesRead >= 0) {
         fos.write(buffer, 0, bytesRead);
         bytesRead = inputStream.read(buffer);
       }
     } catch (final Exception e) {
       Logger.error(getClass().getName(), e.getMessage());
     } finally {
       fos.close();
     }
   }
   /*
    * Redirect to BIRT Viewer
    */
   try {
     // Get informations about user context
     final IUserRoleListService service = PentahoSystem.get(IUserRoleListService.class);
     String roles = "";
     final ListIterator<String> li =
         service.getRolesForUser(null, session.getName()).listIterator();
     while (li.hasNext()) {
       roles = roles + li.next().toString() + ",";
     }
     // Redirect
     final HttpServletResponse response =
         (HttpServletResponse) this.parameterProviders.get("path").getParameter("httpresponse");
     response.sendRedirect(
         "/birt/frameset?__document="
             + BIRTfile.getId()
             + ".rptdocument&__showtitle=false&username="******"&userroles="
             + roles
             + "&reportname="
             + BIRTfile.getTitle());
   } catch (final Exception e) {
     Logger.error(getClass().getName(), e.getMessage());
   }
 }
  @Test
  public void testDeleteFiles() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      String testFile1Id = "abc.txt";
      String testFile2Id = "def.txt";

      // set object in PentahoSystem
      mp.defineInstance(IUnifiedRepository.class, repo);

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + testFile1Id, "abcdefg");
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + testFile2Id, "abcdefg");
      createTestFolder(":home:admin");

      RepositoryFile file1 = repo.getFile(publicFolderPath + "/" + testFile1Id);
      RepositoryFile file2 = repo.getFile(publicFolderPath + "/" + testFile2Id);
      WebResource webResource = resource();
      webResource.path("repo/files/delete").entity(file1.getId() + "," + file2.getId()).put();

      RepositoryFileDto[] deletedFiles =
          webResource
              .path("repo/files/deleted")
              .accept(APPLICATION_XML)
              .get(RepositoryFileDto[].class);
      assertEquals(2, deletedFiles.length);

      webResource.path("repo/files/deletepermanent").entity(file2.getId()).put();
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
 public void fileCreated(String filePath) {
   IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class);
   RepositoryFile outputFile = repository.getFile(filePath);
   if (outputFile != null) {
     Map<String, Serializable> fileMetadata = repository.getFileMetadata(outputFile.getId());
     RepositoryFile inputFile = repository.getFile(inputFilePath);
     if (inputFile != null) {
       fileMetadata.put(PentahoJcrConstants.PHO_CONTENTCREATOR, inputFile.getId());
       repository.setFileMetadata(outputFile.getId(), fileMetadata);
     }
   }
 }
  protected String resolveAnnotationsFilePath(final RepositoryFile domainFile) {

    if (getMetadataDir() != null && domainFile != null) {
      return getMetadataDir().getPath() + "/" + domainFile.getId() + ANNOTATIONS_FILE_ID_POSTFIX;
    }
    return null;
  }
  @Test
  public void testDeleteUserSettingsByName() throws Exception {
    IAuthorizationPolicy policy = mock(IAuthorizationPolicy.class);
    when(policy.isAllowed(anyString())).thenReturn(true);
    PentahoSystem.registerObject(policy);

    final RepositoryFile repositoryFile = mock(RepositoryFile.class);
    when(repositoryFile.getId()).thenReturn(USER_FOLDER_ID);
    when(repository.getFile(anyString())).thenReturn(repositoryFile);

    doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {

                final Map<String, Serializable> settings =
                    (Map<String, Serializable>) invocation.getArguments()[1];

                assertNotNull(settings);
                assertEquals(2, settings.size());

                final Iterator<String> iterator = settings.keySet().iterator();
                assertFalse(iterator.next().startsWith(UserSettingService.SETTING_PREFIX));
                assertFalse(iterator.next().startsWith(UserSettingService.SETTING_PREFIX));

                return null;
              }
            })
        .when(repository)
        .setFileMetadata(eq(USER_FOLDER_ID), anyMap());

    userSettingService.deleteUserSettings("test");
  }
  public void createOrUpdateAnnotationsXml(
      final RepositoryFile domainFile,
      final RepositoryFile annotationsFile,
      final String annotationsXml) {

    if (domainFile == null) {
      return; // exit early
    }

    try {
      ByteArrayInputStream in = new ByteArrayInputStream(annotationsXml.getBytes(DEFAULT_ENCODING));
      final SimpleRepositoryFileData data =
          new SimpleRepositoryFileData(in, DEFAULT_ENCODING, DOMAIN_MIME_TYPE);
      if (annotationsFile == null) {
        // Generate a filename based on the domainId
        final String filename = domainFile.getId() + ANNOTATIONS_FILE_ID_POSTFIX;

        // Create the new file
        getRepository()
            .createFile(
                getMetadataDir().getId(), new RepositoryFile.Builder(filename).build(), data, null);
      } else {
        getRepository().updateFile(annotationsFile, data, null);
      }
    } catch (Exception e) {
      getLogger().warn("Unable to save annotations xml", e);
    }
  }
  /**
   * Creates a new repository file (with the supplied data) and applies the proper metadata to this
   * file.
   *
   * @param domainId the Domain id associated with this file
   * @param locale the locale associated with this file (or null for a domain file)
   * @param data the data to put in the file
   * @return the repository file created
   */
  protected RepositoryFile createUniqueFile(
      final String domainId, final String locale, final SimpleRepositoryFileData data) {
    // Generate a "unique" filename
    final String filename = UUID.randomUUID().toString();

    // Create the new file
    final RepositoryFile file =
        repository.createFile(
            getMetadataDir().getId(), new RepositoryFile.Builder(filename).build(), data, null);

    // Add metadata to the file
    final Map<String, Serializable> metadataMap = new HashMap<String, Serializable>();
    metadataMap.put(PROPERTY_NAME_DOMAIN_ID, domainId);
    if (StringUtils.isEmpty(locale)) {
      // This is a domain file
      metadataMap.put(PROPERTY_NAME_TYPE, TYPE_DOMAIN);
    } else {
      // This is a locale property file
      metadataMap.put(PROPERTY_NAME_TYPE, TYPE_LOCALE);
      metadataMap.put(PROPERTY_NAME_LOCALE, locale);
    }

    // Update the metadata
    repository.setFileMetadata(file.getId(), metadataMap);
    return file;
  }
 /**
  * @param repositoryDir
  * @param outputStream
  */
 @Override
 public void exportDirectory(
     RepositoryFile repositoryDir, OutputStream outputStream, String filePath)
     throws ExportException, IOException {
   addToManifest(repositoryDir);
   List<RepositoryFile> children =
       this.unifiedRepository.getChildren(
           new RepositoryRequest(String.valueOf(repositoryDir.getId()), true, 1, null));
   for (RepositoryFile repositoryFile : children) {
     // exclude 'etc' folder - datasources and etc.
     if (!ClientRepositoryPaths.getEtcFolderPath().equals(repositoryFile.getPath())) {
       if (repositoryFile.isFolder()) {
         if (outputStream.getClass().isAssignableFrom(ZipOutputStream.class)) {
           ZipOutputStream zos = (ZipOutputStream) outputStream;
           ZipEntry entry = new ZipEntry(getZipEntryName(repositoryFile, filePath));
           zos.putNextEntry(entry);
         }
         exportDirectory(repositoryFile, outputStream, filePath);
       } else {
         exportFile(repositoryFile, outputStream, filePath);
       }
     }
   }
   createLocales(repositoryDir, filePath, repositoryDir.isFolder(), outputStream);
 }
 protected void validateEtcWriteAccess(String parentFolderId) {
   RepositoryFile etcFolder = repo.getFile("/etc");
   if (etcFolder != null) {
     String etcFolderId = etcFolder.getId().toString();
     if (etcFolderId.equals(parentFolderId)) {
       throw new RuntimeException("This service is not allowed to access the ETC folder in JCR.");
     }
   }
 }
  /**
   * retrieve a domain from the repo. This does lazy loading of the repo, so it calls
   * reloadDomains() if not already loaded.
   *
   * @param domainId domain to get from the repository
   * @return domain object
   */
  @Override
  public Domain getDomain(final String domainId) {
    if (logger.isDebugEnabled()) {
      logger.debug("getDomain(" + domainId + ")");
    }

    if (StringUtils.isEmpty(domainId)) {
      throw new IllegalArgumentException(
          messages.getErrorString(
              "PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
    }
    Domain domain = null;
    try {
      // Load the domain file
      final RepositoryFile file = getMetadataRepositoryFile(domainId);
      if (file != null) {
        if (hasAccessFor(file)) {
          SimpleRepositoryFileData data =
              repository.getDataForRead(file.getId(), SimpleRepositoryFileData.class);
          if (data != null) {
            domain = xmiParser.parseXmi(data.getStream());
            domain.setId(domainId);
            logger.debug("loaded domain");
            // Load any I18N bundles
            loadLocaleStrings(domainId, domain);
            logger.debug("loaded I18N bundles");
          } else {
            throw new UnifiedRepositoryException(
                messages.getErrorString(
                    "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                    domainId,
                    "data not found"));
          }
        } else {
          throw new PentahoAccessControlException(
              messages.getErrorString(
                  "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                  domainId,
                  "access denied"));
        }
      }
    } catch (Exception e) {
      if (!(e instanceof UnifiedRepositoryException
          || e instanceof PentahoAccessControlException)) {
        throw new UnifiedRepositoryException(
            messages.getErrorString(
                "PentahoMetadataDomainRepository.ERROR_0005_ERROR_RETRIEVING_DOMAIN",
                domainId,
                e.getLocalizedMessage()),
            e);
      }
    }

    // Return
    return domain;
  }
 /**
  * create an entry in the export manifest for this file or folder
  *
  * @param repositoryFile
  * @throws ExportException
  */
 private void addToManifest(RepositoryFile repositoryFile) throws ExportException {
   if (this.withManifest) {
     // add this entity to the manifest
     RepositoryFileAcl fileAcl = unifiedRepository.getAcl(repositoryFile.getId());
     try {
       exportManifest.add(repositoryFile, fileAcl);
     } catch (ExportManifestFormatException e) {
       throw new ExportException(e.getMessage());
     }
   }
 }
 public static MasterReport createReportByName(final String fullFilePathAndName)
     throws ResourceException, IOException {
   IUnifiedRepository unifiedRepository =
       PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession());
   RepositoryFile repositoryFile = unifiedRepository.getFile(fullFilePathAndName);
   if (repositoryFile == null) {
     throw new IOException("File " + fullFilePathAndName + " not found in repository");
   } else {
     return createReport(repositoryFile.getId());
   }
 }
  private NamedParams getMeta(RepositoryFile file) throws KettleException {

    NamedParams meta = null;

    if (file != null) {

      String extension = FilenameUtils.getExtension(file.getName());
      Repository repo = PDIImportUtil.connectToRepository(null);

      if ("ktr".equalsIgnoreCase(extension)) {

        meta = new TransMeta(convertTransformation(file.getId()), repo, true, null, null);

      } else if ("kjb".equalsIgnoreCase(extension)) {

        meta = new JobMeta(convertJob(file.getId()), repo, null);
      }
    }

    return meta;
  }
  /** Performs the process of reloading the domain information from the repository */
  private void internalReloadDomains() {
    lock.writeLock().lock();
    try {
      metadataMapping.reset();

      // Reload the metadata about the metadata (that was fun to say)
      final List<RepositoryFile> children = repository.getChildren(getMetadataDir().getId(), "*");
      if (logger.isTraceEnabled()) {
        logger.trace("\tFound " + children.size() + " files in the repository");
      }
      for (final RepositoryFile child : children) {
        if (getAclHelper().canAccess(child, READ)) {
          // Get the metadata for this file
          final Map<String, Serializable> fileMetadata = repository.getFileMetadata(child.getId());
          if (fileMetadata == null
              || StringUtils.isEmpty((String) fileMetadata.get(PROPERTY_NAME_DOMAIN_ID))) {
            if (logger.isWarnEnabled()) {
              logger.warn(
                  messages.getString(
                      "PentahoMetadataDomainRepository.WARN_0001_FILE_WITHOUT_METADATA",
                      child.getName()));
            }
            continue;
          }
          final String domainId = (String) fileMetadata.get(PROPERTY_NAME_DOMAIN_ID);
          final String type = (String) fileMetadata.get(PROPERTY_NAME_TYPE);
          final String locale = (String) fileMetadata.get(PROPERTY_NAME_LOCALE);
          if (logger.isTraceEnabled()) {
            logger.trace(
                "\tprocessing file [type="
                    + type
                    + " : domainId="
                    + domainId
                    + " : locale="
                    + locale
                    + "]");
          }

          // Save the data in the map
          if (StringUtils.equals(type, TYPE_DOMAIN)) {
            metadataMapping.addDomain(domainId, child);
          } else if (StringUtils.equals(type, TYPE_LOCALE)) {
            metadataMapping.addLocale(domainId, locale, child);
          }
        }
      }

      needToReload = false;
    } finally {
      lock.writeLock().unlock();
    }
  }
 @Override
 public RepositoryFile updateFolder(final RepositoryFile folder, final String versionMessage) {
   return callLogThrow(
       new Callable<RepositoryFile>() {
         public RepositoryFile call() throws Exception {
           return delegatee.updateFolder(folder, versionMessage);
         }
       },
       Messages.getInstance()
           .getString(
               "ExceptionLoggingDecorator.updateFile",
               folder != null ? folder.getId() : null)); // $NON-NLS-1$
 }
 public RepositoryFile updateFile(
     final RepositoryFile file, final IRepositoryFileData data, final String versionMessage) {
   return callLogThrow(
       new Callable<RepositoryFile>() {
         public RepositoryFile call() throws Exception {
           return delegatee.updateFile(file, data, versionMessage);
         }
       },
       Messages.getInstance()
           .getString(
               "ExceptionLoggingDecorator.updateFile",
               file != null ? file.getId() : null)); // $NON-NLS-1$
 }
 @Override
 public List<Locale> getAvailableLocalesForFile(final RepositoryFile repositoryFile) {
   return callLogThrow(
       new Callable<List<Locale>>() {
         public List<Locale> call() throws Exception {
           return delegatee.getAvailableLocalesForFile(repositoryFile);
         }
       },
       Messages.getInstance()
           .getString(
               "ExceptionLoggingDecorator.getAvailableLocalesForFile",
               repositoryFile.getId())); // $NON-NLS-1$
 }
  @Test
  public void testCopyFiles() throws Exception {
    mp.defineInstance(IUnifiedRepository.class, repo);
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {adminAuthorityName, authenticatedAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

    try {
      final String destFolderPath = "public:folder3:folder4";
      final String fileName = "file.txt";

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + fileName, "abcdefg");
      WebResource webResource = resource();
      RepositoryFile file =
          repo.getFile(ClientRepositoryPaths.getPublicFolderPath() + "/" + fileName);
      ClientResponse r =
          webResource
              .path("repo/files/" + destFolderPath + "/children")
              .accept(TEXT_PLAIN)
              .put(ClientResponse.class, file.getId());
      assertResponse(r, Status.OK);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  /**
   * for each locale stored in in Jcr create a .locale file with the stored node properties
   *
   * @param zos
   * @param repositoryFile
   * @param filePath
   * @throws IOException
   */
  private void createLocales(
      RepositoryFile repositoryFile, String filePath, boolean isFolder, OutputStream outputStrean)
      throws IOException {
    ZipEntry entry;
    String zipName;
    String name;
    String localeName;
    Properties properties;
    ZipOutputStream zos = (ZipOutputStream) outputStrean;
    // only process files and folders that we know will have locale settings
    if (supportedLocaleFileExt(repositoryFile)) {
      List<LocaleMapDto> locales = getAvailableLocales(repositoryFile.getId());
      zipName = getZipEntryName(repositoryFile, filePath);
      name = repositoryFile.getName();
      for (LocaleMapDto locale : locales) {
        localeName = locale.getLocale().equalsIgnoreCase("default") ? "" : "_" + locale.getLocale();
        if (isFolder) {
          zipName = getZipEntryName(repositoryFile, filePath) + "index";
          name = "index";
        }

        properties =
            unifiedRepository.getLocalePropertiesForFileById(
                repositoryFile.getId(), locale.getLocale());
        if (properties != null) {
          properties.remove("jcr:primaryType"); // Pentaho Type
          InputStream is = createLocaleFile(name + localeName, properties, locale.getLocale());
          if (is != null) {
            entry = new ZipEntry(zipName + localeName + LOCALE_EXT);
            zos.putNextEntry(entry);
            IOUtils.copy(is, outputStrean);
            zos.closeEntry();
            is.close();
          }
        }
      }
    }
  }
Пример #21
0
 static void deleteContentItem(IContentItem contentItem, IUnifiedRepository unifiedRepository) {
   if (contentItem instanceof RepositoryFileContentItem) {
     String path = contentItem.getPath();
     RepositoryFile repositoryFile = unifiedRepository.getFile(path);
     // repositoryFile can be null if we have not access or file does not exist
     if (repositoryFile != null) {
       unifiedRepository.deleteFile(repositoryFile.getId(), true, null);
     }
   } else if (contentItem instanceof FileContentItem) {
     // Files in the file system must not be deleted here
     String path = ((FileContentItem) contentItem).getFile().getName();
     logger.warn(Messages.getInstance().getString("XactionUtil.SKIP_REMOVING_OUTPUT_FILE", path));
   }
 }
 @Override
 public Properties getLocalePropertiesForFile(
     final RepositoryFile repositoryFile, final String locale) {
   return callLogThrow(
       new Callable<Properties>() {
         public Properties call() throws Exception {
           return delegatee.getLocalePropertiesForFile(repositoryFile, locale);
         }
       },
       Messages.getInstance()
           .getString(
               "ExceptionLoggingDecorator.getLocalePropertiesForFile",
               repositoryFile.getId())); // $NON-NLS-1$
 }
 @Override
 public void deleteLocalePropertiesForFile(
     final RepositoryFile repositoryFile, final String locale) {
   callLogThrow(
       new Callable<Void>() {
         public Void call() throws Exception {
           delegatee.deleteLocalePropertiesForFile(repositoryFile, locale);
           return null;
         }
       },
       Messages.getInstance()
           .getString(
               "ExceptionLoggingDecorator.deleteLocalePropertiesForFile",
               repositoryFile.getId())); // $NON-NLS-1$
 }
  /**
   * Returns the Id of the parent folder of the file path provided
   *
   * @param repositoryPath
   * @return
   */
  protected Serializable getParentId(final String repositoryPath) {
    Assert.notNull(repositoryPath);
    Assert.notNull(parentIdCache);

    final String parentPath = RepositoryFilenameUtils.getFullPathNoEndSeparator(repositoryPath);
    Serializable parentFileId = parentIdCache.get(parentPath);
    if (parentFileId == null) {
      final RepositoryFile parentFile = repository.getFile(parentPath);
      Assert.notNull(parentFile);
      parentFileId = parentFile.getId();
      Assert.notNull(parentFileId);
      parentIdCache.put(parentPath, parentFileId);
    }
    return parentFileId;
  }
  public RepositoryFile getAnnotationsXmlFile(final RepositoryFile domainFile) {

    if (domainFile == null) {
      return null; // exit early
    }

    RepositoryFile annotationsFile = null;
    try {
      annotationsFile = getRepository().getFile(resolveAnnotationsFilePath(domainFile));
    } catch (Exception e) {
      getLogger().warn("Unable to find annotations xml file for: " + domainFile.getId());
    }

    return annotationsFile;
  }
 protected String toString(final RepositoryFile file) {
   try {
     final Map<String, Serializable> fileMetadata = repository.getFileMetadata(file.getId());
     return "[type="
         + fileMetadata.get(PROPERTY_NAME_TYPE)
         + " : domain="
         + fileMetadata.get(PROPERTY_NAME_DOMAIN_ID)
         + " : locale="
         + fileMetadata.get(PROPERTY_NAME_LOCALE)
         + " : filename="
         + file.getName()
         + "]";
   } catch (Throwable ignore) {
     // ignore
   }
   return "null";
 }
  @Test
  public void testFileCreator() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      // set object in PentahoSystem
      mp.defineInstance(IUnifiedRepository.class, repo);

      WebResource webResource = resource();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "file1.txt", "abcdefg");
      RepositoryFile file1 = repo.getFile(publicFolderPath + "/" + "file1.txt");
      RepositoryFileDto file2 = new RepositoryFileDto();
      file2.setId(file1.getId().toString());
      webResource.path("repo/files/public:file1.txt/creator").entity(file2).put();
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
      logout();
    }
  }
  /**
   * remove a domain from disk and memory.
   *
   * @param domainId
   */
  @Override
  public void removeDomain(final String domainId) {
    if (logger.isDebugEnabled()) {
      logger.debug("removeDomain(" + domainId + ")");
    }

    if (StringUtils.isEmpty(domainId)) {
      throw new IllegalArgumentException(
          messages.getErrorString(
              "PentahoMetadataDomainRepository.ERROR_0004_DOMAIN_ID_INVALID", domainId));
    }

    // Get the metadata domain file
    RepositoryFile domainFile;
    Set<RepositoryFile> domainFiles;
    lock.writeLock().lock();
    try {
      domainFiles = metadataMapping.getFiles(domainId);
      domainFile = metadataMapping.getDomainFile(domainId);
      metadataMapping.deleteDomain(domainId);
    } finally {
      lock.writeLock().unlock();
    }

    if (domainFile != null) {
      // it no node exists, nothing would happen
      getAclHelper().removeAclFor(domainFile);
    }

    for (final RepositoryFile file : domainFiles) {
      if (logger.isTraceEnabled()) {
        logger.trace("Deleting repository file " + toString(file));
      }
      repository.deleteFile(file.getId(), true, null);
    }

    // This invalidates any caching
    if (!domainFiles.isEmpty()) {
      flushDomains();
    }
  }
  @Override
  public String loadAnnotationsXml(final String domainId) {

    if (StringUtils.isBlank(domainId)) {
      return null; // exit early
    }

    try {
      final RepositoryFile domainFile = getMetadataRepositoryFile(domainId);
      final RepositoryFile annotationFile =
          getRepository().getFile(resolveAnnotationsFilePath(domainFile));

      // Load referenced annotations xml repo file
      SimpleRepositoryFileData data =
          getRepository().getDataForRead(annotationFile.getId(), SimpleRepositoryFileData.class);
      return IOUtils.toString(data.getInputStream()); // return as String
    } catch (Exception e) {
      getLogger().warn("Unable to load annotations xml file for domain: " + domainId);
    }

    return null;
  }
 protected Properties loadProperties(final RepositoryFile bundle) {
   try {
     Properties properties = null;
     final SimpleRepositoryFileData bundleData =
         repository.getDataForRead(bundle.getId(), SimpleRepositoryFileData.class);
     if (bundleData != null) {
       properties = new Properties();
       properties.load(bundleData.getStream());
     } else {
       if (logger.isWarnEnabled()) {
         logger.warn("Could not load properties from repository file: " + bundle.getName());
       }
     }
     return properties;
   } catch (IOException e) {
     throw new UnifiedRepositoryException(
         messages.getErrorString(
             "PentahoMetadataDomainRepository.ERROR_0008_ERROR_IN_REPOSITORY",
             e.getLocalizedMessage()),
         e);
   }
 }