/**
   * Returns an internal folder to store all files deleted from a given folder. Provides fast access
   * when searching for files deleted from a given folder.
   */
  private Node legacyGetTrashFolderIdNode(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final String origParentFolderPath)
      throws RepositoryException {

    // get folder id
    String folderId = null;
    if (session.itemExists(origParentFolderPath)) {
      folderId = ((Node) session.getItem(origParentFolderPath)).getIdentifier();
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString("DefaultDeleteHelper.ERROR_0001_PATH_NOT_FOUND")); // $NON-NLS-1$
    }

    final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":";
    Node trashInternalFolderNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants);
    if (NodeHelper.hasNode(trashInternalFolderNode, prefix, folderId)) {
      return NodeHelper.getNode(trashInternalFolderNode, prefix, folderId);
    } else {
      // if Trash Structure 1 (legacy) doesn't exist, no need to create it now
      return null;
    }
  }
 /** Tests that Session.getNamespacePrefix returns the session scoped mapping. */
 public void testGetNamespacePrefix() throws RepositoryException {
   String testPrefix = getUnusedPrefix();
   // remap the jcr uri
   session.setNamespacePrefix(testPrefix, NS_JCR_URI);
   String prefix = session.getNamespacePrefix(NS_JCR_URI);
   assertEquals(
       "Session.getNamespacePrefix does not return the correct value.", testPrefix, prefix);
 }
  public void setRoleBindings(
      Session session, ITenant tenant, String runtimeRoleName, List<String> logicalRoleNames)
      throws NamespaceException, RepositoryException {
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(runtimeRoleName, false);
      runtimeRoleName = getPrincipalName(runtimeRoleName);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      throw new NotFoundException("Tenant " + tenant.getId() + " not found");
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    int i = 0;
    while (runtimeRoleNodes.hasNext()) {
      runtimeRoleNodes.nextNode();
      i++;
    }
    if (i == 0) {
      // no bindings setup yet; install bootstrap bindings; bootstrapRoleBindings will now no longer
      // be
      // consulted
      for (Map.Entry<String, List<String>> entry : bootstrapRoleBindings.entrySet()) {
        JcrRoleAuthorizationPolicyUtils.internalSetBindings(
            pentahoJcrConstants,
            runtimeRolesFolderNode,
            entry.getKey(),
            entry.getValue(),
            phoNsPrefix);
      }
    }
    if (!isImmutable(runtimeRoleName)) {
      JcrRoleAuthorizationPolicyUtils.internalSetBindings(
          pentahoJcrConstants,
          runtimeRolesFolderNode,
          runtimeRoleName,
          logicalRoleNames,
          phoNsPrefix);
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString(
                  "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0001_ATTEMPT_MOD_IMMUTABLE",
                  runtimeRoleName)); //$NON-NLS-1$
    }
    session.save();
    Assert.isTrue(NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName));

    // update cache
    String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
    cacheManager.putInRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId, logicalRoleNames);
  }
  /**
   * Test case for the scope of the local namespace mappings as specified in section 3.5.2
   * Session-Local Mappings:
   *
   * <blockquote>
   *
   * The resulting mapping table applies only within the scope of that session
   *
   * </blockquote>
   *
   * <p>Also specified in the javadoc of {@link Session#setNamespacePrefix(String, String)}:
   *
   * <blockquote>
   *
   * The remapping only affects operations done through this <code>Session</code>. To clear all
   * remappings, the client must acquire a new <code>Session</code>.
   *
   * </blockquote>
   */
  public void testScopeOfLocalNamepaceMappings() throws RepositoryException {
    String before = session.getNamespacePrefix(NS_JCR_URI);
    String after = before + "-changed";

    // Change the prefix of a well-known namespace
    session.setNamespacePrefix(after, NS_JCR_URI);
    assertEquals(after, session.getNamespacePrefix(NS_JCR_URI));

    // Check whether the mapping affects another session
    Session another = getHelper().getReadOnlySession();
    try {
      assertEquals(
          "Local namespace changes must not affect other sessions",
          before,
          another.getNamespacePrefix(NS_JCR_URI));
    } finally {
      another.logout();
    }
  }
 /**
  * Test case for the initial set of local namespace mappings as specified in section 3.5.2
  * Session-Local Mappings:
  *
  * <blockquote>
  *
  * When a new session is acquired, the mappings present in the persistent namespace registry are
  * copied to the local namespace mappings of that session.
  *
  * </blockquote>
  */
 public void testInitialLocalNamespaceMappings() throws RepositoryException {
   String[] uris = nsr.getURIs();
   for (int i = 0; i < uris.length; i++) {
     assertEquals(
         "The initial local namespace prefix of \""
             + uris[i]
             + "\" must match the persistent registry mapping",
         nsr.getPrefix(uris[i]),
         session.getNamespacePrefix(uris[i]));
   }
 }
  /**
   * Test case for the unknown prefix behaviour specified in section 3.5.2 Session-Local Mappings:
   *
   * <blockquote>
   *
   * If a JCR method is passed a name or path containing a prefix which does not exist in the local
   * mapping an exception is thrown.
   *
   * </blockquote>
   */
  public void testExceptionOnUnknownPrefix() throws RepositoryException {
    // Change the local prefix of of NS_JCR_URI
    // NOTE: JCR 1.0 repositories will throw an exception on this
    String before = session.getNamespacePrefix(NS_JCR_URI);
    String after = before + "-changed";
    session.setNamespacePrefix(after, NS_JCR_URI);

    // Try to use the changed prefix
    try {
      session.propertyExists("/" + before + ":primaryType");
      fail("A path with an unknown prefix must cause" + " an exception to be thrown");
    } catch (RepositoryException expected) {
    }
  }
  /**
   * Test case for the automatic generation of a new local prefix for a registered namespace URI
   * that doesn't have a local mapping, as specified in section 3.5.2 Session-Local Mappings:
   *
   * <blockquote>
   *
   * If a JCR method returns a name from the repository with a namespace URI for which no local
   * mapping exists, a prefix is created automatically and a mapping between that prefix and the
   * namespace URI in question is added to the set of local mappings. The new prefix must differ
   * from those already present among the set of local mappings.
   *
   * </blockquote>
   */
  public void testAutomaticNewLocalPrefix() throws RepositoryException {
    Set prefixes = new HashSet(Arrays.asList(session.getNamespacePrefixes()));
    prefixes.remove(session.getNamespacePrefix(NS_JCR_URI));
    prefixes.remove(session.getNamespacePrefix(NS_NT_URI));

    // Remove the local mapping of NS_JCR_URI
    // NOTE: JCR 1.0 repositories will throw an exception on this
    String before = session.getNamespacePrefix(NS_JCR_URI);
    session.setNamespacePrefix(before, NS_NT_URI);

    // Have the repository come up with a new prefix for this namespace
    String name = session.getProperty("/{" + NS_JCR_URI + "}primaryType").getName();
    int colon = name.indexOf(':');
    String after = name.substring(0, colon);

    assertFalse(
        "Automatically created new local prefix of a namespace"
            + " must be different from the prefix that removed the mapping",
        after.equals(before));

    assertFalse(
        "Automatically created new local prefix of a namespace"
            + " must be different from those already present",
        prefixes.contains(after));

    try {
      assertEquals(
          "The local namespace mappings must match the"
              + " automatically created new prefix of a namespace",
          after,
          session.getNamespacePrefix(NS_JCR_URI));
    } catch (NamespaceException e) {
      fail(
          "Automatically created new prefix must be included in"
              + " the set of local namespace mappings");
    }
  }
 /**
  * Creates and/or returns an internal folder to store a single deleted file. This folder is
  * uniquely named and thus prevents same-name sibling conflicts.
  *
  * @param fileId id of file to delete
  */
 private Node getOrCreateTrashFileIdNode(
     final Session session,
     final PentahoJcrConstants pentahoJcrConstants,
     final Serializable fileId)
     throws RepositoryException {
   final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":";
   final String folderName = fileId.toString(); // $NON-NLS-1$
   Node trashInternalFolderNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants);
   if (NodeHelper.hasNode(trashInternalFolderNode, prefix, folderName)) {
     return NodeHelper.getNode(trashInternalFolderNode, prefix, folderName);
   } else {
     return trashInternalFolderNode.addNode(
         prefix + folderName, pentahoJcrConstants.getPHO_NT_INTERNALFOLDER());
   }
 }
