public Map<String, VProperty> getPropertiesMap(boolean includePrimaryType) {
    Map<String, VProperty> propertiesMap = new HashMap<String, VProperty>();
    for (Map.Entry<String, VPropertyDefinitionI> entry : properties.entrySet()) {
      // TODO: Replace with VProperty Factory
      VProperty newProp =
          new XMLProperty(name, entry.getValue().getDefaultValue(), AbstractProperty.STRING_PREFIX);
      propertiesMap.put(entry.getKey(), newProp);
    }
    if (includePrimaryType) {
      propertiesMap.put(
          AbstractProperty.JCR_PRIMARYTYPE,
          new XMLProperty(AbstractProperty.JCR_PRIMARYTYPE, name, AbstractProperty.STRING_PREFIX));
    }

    // also get supertype properties
    for (String supertype : supertypes) {
      VNodeDefinition vNodeDefinition = VNodeDefinition.getDefinition(supertype);
      if (vNodeDefinition != null) propertiesMap.putAll(vNodeDefinition.getPropertiesMap(false));
      else {
        log.error("Could not get definition for " + supertype);
      }
    }

    return propertiesMap;
  }
  public void save(final int operationType)
      throws AccessDeniedException, ItemExistsException, ConstraintViolationException,
          InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException,
          RepositoryException {
    if (!isSystem() && getLocale() != null) {
      for (JCRNodeWrapper node : newNodes.values()) {
        for (String s : node.getNodeTypes()) {
          ExtendedPropertyDefinition[] propDefs =
              NodeTypeRegistry.getInstance().getNodeType(s).getPropertyDefinitions();
          for (ExtendedPropertyDefinition propDef : propDefs) {
            if (propDef.isMandatory()
                && propDef.getRequiredType() != PropertyType.WEAKREFERENCE
                && propDef.getRequiredType() != PropertyType.REFERENCE
                && !propDef.isProtected()
                && !node.hasProperty(propDef.getName())) {
              throw new ConstraintViolationException("Mandatory field : " + propDef.getName());
            }
          }
        }
      }
    }
    newNodes.clear();

    JCRObservationManager.doWorkspaceWriteCall(
        this,
        operationType,
        new JCRCallback<Object>() {
          public Object doInJCR(JCRSessionWrapper thisSession) throws RepositoryException {
            for (Session session : sessions.values()) {
              session.save();
            }
            return null;
          }
        });
  }
 public Map<String, String> getStoredPasswordsProviders() {
   Map<String, String> results = new HashMap<String, String>();
   results.put(null, user.getUsername());
   for (JCRStoreProvider provider : sessionFactory.getProviders().values()) {
     if ("storedPasswords".equals(provider.getAuthenticationType())) {
       results.put(provider.getKey(), user.getProperty("storedUsername_" + provider.getKey()));
     }
   }
   return results;
 }
  public Map<String, String> getChildSuggestions() {
    Map<String, String> suggestions = new HashMap<String, String>();
    // get supertype child suggestions
    for (String supertype : supertypes) {
      VNodeDefinition vNodeDefinition = VNodeDefinition.getDefinition(supertype);
      suggestions.putAll(vNodeDefinition.getChildSuggestions());
    }

    // now put in this node's suggestions
    suggestions.putAll(childSuggestions);

    return suggestions;
  }
  public VNodeDefinition(Node node) throws RepositoryException {
    name = node.getProperty(JCR_NODETYPENAME).getString();

    // do properties
    properties = new HashMap<String, VPropertyDefinitionI>();
    childSuggestions = new HashMap<String, String>();
    NodeIterator nodeIterator = node.getNodes();
    while (nodeIterator.hasNext()) {
      Node definitionNode = nodeIterator.nextNode();
      String nodeType = definitionNode.getProperty(AbstractProperty.JCR_PRIMARYTYPE).getString();

      // do a property
      if (NT_PROPERTYDEFINITION.equals(nodeType)) {
        String propertyName = "*"; // default to wildcard name
        if (definitionNode.hasProperty(JCR_NAME)) {

          // only add non-autogenerated properties
          if (!definitionNode.getProperty(JCR_AUTOCREATED).getBoolean()) {
            propertyName = definitionNode.getProperty(JCR_NAME).getString();
            properties.put(propertyName, new VPropertyDefinition(definitionNode));
          }
        } else {
          // property with no name means this node can accept custom properties
          canAddProperties = true;
        }
      }

      // do a child suggestion
      if (NT_CHILDNODEDEFINITION.equals(nodeType)) {
        String childName = "*";
        // only do well-defined childnodedefinitions with the following 2 jcr properties
        if (definitionNode.hasProperty(JCR_NAME)
            && definitionNode.hasProperty(JCR_DEFAULTPRIMARYTYPE)) {
          childSuggestions.put(
              definitionNode.getProperty(JCR_NAME).getString(),
              definitionNode.getProperty(JCR_DEFAULTPRIMARYTYPE).getString());
        }
      }
    }

    // do supertypes
    supertypes = new HashSet<String>();
    if (node.hasProperty(JCR_SUPERTYPES)) {
      for (Value value : node.getProperty(JCR_SUPERTYPES).getValues()) {
        supertypes.add(value.getString());
      }
    }

    // set mixin status
    isMixin = node.hasProperty(JCR_ISMIXIN) && node.getProperty(JCR_ISMIXIN).getBoolean();
  }
 public void move(String source, String dest)
     throws ItemExistsException, PathNotFoundException, VersionException,
         ConstraintViolationException, LockException, RepositoryException {
   getWorkspace().move(source, dest, true);
   if (sessionCacheByPath.containsKey(source)) {
     JCRNodeWrapper n = sessionCacheByPath.get(source);
     if (n instanceof JCRNodeDecorator) {
       n = ((JCRNodeDecorator) n).getDecoratedNode();
     }
     ((JCRNodeWrapperImpl) n).localPath = dest;
     ((JCRNodeWrapperImpl) n).localPathInProvider = dest;
   }
   flushCaches();
 }
 void unregisterNewNode(JCRNodeWrapper node) {
   if (!newNodes.isEmpty()) {
     newNodes.remove(node.getPath());
     try {
       if (node.hasNodes()) {
         NodeIterator it = node.getNodes();
         while (it.hasNext()) {
           unregisterNewNode((JCRNodeWrapper) it.next());
         }
       }
     } catch (RepositoryException e) {
       logger.warn("Error unregistering new nodes", e);
     }
   }
 }
 public boolean hasPendingChanges() throws RepositoryException {
   for (Session session : sessions.values()) {
     if (session.hasPendingChanges()) {
       return true;
     }
   }
   return false;
 }
  public Session getProviderSession(JCRStoreProvider provider) throws RepositoryException {
    if (sessions.get(provider) == null) {
      Session s = null;

      if (credentials instanceof SimpleCredentials) {
        SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
        JahiaLoginModule.Token t =
            JahiaLoginModule.getToken(
                simpleCredentials.getUserID(), new String(simpleCredentials.getPassword()));

        s = provider.getSession(credentials, workspace.getName());

        credentials =
            JahiaLoginModule.getCredentials(
                simpleCredentials.getUserID(), t != null ? t.deniedPath : null);
      } else {
        s = provider.getSession(credentials, workspace.getName());
      }

      sessions.put(provider, s);
      for (String token : tokens) {
        s.addLockToken(token);
      }

      NamespaceRegistry namespaceRegistryWrapper = getWorkspace().getNamespaceRegistry();
      NamespaceRegistry providerNamespaceRegistry = s.getWorkspace().getNamespaceRegistry();

      if (providerNamespaceRegistry != null) {
        for (String prefix : namespaceRegistryWrapper.getPrefixes()) {
          try {
            providerNamespaceRegistry.getURI(prefix);
          } catch (NamespaceException ne) {
            providerNamespaceRegistry.registerNamespace(
                prefix, namespaceRegistryWrapper.getURI(prefix));
          }
        }
      }

      for (String prefix : prefixToNs.keySet()) {
        s.setNamespacePrefix(prefix, prefixToNs.get(prefix));
      }
    }
    return sessions.get(provider);
  }
 /**
  * Applies the namespace prefix to the appropriate sessions, including the underlying provider
  * sessions.
  *
  * @param prefix
  * @param uri
  * @throws NamespaceException
  * @throws RepositoryException
  */
 public void setNamespacePrefix(String prefix, String uri)
     throws NamespaceException, RepositoryException {
   nsToPrefix.put(uri, prefix);
   prefixToNs.put(prefix, uri);
   for (Session s : sessions.values()) {
     s.setNamespacePrefix(prefix, uri);
     try {
       NamespaceRegistry nsReg = s.getWorkspace().getNamespaceRegistry();
       if (nsReg != null) {
         nsReg.registerNamespace(prefix, uri);
       }
     } catch (RepositoryException e) {
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Prefix/uri could not be registered in workspace's registry- " + prefix + "/" + uri,
             e);
       }
     }
   }
 }
 public void logout() {
   for (Session session : sessions.values()) {
     session.logout();
   }
   if (credentials instanceof SimpleCredentials) {
     SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
     JahiaLoginModule.removeToken(
         simpleCredentials.getUserID(), new String(simpleCredentials.getPassword()));
   }
   isLive = false;
   activeSessions.decrementAndGet();
 }
 public String[] getLockTokens() {
   List<String> allTokens = new ArrayList<String>(tokens);
   for (Session session : sessions.values()) {
     String[] tokens = session.getLockTokens();
     for (String token : tokens) {
       if (!allTokens.contains(token)) {
         allTokens.add(token);
       }
     }
   }
   return allTokens.toArray(new String[allTokens.size()]);
 }
  // only include non-mixin types
  public static String[] getNodeTypeNames() {
    // filter mixins out
    Set<String> keySet = allNodes.keySet();
    Set<String> copySet = new HashSet<String>();
    for (String s : keySet) copySet.add(s); // do I really need to do this, java?
    for (String s : keySet) {
      if (getDefinition(s).isMixin) copySet.remove(s);
    }

    String[] options = new String[copySet.size()];
    options = copySet.toArray(options);
    Arrays.sort(options);
    return options;
  }
 public static void buildDefinitions(Session session) {
   log.info("started building node definitions");
   String nodeName = "";
   try {
     allNodes = new HashMap<String, VNodeDefinition>();
     Node rootNode = session.getNode("/jcr:system/jcr:nodeTypes");
     NodeIterator nodeIterator = rootNode.getNodes();
     while (nodeIterator.hasNext()) {
       Node node = nodeIterator.nextNode();
       nodeName = node.getName();
       VNodeDefinition vNodeDefinition = new VNodeDefinition(node);
       customizeDefinition(vNodeDefinition); // possibly customize this definition
       allNodes.put(nodeName, vNodeDefinition);
     }
     log.info("finished building nodes");
   } catch (RepositoryException re) {
     log.warn("Could not build node definitions, died at " + nodeName, re);
   } finally {
     if (session != null) session.logout();
   }
 }
 private JCRNodeWrapper dereference(JCRNodeWrapper parent, String refPath)
     throws RepositoryException {
   JCRStoreProvider provider = parent.getProvider();
   JCRNodeWrapper wrapper;
   Node referencedNode = parent.getRealNode().getProperty("j:node").getNode();
   String fullPath = parent.getPath() + DEREF_SEPARATOR + refPath;
   if (parent.getPath().startsWith(referencedNode.getPath())) {
     throw new PathNotFoundException(fullPath);
   }
   String refRootName = StringUtils.substringBefore(refPath, "/");
   if (!referencedNode.getName().equals(refRootName)) {
     throw new PathNotFoundException(fullPath);
   }
   refPath = StringUtils.substringAfter(refPath, "/");
   if (refPath.equals("")) {
     wrapper = provider.getNodeWrapper(referencedNode, fullPath, parent, this);
   } else {
     Node node = referencedNode.getNode(refPath);
     wrapper = provider.getNodeWrapper(node, fullPath, null, this);
   }
   sessionCacheByPath.put(fullPath, wrapper);
   return wrapper;
 }
 public static boolean hasDefinitions() {
   return allNodes != null && !allNodes.isEmpty();
 }
 /**
  * Get sessions from all providers used in this wrapper.
  *
  * @return a <code>Collection</code> of <code>JCRSessionWrapper</code> objects
  */
 public Collection<Session> getAllSessions() {
   return sessions.values();
 }
 public void removeLockToken(String token) {
   tokens.remove(token);
   for (Session session : sessions.values()) {
     session.removeLockToken(token);
   }
 }
 protected void flushCaches() {
   sessionCacheByIdentifier.clear();
   sessionCacheByPath.clear();
 }
 /**
  * Adds the specified lock token to the wrapped sessions. Holding a lock token makes the <code>
  * Session</code> the owner of the lock specified by that particular lock token.
  *
  * @param token a lock token (a string).
  * @deprecated As of JCR 2.0, {@link LockManager#addLockToken(String)} should be used instead.
  */
 public void addLockToken(String token) {
   tokens.add(token);
   for (Session session : sessions.values()) {
     session.addLockToken(token);
   }
 }
 protected JCRNodeWrapper getCachedNode(String uuid) {
   return sessionCacheByIdentifier.get(uuid);
 }
 public String getNamespaceURI(String prefix) throws NamespaceException, RepositoryException {
   if (prefixToNs.containsKey(prefix)) {
     return prefixToNs.get(prefix);
   }
   return getWorkspace().getNamespaceRegistry().getURI(prefix);
 }
 public String[] getNamespacePrefixes() throws RepositoryException {
   Set<String> wsPrefixes =
       new HashSet<String>(Arrays.asList(getWorkspace().getNamespaceRegistry().getPrefixes()));
   wsPrefixes.addAll(prefixToNs.keySet());
   return wsPrefixes.toArray(new String[wsPrefixes.size()]);
 }
  public JCRNodeWrapper getNodeByUUID(final String uuid, final boolean checkVersion)
      throws ItemNotFoundException, RepositoryException {

    if (sessionCacheByIdentifier.containsKey(uuid)) {
      return sessionCacheByIdentifier.get(uuid);
    }
    RepositoryException originalEx = null;
    for (JCRStoreProvider provider : sessionFactory.getProviderList()) {
      if (!provider.isInitialized()) {
        logger.debug(
            "Provider "
                + provider.getKey()
                + " / "
                + provider.getClass().getName()
                + " is not yet initialized, skipping...");
        continue;
      }
      if (provider instanceof JackrabbitStoreProvider && JCRContentUtils.isNotJcrUuid(uuid)) {
        // not a valid UUID, probably a VFS node
        continue;
      }
      try {
        Session session = getProviderSession(provider);
        if (session instanceof JahiaSessionImpl
            && getUser() != null
            && sessionFactory.getCurrentAliasedUser() != null
            && sessionFactory.getCurrentAliasedUser().equals(getUser())) {
          ((JahiaSessionImpl) session).toggleThisSessionAsAliased();
        }
        Node n = session.getNodeByIdentifier(uuid);
        JCRNodeWrapper wrapper = provider.getNodeWrapper(n, this);
        if (getUser() != null
            && sessionFactory.getCurrentAliasedUser() != null
            && !sessionFactory.getCurrentAliasedUser().equals(getUser())) {
          JCRTemplate.getInstance()
              .doExecuteWithUserSession(
                  sessionFactory.getCurrentAliasedUser().getUsername(),
                  session.getWorkspace().getName(),
                  getLocale(),
                  new JCRCallback<Object>() {
                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                      return session.getNodeByUUID(uuid, checkVersion);
                    }
                  });
        }
        if (checkVersion && (versionDate != null || versionLabel != null)) {
          wrapper = getFrozenVersionAsRegular(n, provider);
        }
        sessionCacheByIdentifier.put(uuid, wrapper);
        sessionCacheByPath.put(wrapper.getPath(), wrapper);

        return wrapper;
      } catch (ItemNotFoundException ee) {
        // All good
        if (originalEx == null) {
          originalEx = ee;
        }
      } catch (UnsupportedRepositoryOperationException uso) {
        logger.debug(
            "getNodeByUUID unsupported by : "
                + provider.getKey()
                + " / "
                + provider.getClass().getName());
        if (originalEx == null) {
          originalEx = uso;
        }
      } catch (RepositoryException ex) {
        if (originalEx == null) {
          originalEx = ex;
        }
        logger.warn(
            "repository exception : "
                + provider.getKey()
                + " / "
                + provider.getClass().getName()
                + " : "
                + ex.getMessage());
      }
    }
    if (originalEx != null) {
      if (originalEx instanceof ItemNotFoundException) {
        throw originalEx;
      } else {
        throw new ItemNotFoundException(uuid, originalEx);
      }
    }

    throw new ItemNotFoundException(uuid);
  }
  public JCRItemWrapper getItem(String path, final boolean checkVersion)
      throws PathNotFoundException, RepositoryException {
    if (sessionCacheByPath.containsKey(path)) {
      return sessionCacheByPath.get(path);
    }
    if (path.contains(DEREF_SEPARATOR)) {
      JCRNodeWrapper parent =
          (JCRNodeWrapper)
              getItem(StringUtils.substringBeforeLast(path, DEREF_SEPARATOR), checkVersion);
      return dereference(parent, StringUtils.substringAfterLast(path, DEREF_SEPARATOR));
    }
    Map<String, JCRStoreProvider> dynamicMountPoints = sessionFactory.getDynamicMountPoints();
    for (Map.Entry<String, JCRStoreProvider> mp : dynamicMountPoints.entrySet()) {
      if (path.startsWith(mp.getKey() + "/")) {
        String localPath = path.substring(mp.getKey().length());
        JCRStoreProvider provider = mp.getValue();
        Item item = getProviderSession(provider).getItem(provider.getRelativeRoot() + localPath);
        if (item.isNode()) {
          return provider.getNodeWrapper((Node) item, localPath, null, this);
        } else {
          return provider.getPropertyWrapper((Property) item, this);
        }
      }
    }
    Map<String, JCRStoreProvider> mountPoints = sessionFactory.getMountPoints();
    for (Map.Entry<String, JCRStoreProvider> mp : mountPoints.entrySet()) {
      String key = mp.getKey();
      if (key.equals("/") || path.equals(key) || path.startsWith(key + "/")) {
        String localPath = path;
        if (!key.equals("/")) {
          localPath = localPath.substring(key.length());
        }
        JCRStoreProvider provider = mp.getValue();
        if (localPath.equals("")) {
          localPath = "/";
        }
        //                Item item = getProviderSession(provider).getItem(localPath);
        Session session = getProviderSession(provider);
        if (session instanceof JahiaSessionImpl
            && getUser() != null
            && sessionFactory.getCurrentAliasedUser() != null
            && sessionFactory.getCurrentAliasedUser().equals(getUser())) {
          ((JahiaSessionImpl) session).toggleThisSessionAsAliased();
        }
        Item item = session.getItem(provider.getRelativeRoot() + localPath);
        if (item.isNode()) {
          final Node node = (Node) item;
          JCRNodeWrapper wrapper = provider.getNodeWrapper(node, localPath, null, this);
          if (getUser() != null
              && sessionFactory.getCurrentAliasedUser() != null
              && !sessionFactory.getCurrentAliasedUser().equals(getUser())) {
            final JCRNodeWrapper finalWrapper = wrapper;
            JCRTemplate.getInstance()
                .doExecuteWithUserSession(
                    sessionFactory.getCurrentAliasedUser().getUsername(),
                    getWorkspace().getName(),
                    getLocale(),
                    new JCRCallback<Object>() {
                      public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        return session.getNodeByUUID(finalWrapper.getIdentifier(), checkVersion);
                      }
                    });
          }
          if (checkVersion
              && (versionDate != null || versionLabel != null)
              && node.isNodeType("mix:versionable")) {
            wrapper = getFrozenVersionAsRegular(node, provider);
          }
          sessionCacheByPath.put(path, wrapper);
          sessionCacheByIdentifier.put(wrapper.getIdentifier(), wrapper);

          return wrapper;
        } else {
          return provider.getPropertyWrapper((Property) item, this);
        }
      }
    }
    throw new PathNotFoundException(path);
  }
 public static VNodeDefinition getDefinition(String name) {
   return allNodes.get(name);
 }
 void removeFromCache(JCRItemWrapper item) throws RepositoryException {
   sessionCacheByPath.remove(item.getPath());
   if (item instanceof JCRNodeWrapper) {
     sessionCacheByIdentifier.remove(((JCRNodeWrapper) item).getIdentifier());
   }
 }
 public String getNamespacePrefix(String uri) throws NamespaceException, RepositoryException {
   if (nsToPrefix.containsKey(uri)) {
     return nsToPrefix.get(uri);
   }
   return getWorkspace().getNamespaceRegistry().getPrefix(uri);
 }
 public void refresh(boolean b) throws RepositoryException {
   for (Session session : sessions.values()) {
     session.refresh(b);
   }
 }
 void registerNewNode(JCRNodeWrapper node) {
   newNodes.put(node.getPath(), node);
 }