@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);
  }
 public void setUp() throws Exception {
   IUnifiedRepository repository =
       new MockUnifiedRepository(new MockUnifiedRepository.SpringSecurityCurrentUserProvider());
   datasourceMgmtService =
       new JcrBackedDatasourceMgmtService(repository, new DatabaseDialectService());
   datasourceMgmtWebService = new DefaultDatasourceMgmtWebService(datasourceMgmtService);
   dbConnectionAdapter = new DatabaseConnectionAdapter();
   SecurityContextHolder.getContext()
       .setAuthentication(
           new UsernamePasswordAuthenticationToken(
               MockUnifiedRepository.root().getName(), null, new GrantedAuthority[0]));
   repository.createFolder(
       repository.getFile("/etc").getId(),
       new RepositoryFile.Builder(FOLDER_PDI).folder(true).build(),
       new RepositoryFileAcl.Builder(MockUnifiedRepository.root())
           .ace(MockUnifiedRepository.everyone(), READ, READ_ACL, WRITE, WRITE_ACL)
           .build(),
       null);
   repository.createFolder(
       repository.getFile("/etc/pdi").getId(),
       new RepositoryFile.Builder(FOLDER_DATABASES).folder(true).build(),
       null);
   SecurityContextHolder.getContext()
       .setAuthentication(
           new UsernamePasswordAuthenticationToken(EXP_LOGIN, null, new GrantedAuthority[0]));
 }
  /**
   * 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;
  }
  public static MasterReport createReport(final Serializable fileId)
      throws ResourceException, IOException {
    final ResourceManager resourceManager = new ResourceManager();
    resourceManager.registerDefaults();
    final HashMap helperObjects = new HashMap();
    // add the runtime context so that PentahoResourceData class can get access
    // to the solution repo

    ResourceKey key = null;

    IUnifiedRepository unifiedRepository =
        PentahoSystem.get(IUnifiedRepository.class, PentahoSessionHolder.getSession());
    RepositoryFile repositoryFile = unifiedRepository.getFileById(fileId);
    if (repositoryFile != null) {
      key =
          resourceManager.createKey(
              RepositoryResourceLoader.SOLUTION_SCHEMA_NAME
                  + RepositoryResourceLoader.SCHEMA_SEPARATOR
                  + repositoryFile.getPath(),
              helperObjects);
    } else {
      key =
          resourceManager.createKey(
              RepositoryResourceLoader.SOLUTION_SCHEMA_NAME
                  + RepositoryResourceLoader.SCHEMA_SEPARATOR
                  + fileId,
              helperObjects);
    }

    final Resource resource = resourceManager.create(key, null, MasterReport.class);
    return (MasterReport) resource.getResource();
  }
 public InputStream getInputStream() throws Exception {
   IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class);
   RepositoryFile repositoryFile = repository.getFile(inputFilePath);
   if ((repositoryFile == null) || repositoryFile.isFolder()) {
     throw new FileNotFoundException();
   }
   return new RepositoryFileInputStream(repositoryFile);
 }
 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());
   }
 }
 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);
     }
   }
 }
  /** 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();
    }
  }
예제 #9
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));
   }
 }
  @Test
  public void testDoNewTenant() throws Exception {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1,
        "admin",
        "password",
        "",
        new String[] {adminAuthorityName, tenantAuthenticatedAuthorityName});
    login(
        "admin", mainTenant_1, new String[] {adminAuthorityName, tenantAuthenticatedAuthorityName});
    JcrRepositoryDumpToFile dumpToFile =
        new JcrRepositoryDumpToFile(
            testJcrTemplate,
            jcrTransactionTemplate,
            repositoryAdminUsername,
            "c:/build/testrepo_3",
            Mode.CUSTOM);
    dumpToFile.execute();
    metadataRepositoryLifecycleManager.newTenant(mainTenant_1);
    String metadataPath = ClientRepositoryPaths.getEtcFolderPath() + "/metadata";
    RepositoryFile metadataRepositoryPath = repo.getFile(metadataPath);
    assertTrue(metadataRepositoryPath.getPath() != null);

    // Nothing should change if we run it again
    metadataRepositoryLifecycleManager.newTenant(mainTenant_1);
    metadataPath = ClientRepositoryPaths.getEtcFolderPath() + "/metadata";
    metadataRepositoryPath = repo.getFile(metadataPath);
    assertTrue(metadataRepositoryPath.getPath() != null);
    cleanupUserAndRoles(mainTenant_1);
    cleanupUserAndRoles(systemTenant);
  }
  @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");
  }
  @Override
  public String[] getUserParameters(String kettleFilePath) {

    List<String> userParams = new ArrayList<String>();

    if (!StringUtils.isEmpty(kettleFilePath)) {

      RepositoryFile file = unifiedRepository.getFile(kettleFilePath);

      if (file != null) {

        try {

          NamedParams np = getMeta(file);

          if (!isEmpty(np = filterUserParameters(np))) {

            return np.listParameters();
          }

        } catch (KettleException e) {
          log.error(e);
        }
      }
    }

    return userParams.toArray(new String[] {});
  }
 public RepositoryFileDto updateFile(
     RepositoryFileDto file, NodeRepositoryFileDataDto data, String versionMessage) {
   return repositoryFileAdapter.marshal(
       repo.updateFile(
           repositoryFileAdapter.unmarshal(file),
           nodeRepositoryFileDataAdapter.unmarshal(data),
           versionMessage));
 }
 public List<VersionSummaryDto> getVersionSummaryInBatch(final List<RepositoryFileDto> files) {
   List<VersionSummaryDto> versions = new ArrayList<VersionSummaryDto>(files.size());
   for (RepositoryFileDto file : files) {
     versions.add(
         versionSummaryAdapter.marshal(repo.getVersionSummary(file.getId(), file.getVersionId())));
   }
   return versions;
 }
 public List<NodeRepositoryFileDataDto> getDataAsNodeForReadInBatch(
     final List<RepositoryFileDto> files) {
   List<NodeRepositoryFileDataDto> data = new ArrayList<NodeRepositoryFileDataDto>(files.size());
   for (RepositoryFileDto f : files) {
     if (f.getVersionId() == null) {
       data.add(
           nodeRepositoryFileDataAdapter.marshal(
               repo.getDataForRead(f.getId(), NodeRepositoryFileData.class)));
     } else {
       data.add(
           nodeRepositoryFileDataAdapter.marshal(
               repo.getDataAtVersionForRead(
                   f.getId(), f.getVersionId(), NodeRepositoryFileData.class)));
     }
   }
   return data;
 }
  public List<RepositoryFileDto> getReferrers(String fileId) {
    List<RepositoryFileDto> fileList = new ArrayList<RepositoryFileDto>();

    for (RepositoryFile file : repo.getReferrers(fileId)) {
      fileList.add(repositoryFileAdapter.marshal(file));
    }
    return fileList;
  }
 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.");
     }
   }
 }
 @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());
   }
 }
  /**
   * 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;
  }
 /**
  * lookup the list of available locale values
  *
  * @param fileId
  * @return
  */
 private List<LocaleMapDto> getAvailableLocales(Serializable fileId) {
   List<LocaleMapDto> availableLocales = new ArrayList<LocaleMapDto>();
   List<Locale> locales = unifiedRepository.getAvailableLocalesForFileById(fileId);
   if (locales != null && !locales.isEmpty()) {
     for (Locale locale : locales) {
       availableLocales.add(new LocaleMapDto(locale.toString(), null));
     }
   }
   return availableLocales;
 }
 @Override
 public List<StringKeyStringValueDto> getFileMetadata(final String fileId) {
   final Map<String, Serializable> metadataMap = repo.getFileMetadata(fileId);
   final List<StringKeyStringValueDto> fileMetadataMap =
       new ArrayList<StringKeyStringValueDto>(metadataMap.size());
   for (final String key : metadataMap.keySet()) {
     fileMetadataMap.add(new StringKeyStringValueDto(key, metadataMap.get(key).toString()));
   }
   return fileMetadataMap;
 }
 @Override
 public void setFileMetadata(
     final String fileId, final List<StringKeyStringValueDto> fileMetadataMap) {
   Map<String, Serializable> metadataMap =
       new HashMap<String, Serializable>(fileMetadataMap.size());
   for (final StringKeyStringValueDto dto : fileMetadataMap) {
     metadataMap.put(dto.getKey(), dto.getValue());
   }
   repo.setFileMetadata(fileId, metadataMap);
 }
  @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);
    }
  }
 private boolean isValidOutputPath(String path) {
   try {
     RepositoryFile repoFile = repository.getFile(path);
     if (repoFile != null && repoFile.isFolder()) {
       return true;
     }
   } catch (Exception e) {
     logger.warn(e.getMessage(), e);
   }
   return false;
 }
 /**
  * Creates a new file in the repository
  *
  * @param bundle
  * @param destinationPath
  * @param bundlePath
  * @param ext
  * @param data
  * @param comment
  */
 protected RepositoryFile createFile(
     final ImportSource.IRepositoryFileBundle bundle,
     final String destinationPath,
     final boolean hidden,
     final IRepositoryFileData data,
     final String comment) {
   final RepositoryFile file =
       new RepositoryFile.Builder(bundle.getFile())
           .hidden(hidden)
           .title(RepositoryFile.DEFAULT_LOCALE, getTitle(bundle.getFile().getName()))
           .versioned(true)
           .build();
   final Serializable parentId = getParentId(destinationPath);
   final RepositoryFileAcl acl = bundle.getAcl();
   if (null == acl) {
     return repository.createFile(parentId, file, data, comment);
   } else {
     return repository.createFile(parentId, file, data, acl, comment);
   }
 }
 /**
  * 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());
     }
   }
 }
 @Override
 public List<PentahoLocale> getAvailableLocalesForFileById(String fileId) {
   List<PentahoLocale> pentahoLocales = new ArrayList<PentahoLocale>();
   List<Locale> locales = repo.getAvailableLocalesForFileById(fileId);
   if (locales != null && !locales.isEmpty()) {
     for (Locale locale : locales) {
       pentahoLocales.add(new PentahoLocale(locale));
     }
   }
   return pentahoLocales;
 }
 public RepositoryFileDto createFolderWithAcl(
     String parentFolderId,
     RepositoryFileDto file,
     RepositoryFileAclDto acl,
     String versionMessage) {
   RepositoryFile newFile =
       repo.createFolder(
           parentFolderId,
           repositoryFileAdapter.unmarshal(file),
           repositoryFileAclAdapter.unmarshal(acl),
           versionMessage);
   return newFile != null ? repositoryFileAdapter.marshal(newFile) : null;
 }
 public RepositoryFileDto createFile(
     String parentFolderId,
     RepositoryFileDto file,
     NodeRepositoryFileDataDto data,
     String versionMessage) {
   validateEtcWriteAccess(parentFolderId);
   return repositoryFileAdapter.marshal(
       repo.createFile(
           parentFolderId,
           repositoryFileAdapter.unmarshal(file),
           nodeRepositoryFileDataAdapter.unmarshal(data),
           versionMessage));
 }
  @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);
    }
  }