示例#9
0
  public void defineNamespacePrefixes(Session session) throws RepositoryException {
    final Iterator<NamespaceEntry[]> iter = this.namespaceTable.values().iterator();
    while (iter.hasNext()) {
      final NamespaceEntry[] entries = iter.next();
      for (int i = 0; i < entries.length; i++) {

        // the namespace prefixing is a little bit tricky:
        String mappedPrefix = null;
        // first, we check if the namespace is registered with a prefix
        try {
          mappedPrefix = session.getNamespacePrefix(entries[i].namespace);
        } catch (NamespaceException ne) {
          // the namespace is not registered yet, so we should do this
          // can we directly use the desired prefix?
          mappedPrefix = entries[i].prefix + "_new";
          try {
            session.getNamespaceURI(entries[i].prefix);
          } catch (NamespaceException ne2) {
            // as an exception occured we can directly use the new prefix
            mappedPrefix = entries[i].prefix;
          }
          session
              .getWorkspace()
              .getNamespaceRegistry()
              .registerNamespace(mappedPrefix, entries[i].namespace);
        }
        // do we have to remap?
        if (mappedPrefix != null && !mappedPrefix.equals(entries[i].prefix)) {
          // check if the prefix is already used?
          String oldUri = null;
          try {
            oldUri = session.getNamespaceURI(entries[i].prefix);
            session.setNamespacePrefix(entries[i].prefix + "_old", oldUri);
          } catch (NamespaceException ne) {
            // ignore: prefix is not used
          }
          // finally set prefix
          session.setNamespacePrefix(entries[i].prefix, entries[i].namespace);
        }
      }
    }
  }
 protected Map<String, List<String>> getRoleBindings(Session session, ITenant tenant)
     throws RepositoryException {
   Map<String, List<String>> map = new HashMap<String, List<String>>();
   if (tenant == null) {
     tenant = JcrTenantUtils.getTenant();
   }
   if (!TenantUtils.isAccessibleTenant(tenant)) {
     return map;
   }
   PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
   final String phoNsPrefix =
       session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
   final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
   Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
   NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
   if (!runtimeRoleNodes.hasNext()) {
     // no bindings setup yet; fall back on bootstrap bindings
     map.putAll(bootstrapRoleBindings);
   } else {
     while (runtimeRoleNodes.hasNext()) {
       Node runtimeRoleNode = runtimeRoleNodes.nextNode();
       if (runtimeRoleNode.hasProperty(pentahoJcrConstants.getPHO_BOUNDROLES())) {
         // get clean runtime role name
         String runtimeRoleName =
             JcrStringHelper.fileNameDecode(
                 runtimeRoleNode.getName().substring(phoNsPrefix.length()));
         // get logical role names
         List<String> logicalRoleNames = new ArrayList<String>();
         Value[] values =
             runtimeRoleNode.getProperty(pentahoJcrConstants.getPHO_BOUNDROLES()).getValues();
         for (Value value : values) {
           logicalRoleNames.add(value.getString());
         }
         map.put(runtimeRoleName, logicalRoleNames);
       }
     }
   }
   // add all immutable bindings
   map.putAll(immutableRoleBindingNames);
   return map;
 }
 // returns encoded path
 private String getOriginalParentFolderPath(
     final Session session,
     final PentahoJcrConstants pentahoJcrConstants,
     final Node trashFileNode,
     final boolean relative)
     throws RepositoryException {
   if (trashFileNode.getParent().hasProperty(pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH())) {
     String relPath =
         trashFileNode
             .getParent()
             .getProperty(pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH())
             .getString();
     return relative ? relPath : pathConversionHelper.relToAbs(relPath);
   } else {
     // legacy mode
     final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS);
     String originalParentFolderId =
         trashFileNode.getParent().getParent().getName().substring(prefix.length() + 1);
     String absPath = session.getNodeByIdentifier(originalParentFolderId).getPath();
     return relative ? pathConversionHelper.absToRel(absPath) : absPath;
   }
 }
  @Test
  public void shouldAddNodeTypesAndNamespaces() throws Exception {
    File file = new File("src/test/resources/config/configRepository.xml");
    assertThat(file.exists(), is(true));
    assertThat(file.canRead(), is(true));
    assertThat(file.isFile(), is(true));

    configuration.loadFrom("src/test/resources/config/configRepository.xml");
    // Verify that the configration was loaded correctly ...
    assertThat(configuration.repository("Car Repository").getSource(), is("Cars"));
    // ModeShapeConfiguration.ConfigurationDefinition content1 =
    // configuration.getConfigurationDefinition();
    // Subgraph subgraph1 = content1.graph().getSubgraphOfDepth(6).at("/");

    // Load the node types from the CND file, and save the configuration ...
    InputStream nodeTypes = getClass().getResourceAsStream("/tck/tck_test_types.cnd");
    configuration.repository("Car Repository").addNodeTypes(nodeTypes);
    configuration.save();
    // ModeShapeConfiguration.ConfigurationDefinition content2 =
    // configuration.getConfigurationDefinition();
    // Subgraph subgraph2 = content2.graph().getSubgraphOfDepth(6).at("/");

    // Verify there were no problems loading the CND file ...
    assertThat(configuration.getProblems().isEmpty(), is(true));
    assertThat(
        configuration
            .getConfigurationDefinition()
            .getContext()
            .getNamespaceRegistry()
            .isRegisteredNamespaceUri("http://www.modeshape.org/test/1.0"),
        is(true));

    // Verify that the graph has been updated correctly ...
    ModeShapeConfiguration.ConfigurationDefinition content =
        configuration.getConfigurationDefinition();
    Subgraph subgraph = content.graph().getSubgraphOfDepth(6).at("/");

    assertThat(
        subgraph.getNode("/mode:repositories").getChildren(), hasChild(segment("Car Repository")));
    assertThat(subgraph.getNode("/mode:repositories/Car Repository"), is(notNullValue()));
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository"),
        hasProperty(ModeShapeLexicon.SOURCE_NAME, "Cars"));
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository").getChildren(),
        hasChild(segment("mode:options")));
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository/jcr:nodeTypes"), is(notNullValue()));
    // for (Location child : subgraph.getNode("/mode:repositories/Car
    // Repository/mode:nodeTypes").getChildren()) {
    // System.out.println(child.getPath().getLastSegment().getString(context().getNamespaceRegistry()));
    // }
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository/jcr:nodeTypes").getChildren(),
        hasChildren(
            segment("modetest:noSameNameSibs"),
            segment("modetest:referenceableUnstructured"),
            segment("modetest:nodeWithMandatoryProperty"),
            segment("modetest:nodeWithMandatoryChild"),
            segment("modetest:unorderableUnstructured")));
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository/mode:namespaces"), is(notNullValue()));

    // Check that the namespace in the CND file was persisted correctly ...
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository/mode:namespaces").getChildren(),
        hasChild(segment("modetest")));
    assertThat(
        subgraph.getNode("/mode:repositories/Car Repository/mode:namespaces/modetest"),
        hasProperty(ModeShapeLexicon.URI, "http://www.modeshape.org/test/1.0"));

    // Initialize IDTrust and a policy file (which defines the "modeshape-jcr" login config name)
    JaasTestUtil.initJaas("security/jaas.conf.xml");

    // Create and start the engine ...
    engine = configuration.build();
    engine.start();
    Repository repository = engine.getRepository("Car Repository");
    assertThat(repository, is(notNullValue()));

    // Create a session, authenticating using one of the usernames defined by our JAAS policy
    // file(s) ...
    Session session = null;
    try {
      session = repository.login(new SimpleCredentials("superuser", "superuser".toCharArray()));

      // Check that the namespace showed up ...
      assertThat(session.getNamespacePrefix("http://www.modeshape.org/test/1.0"), is("modetest"));

      // Check that some of the node types showed up ...
      NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();
      assertThat(
          ntm.getNodeType("modetest:noSameNameSibs"), is(notNullValue())); // throws exception
      assertThat(
          ntm.getNodeType("modetest:referenceableUnstructured"),
          is(notNullValue())); // throws exception
      assertThat(
          ntm.getNodeType("modetest:nodeWithMandatoryProperty"),
          is(notNullValue())); // throws exception
      assertThat(
          ntm.getNodeType("modetest:nodeWithMandatoryChild"),
          is(notNullValue())); // throws exception
      assertThat(
          ntm.getNodeType("modetest:unorderableUnstructured"),
          is(notNullValue())); // throws exception
    } finally {
      if (session != null) session.logout();
    }
  }
  @Override
  public List<String> getBoundLogicalRoleNames(
      Session session, ITenant tenant, List<String> runtimeRoleNames)
      throws NamespaceException, RepositoryException {
    if ((tenant == null) || (tenant.getId() == null)) {
      return getBoundLogicalRoleNames(session, runtimeRoleNames);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      return new ArrayList<String>();
    }

    final List<String> uncachedRuntimeRoleNames = new ArrayList<String>();
    final Set<String> cachedBoundLogicalRoleNames = new HashSet<String>();
    for (String runtimeRoleName : runtimeRoleNames) {
      String roleName = tenantedRoleNameUtils.getPrincipleName(runtimeRoleName);
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
      Object fromRegionCache =
          cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId);
      if (fromRegionCache != null) {
        cachedBoundLogicalRoleNames.addAll((Collection<String>) fromRegionCache);
      } else {
        uncachedRuntimeRoleNames.add(roleName);
      }
    }
    if (uncachedRuntimeRoleNames.isEmpty()) {
      // no need to hit the repo
      return new ArrayList<String>(cachedBoundLogicalRoleNames);
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    HashMultimap<String, String> boundLogicalRoleNames = HashMultimap.create();
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    if (!runtimeRoleNodes.hasNext()) {
      // no bindings setup yet; fall back on bootstrap bindings
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        if (bootstrapRoleBindings.containsKey(runtimeRoleName)) {
          boundLogicalRoleNames.putAll(roleId, bootstrapRoleBindings.get(runtimeRoleName));
        }
      }
    } else {
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        if (NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName)) {
          Node runtimeRoleFolderNode =
              NodeHelper.getNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName);
          if (runtimeRoleFolderNode.hasProperty(pentahoJcrConstants.getPHO_BOUNDROLES())) {
            Value[] values =
                runtimeRoleFolderNode
                    .getProperty(pentahoJcrConstants.getPHO_BOUNDROLES())
                    .getValues();
            String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
            for (Value value : values) {
              boundLogicalRoleNames.put(roleId, value.getString());
            }
          }
        }
      }
    }
    // now add in immutable bound logical role names
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      if (immutableRoleBindings.containsKey(runtimeRoleName)) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        boundLogicalRoleNames.putAll(roleId, immutableRoleBindingNames.get(runtimeRoleName));
      }
    }

    // update cache
    Map<String, Collection<String>> stringCollectionMap = boundLogicalRoleNames.asMap();
    for (Entry<String, Collection<String>> stringCollectionEntry : stringCollectionMap.entrySet()) {
      cacheManager.putInRegionCache(
          LOGICAL_ROLE_BINDINGS_REGION,
          stringCollectionEntry.getKey(),
          stringCollectionEntry.getValue());
    }

    // now add in those runtime roles that have no bindings to the cache
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);

      if (cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId) == null) {
        cacheManager.putInRegionCache(
            LOGICAL_ROLE_BINDINGS_REGION, roleId, Collections.emptyList());
      }
    }

    // combine cached findings plus ones from repo
    Set<String> res = new HashSet<String>();
    res.addAll(cachedBoundLogicalRoleNames);
    res.addAll(boundLogicalRoleNames.values());
    return new ArrayList<String>(res);
  }