@Before
  public void setUp() throws Exception {

    MicroPlatform microPlatform = new MicroPlatform();
    Mockery context = new Mockery();

    Map<String, String> mimeMap = new HashMap<String, String>();
    mimeMap.put("locale", "text/locale");
    microPlatform.defineInstance(NameBaseMimeResolver.class, new NameBaseMimeResolver(mimeMap));

    IPlatformImportMimeResolver nameBaseMimeResolver =
        context.mock(IPlatformImportMimeResolver.class);
    microPlatform.defineInstance(IPlatformImportMimeResolver.class, nameBaseMimeResolver);

    List<String> allowedArtifacts = new ArrayList<String>();
    allowedArtifacts.add("xaction");
    allowedArtifacts.add("url");
    LocaleImportHandler localeImportHandler = new LocaleImportHandler(allowedArtifacts);

    Map<String, IPlatformImportHandler> handlers = new HashMap<String, IPlatformImportHandler>();
    handlers.put("text/locale", localeImportHandler);

    Map<String, String> mimes = new HashMap<String, String>();
    mimes.put("locale", "text/locale");
    importer = new PentahoPlatformImporter(handlers, new NameBaseMimeResolver(mimes));
    importer.setRepositoryImportLogger(new Log4JRepositoryImportLogger());
  }
  @SuppressWarnings("deprecation")
  @Test(expected = PlatformPluginRegistrationException.class)
  public void testLoad_BadSolutionPath() throws PlatformPluginRegistrationException {
    MicroPlatform mp = new MicroPlatform("plugin-mgr/test-res/SystemPathPluginProviderTest/system");
    mp.define(ISolutionEngine.class, SolutionEngine.class);
    mp.define(ISolutionRepository.class, FileBasedSolutionRepository.class);
    mp.init();

    provider.getPlugins(new StandaloneSession());
  }
  @Before
  public void setUp() throws Exception {

    manager = new MockBackingRepositoryLifecycleManager(new MockSecurityHelper());
    repo = context.mock(IUnifiedRepository.class);

    booter = new MicroPlatform("test-res/solution1");
    booter.define(IPasswordService.class, Base64PasswordService.class, Scope.GLOBAL);
    booter.define(IDatabaseConnection.class, DatabaseConnection.class, Scope.GLOBAL);
    booter.define(IDatabaseDialectService.class, DatabaseDialectService.class, Scope.GLOBAL);
    booter.define(IMondrianCatalogService.class, MondrianCatalogHelper.class, Scope.GLOBAL);
    booter.define(ICacheManager.class, CacheManager.class, Scope.GLOBAL);
    booter.defineInstance(IUserRoleListService.class, context.mock(IUserRoleListService.class));
    final IAuthorizationPolicy policy = context.mock(IAuthorizationPolicy.class);
    booter.defineInstance(IAuthorizationPolicy.class, policy);
    booter.defineInstance(IUnifiedRepository.class, repo);
    booter.setSettingsProvider(new SystemSettings());
    booter.start();

    context.checking(
        new Expectations() {
          {
            oneOf(policy);
            will(returnValue(false));
            oneOf(policy);
            will(returnValue(false));
            oneOf(policy);
            will(returnValue(false));
          }
        });

    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
  }
  /** @throws java.lang.Exception */
  @SuppressWarnings("deprecation")
  @Before
  public void setUp() throws Exception {

    String solutionsRelativePath = "test-src/org/pentaho/test/platform/plugin/chartbeans/solutions";
    MicroPlatform mp = new MicroPlatform(solutionsRelativePath);
    mp.define(ISolutionEngine.class, Object.class);
    ISystemSettings settings = new XmlSimpleSystemSettings();
    mp.setSettingsProvider(settings);
    mp.init();
  }
  @Before
  public void init0() {
    microPlatform = new MicroPlatform("test-src/solution");
    microPlatform.define(ISolutionEngine.class, SolutionEngine.class);
    microPlatform.define(
        IUnifiedRepository.class, FileSystemBackedUnifiedRepository.class, Scope.GLOBAL);
    microPlatform.define(IMondrianCatalogService.class, MondrianCatalogHelper.class, Scope.GLOBAL);
    microPlatform.define("connection-SQL", SQLConnection.class);
    microPlatform.define("connection-MDX", MDXConnection.class);
    microPlatform.define(IDBDatasourceService.class, JndiDatasourceService.class, Scope.GLOBAL);
    microPlatform.define(IUserRoleListService.class, TestUserRoleListService.class, Scope.GLOBAL);
    microPlatform.define(UserDetailsService.class, TestUserDetailsService.class, Scope.GLOBAL);
    FileSystemBackedUnifiedRepository repo =
        (FileSystemBackedUnifiedRepository) PentahoSystem.get(IUnifiedRepository.class);
    repo.setRootDir(new File("test-src/solution"));
    try {
      microPlatform.start();
    } catch (PlatformInitializationException ex) {
      Assert.fail();
    }

    MondrianCatalogHelper catalogService =
        (MondrianCatalogHelper) PentahoSystem.get(IMondrianCatalogService.class);
    catalogService.setDataSourcesConfig(
        "file:"
            + PentahoSystem.getApplicationContext()
                .getSolutionPath("test/analysis/test-datasources.xml"));

    // JNDI
    System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory");
    System.setProperty("org.osjava.sj.root", "test-src/solution/system/simple-jndi");
    System.setProperty("org.osjava.sj.delimiter", "/");
  }
  @Before
  public void init() {
    microPlatform = new MicroPlatform("plugin-mgr/test-res/SystemPathPluginProviderTest/");
    microPlatform.define(ISolutionEngine.class, SolutionEngine.class);

    provider = new SystemPathXmlPluginProvider();
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testLoad_Good() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();

    PluginMessageLogger.clear();

    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    // should successfully load good-plugin1 and good-plugin2 and not load bad-plugin.  The fact
    // that bad-plugin does not load should not prevent the good ones from being loaded
    assertTrue(
        "plugin1 was not found",
        CollectionUtils.exists(plugins, new PluginNameMatcherPredicate("Plugin 1")));
    assertTrue(
        "plugin2 was not found",
        CollectionUtils.exists(plugins, new PluginNameMatcherPredicate("Plugin 2")));

    // make sure that the bad plugin caused an error message to be logged
    assertEquals(
        "bad plugin did not log an error message",
        1,
        PluginMessageLogger.count("SystemPathXmlPluginProvider.ERROR_0001"));

    for (String msg : PluginMessageLogger.getAll()) {
      System.err.println(msg);
    }
  }
  @Test
  public void testWriteBinaryFile() throws InterruptedException {
    final String str = "some binary text";
    final String fileName = "file.bn";

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

    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, authenticatedAuthorityName});
    try {
      login(sysAdminUserName, systemTenant, new String[] {adminAuthorityName});
      login("admin", mainTenant_1, new String[] {adminAuthorityName, authenticatedAuthorityName});

      WebResource webResource = resource();
      final byte[] blob = str.getBytes();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFileBinary(publicFolderPath.replaceAll("/", ":") + ":" + fileName, blob);

      // the file might not actually be ready.. wait a second
      Thread.sleep(20000);

      ClientResponse response =
          webResource
              .path("repo/files/:public:file.bn")
              .accept(APPLICATION_OCTET_STREAM)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, APPLICATION_OCTET_STREAM);

      byte[] data = response.getEntity(byte[].class);
      assertEquals("contents of file incorrect/missing", str, new String(data));
    } catch (Exception ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @SuppressWarnings("deprecation")
  @Test(expected = PlatformPluginRegistrationException.class)
  public void testLoad_NoSolutionRepo() throws PlatformPluginRegistrationException {
    microPlatform.init();

    provider.getPlugins(new StandaloneSession());
  }
  @SuppressWarnings("deprecation")
  @Test
  public void tesLoadtLifecycleListener() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();

    PluginMessageLogger.clear();

    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    // first make sure Plugin 1 was loaded, otherwise our check for lifcycle class will never happen
    assertTrue(
        "plugin1 was not found",
        CollectionUtils.exists(plugins, new PluginNameMatcherPredicate("Plugin 1")));

    for (IPlatformPlugin plugin : plugins) {
      if (plugin.getId().equals("Plugin 1")) {
        assertEquals(
            "org.pentaho.test.platform.plugin.pluginmgr.FooInitializer",
            plugin.getLifecycleListenerClassname());
      }
      if (plugin.getId().equals("Plugin 2")) {
        // no listener defined to for Plugin 2
        assertNull(plugin.getLifecycleListenerClassname());
      }
    }
  }
  @Ignore
  public void testGetFileText() throws Exception {
    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});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "file.txt", "abcdefg");

    WebResource webResource = resource();

    ClientResponse r1 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .get(ClientResponse.class);
    assertResponse(r1, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r1.getEntity(String.class));

    // check again but with no Accept header
    ClientResponse r2 =
        webResource.path("repos/:public:file.txt/content").get(ClientResponse.class);
    assertResponse(r2, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r2.getEntity(String.class));

    // check again but with */*
    ClientResponse r3 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .accept(MediaType.WILDCARD)
            .get(ClientResponse.class);
    assertResponse(r3, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r3.getEntity(String.class));

    cleanupUserAndRoles(mainTenant_1);
    cleanupUserAndRoles(systemTenant);
  }
  @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);
    }
  }
  @Test
  public void testWriteTextFile() throws Exception {
    final String text = "sometext";

    mp.defineInstance(IUnifiedRepository.class, repo);
    final String fileName = "file.txt";

    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(
          sysAdminUserName,
          systemTenant,
          new String[] {adminAuthorityName, authenticatedAuthorityName});

      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      WebResource webResource = resource();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + fileName, text);

      ClientResponse response =
          webResource
              .path("repo/files/:public:" + fileName)
              .accept(TEXT_PLAIN)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, TEXT_PLAIN);
      assertEquals("contents of file incorrect/missing", text, response.getEntity(String.class));

    } catch (Throwable th) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
 private static PentahoMetadataDomainRepository createMetadataDomainRepository() throws Exception {
   IUnifiedRepository repository = new FileSystemBackedUnifiedRepository("test-res/dsw");
   mp.defineInstance(IUnifiedRepository.class, repository);
   Assert.assertNotNull(
       new RepositoryUtils(repository).getFolder("/etc/metadata", true, true, null));
   Assert.assertNotNull(
       new RepositoryUtils(repository).getFolder("/etc/mondrian", true, true, null));
   PentahoMetadataDomainRepository pentahoMetadataDomainRepository =
       new PentahoMetadataDomainRepository(repository);
   return pentahoMetadataDomainRepository;
 }
  @Test
  public void testPublishDsw() throws Exception {
    DatasourceResource service = new DatasourceResource();
    Mockery mockery = new Mockery();
    final IPlatformImporter mockImporter = mockery.mock(IPlatformImporter.class);
    mp.defineInstance(IPlatformImporter.class, mockImporter);
    mockery.checking(
        new Expectations() {
          {
            oneOf(mockImporter)
                .importFile(
                    with(
                        match(
                            new TypeSafeMatcher<IPlatformImportBundle>() {
                              public boolean matchesSafely(IPlatformImportBundle bundle) {
                                return bundle.isPreserveDsw()
                                    && bundle.getProperty("domain-id").equals("AModel.xmi")
                                    && bundle.getMimeType().equals("text/xmi+xml");
                              }

                              public void describeTo(Description description) {
                                description.appendText("bundle with xmi");
                              }
                            })));
            oneOf(mockImporter)
                .importFile(
                    with(
                        match(
                            new TypeSafeMatcher<IPlatformImportBundle>() {
                              public boolean matchesSafely(IPlatformImportBundle bundle) {
                                return bundle.getProperty("domain-id").equals("AModel")
                                    && bundle
                                        .getMimeType()
                                        .equals("application/vnd.pentaho.mondrian+xml");
                              }

                              public void describeTo(Description description) {
                                description.appendText("bundle with mondrian schema");
                              }
                            })));
          }
        });
    FileInputStream in = new FileInputStream(new File(new File("test-res"), "SampleDataOlap.xmi"));
    try {
      Response resp = service.publishDsw("AModel.xmi", in, true, false);
      Assert.assertEquals(
          Response.Status.Family.SUCCESSFUL,
          Response.Status.fromStatusCode(resp.getStatus()).getFamily());
      mockery.assertIsSatisfied();
    } finally {
      IOUtils.closeQuietly(in);
    }
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testLoadContentGenerators() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();
    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    IPlatformPlugin plugin =
        (IPlatformPlugin)
            CollectionUtils.find(
                plugins, new PluginNameMatcherPredicate("content-generator-plugin"));
    assertNotNull("content-generator-plugin should have been found", plugin);

    List<IContentInfo> contentTypes = plugin.getContentInfos();

    Object contentType =
        CollectionUtils.find(
            contentTypes,
            new Predicate() {
              public boolean evaluate(Object object) {
                IContentInfo type = (IContentInfo) object;
                return type.getTitle().equals("Good Test Type");
              }
            });
    assertNotNull("\"Good Test Type\" should have been loaded", contentType);
    assertNotNull(
        "\"Good Test Type\" extension definition is incorrect",
        ((IContentInfo) contentType).getExtension().equals("good-content-type"));

    assertEquals(
        "\"Test Type Missing type\" should not have been loaded",
        0,
        CollectionUtils.countMatches(
            contentTypes,
            new Predicate() {
              public boolean evaluate(Object object) {
                IContentInfo contentType = (IContentInfo) object;
                return contentType.getTitle().equals("Test Type Missing type");
              }
            }));

    assertEquals(
        "\"test-type-missing-title\" should not have been loaded",
        0,
        CollectionUtils.countMatches(
            contentTypes,
            new Predicate() {
              public boolean evaluate(Object object) {
                IContentInfo contentType = (IContentInfo) object;
                return contentType.getExtension().equals("test-type-missing-title");
              }
            }));
  }
  @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);
    }
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testLoadLifeCycleListener() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();
    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    IPlatformPlugin plugin =
        (IPlatformPlugin) CollectionUtils.find(plugins, new PluginNameMatcherPredicate("Plugin 1"));
    assertNotNull("Plugin 1 should have been found", plugin);

    assertEquals(
        "org.pentaho.test.platform.plugin.pluginmgr.FooInitializer",
        plugin.getLifecycleListenerClassname());
  }
  @Test
  public void testGetWhenFileDNE() {
    mp.defineInstance(IUnifiedRepository.class, repo);
    loginAsRepositoryAdmin();

    WebResource webResource = resource();
    try {
      webResource
          .path("repo/files/public:thisfiledoesnotexist.txt")
          .accept(TEXT_PLAIN)
          .get(ClientResponse.class);
    } catch (UnifiedRepositoryException ure) {
      assertNotNull(ure);
    }
  }
  @Ignore
  public void a2_HappyPath() {
    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});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "js/test.js", "js content");
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.css", "css content");

    WebResource webResource = resource();

    // load the css
    ClientResponse response =
        webResource.path("repos/:public:test.xjunit/test.css").get(ClientResponse.class);
    assertResponse(response, ClientResponse.Status.OK, "text/css");
    assertEquals(
        "contents of file incorrect/missing", "css content", response.getEntity(String.class));

    // load the js
    response = webResource.path("repos/:public:test.xjunit/js/test.js").get(ClientResponse.class);
    assertResponse(response, ClientResponse.Status.OK, "text/javascript");
    assertEquals(
        "contents of file incorrect/missing", "js content", response.getEntity(String.class));
  }
  // We should be testing the underlying class functionality in unit tests
  @Test
  public void testGetDirChildren() {
    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);
      final String fileName = "file.txt";
      createTestFile("/public".replaceAll("/", ":") + ":" + fileName, "abcdefg");
      WebResource webResource = resource();
      ClientResponse response =
          webResource
              .path("repo/files/public/children")
              .accept(APPLICATION_XML)
              .get(ClientResponse.class);

      assertResponse(response, Status.OK, APPLICATION_XML);

      String xml = response.getEntity(String.class);
      assertTrue(xml.startsWith("<?"));
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Ignore
  public void a3_HappyPath_POST() {
    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});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");

    WebResource webResource = resource();

    // get the output of the .junit file (should invoke the content generator)
    MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
    formData.add("testParam", "testParamValue");

    ClientResponse response =
        webResource
            .path("repos/:public:test.xjunit/viewer")
            .type(APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, formData);
    assertResponse(response, Status.OK);
    assertEquals(
        "Content generator failed to provide correct output",
        "hello viewer content generator",
        response.getEntity(String.class));
  }
  @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();
    }
  }
  @Before
  public void setUp() throws Exception {
    mp = new MicroPlatform();
    // used by DefaultPentahoJackrabbitAccessControlHelper
    mp.defineInstance("tenantedUserNameUtils", tenantedUserNameUtils);
    mp.defineInstance("tenantedRoleNameUtils", tenantedRoleNameUtils);
    mp.defineInstance(IAuthorizationPolicy.class, authorizationPolicy);
    mp.defineInstance(ITenantManager.class, tenantManager);
    mp.define(ITenant.class, Tenant.class);
    mp.defineInstance(
        "roleAuthorizationPolicyRoleBindingDaoTarget", roleAuthorizationPolicyRoleBindingDao);
    mp.defineInstance("repositoryAdminUsername", repositoryAdminUsername);

    // Start the micro-platform
    mp.start();
    logout();
    startupCalled = true;
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testLoadBeanDefinition() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();

    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    IPlatformPlugin plugin =
        (IPlatformPlugin) CollectionUtils.find(plugins, new PluginNameMatcherPredicate("Plugin 1"));
    assertNotNull("Plugin 1 should have been found", plugin);

    Collection<PluginBeanDefinition> beans = plugin.getBeans();

    assertEquals(
        "FooComponent was not loaded",
        1,
        CollectionUtils.countMatches(
            beans,
            new Predicate() {
              public boolean evaluate(Object object) {
                PluginBeanDefinition bean = (PluginBeanDefinition) object;
                return bean.getBeanId().equals("FooComponent")
                    && bean.getClassname()
                        .equals("org.pentaho.test.platform.plugin.pluginmgr.FooComponent");
              }
            }));
    assertEquals(
        "genericBean was not loaded",
        1,
        CollectionUtils.countMatches(
            beans,
            new Predicate() {
              public boolean evaluate(Object object) {
                PluginBeanDefinition bean = (PluginBeanDefinition) object;
                return bean.getBeanId().equals("genericBean")
                    && bean.getClassname().equals("java.lang.Object");
              }
            }));
  }
  @Ignore
  public void a3_dotUrl() {
    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});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    final String text = "URL=http://google.com";
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.url", text);

    WebResource webResource = resource();

    String response = webResource.path("repos/:public:test.url/content").get(String.class);
    assertEquals("contents of file incorrect/missing", text, response);

    ClientResponse getResponse =
        webResource.path("repos/:public:test.url/generatedContent").get(ClientResponse.class);
    assertEquals(ClientResponse.Status.OK, getResponse.getClientResponseStatus());
  }
  @Ignore
  public void a3_HappyPath_GET() {
    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});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");

    WebResource webResource = resource();

    // get the output of the .xjunit file (should invoke the content generator)
    String textResponse = webResource.path("repos/:public:test.xjunit/viewer").get(String.class);
    assertEquals(
        "Content generator failed to provide correct output",
        "hello viewer content generator",
        textResponse);
  }
  @SuppressWarnings("deprecation")
  @Test
  public void testLoadWebservices() throws PlatformPluginRegistrationException {
    microPlatform.define(ISolutionRepository.class, FileBasedSolutionRepository.class).init();
    List<IPlatformPlugin> plugins = provider.getPlugins(new StandaloneSession());

    System.out.println(PluginMessageLogger.getAll());

    IPlatformPlugin plugin =
        (IPlatformPlugin) CollectionUtils.find(plugins, new PluginNameMatcherPredicate("Plugin 1"));
    assertNotNull("Plugin 1 should have been found", plugin);

    Collection<PluginServiceDefinition> webservices = plugin.getServices();

    Object wsobj =
        CollectionUtils.find(
            webservices,
            new Predicate() {
              public boolean evaluate(Object object) {
                PluginServiceDefinition ws = (PluginServiceDefinition) object;
                boolean ret = ws.getTitle().equals("%TestWS1.TITLE%");
                return ret;
              }
            });

    assertNotNull("Webservice \"%TestWS1.TITLE%\" should have been loaded", wsobj);

    PluginServiceDefinition wsDfn = (PluginServiceDefinition) wsobj;

    assertEquals("org.pentaho.test.platform.engine.core.EchoServiceBean", wsDfn.getServiceClass());
    assertEquals("xml", wsDfn.getTypes()[0]);
    assertEquals("gwt", wsDfn.getTypes()[1]);
    assertEquals("A test webservice", wsDfn.getDescription());
    assertEquals(1, wsDfn.getExtraClasses().size());
    assertEquals("java.lang.String", wsDfn.getExtraClasses().iterator().next());
  }
  @Test
  public void testFileAcls() throws InterruptedException {
    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});
      mp.defineInstance(IUnifiedRepository.class, repo);

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "aclFile.txt", "abcdefg");

      WebResource webResource = resource();
      RepositoryFileAclDto fileAcls =
          webResource
              .path("repo/files/public:aclFile.txt/acl")
              .accept(APPLICATION_XML)
              .get(RepositoryFileAclDto.class);
      List<RepositoryFileAclAceDto> aces = fileAcls.getAces();
      assertEquals(2, aces.size());
      RepositoryFileAclAceDto ace = aces.get(0);
      assertEquals(authenticatedAuthorityName, ace.getRecipient());
      List<Integer> permissions = ace.getPermissions();
      assertEquals(1, permissions.size());
      Assert.assertTrue(permissions.contains(new Integer(0)));

      String authenticated = authenticatedAuthorityName;

      aces = new ArrayList<RepositoryFileAclAceDto>();
      ace = new RepositoryFileAclAceDto();
      ace.setRecipient(authenticated);
      ace.setRecipientType(1);
      permissions = new ArrayList<Integer>();
      permissions.add(2);
      ace.setPermissions(permissions);
      aces.add(ace);
      fileAcls.setAces(aces);

      ClientResponse putResponse2 =
          webResource
              .path("repo/files/public:aclFile.txt/acl")
              .type(APPLICATION_XML)
              .put(ClientResponse.class, fileAcls);
      assertResponse(putResponse2, Status.OK);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  // This is testing the Rest end points, we should instead be testing the underlying functionality
  // in unit tests
  @Test
  public void testBrowserDownload() {
    final String text = "abcdefg";

    // mock converters map
    StreamConverter streamConverter = new StreamConverter(repo);
    Map<String, Converter> converterMap = new HashMap<String, Converter>();
    converterMap.put("txt", streamConverter);

    // stub DefaultExportProcessor
    DefaultExportHandler defaultExportHandler = new DefaultExportHandler();
    defaultExportHandler.setConverters(converterMap);
    defaultExportHandler.setRepository(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});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName, adminAuthorityName});

      mp.defineInstance(IUnifiedRepository.class, repo);
      mp.defineInstance(DefaultExportHandler.class, defaultExportHandler);

      final String fileName = "file.txt";
      createTestFile("/public".replaceAll("/", ":") + ":" + fileName, text);

      // test download of file
      WebResource webResource = resource();
      webResource.path("repo/files/public:file.txt/download").get(ClientResponse.class);

      // test download of dir as a zip file
      ClientResponse r2 =
          webResource.path("repo/files/public:file.txt/download").get(ClientResponse.class);
      assertResponse(r2, Status.OK);
      JerseyTestUtil.assertResponseIsZip(r2);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }