/**
  * {@inheritDoc}
  *
  * @see
  *     org.modeshape.graph.request.processor.RequestProcessor#process(org.modeshape.graph.request.ReadAllPropertiesRequest)
  */
 @Override
 public void process(ReadAllPropertiesRequest request) {
   if (request == null) return;
   try {
     Workspace workspace = workspaceFor(request.inWorkspace());
     Node node = workspace.node(request.at());
     Location actualLocation = workspace.locationFor(node);
     request.setActualLocationOfNode(actualLocation);
     // Read the properties ...
     for (PropertyIterator iter = node.getProperties(); iter.hasNext(); ) {
       request.addProperty(workspace.propertyFor(iter.nextProperty()));
     }
     // Add in the 'jcr:uuid' property ...
     if (actualLocation.hasIdProperties()) {
       request.addProperty(workspace.propertyFor(ModeShapeLexicon.UUID, actualLocation.getUuid()));
     }
     // Get the number of children ...
     NodeIterator childIter = node.getNodes();
     int numChildren = (int) childIter.getSize();
     if (numChildren == -1) {
       numChildren = 0;
       while (childIter.hasNext()) {
         childIter.nextNode();
         ++numChildren;
       }
     }
     request.setNumberOfChildren(numChildren);
     setCacheableInfo(request);
   } catch (Throwable e) {
     request.setError(e);
   }
 }
Example #2
0
 protected RepositoryBuilder(
     ReturnType returnObject, Graph.Batch batch, Path path, Name... names) {
   super(returnObject, batch, path, names);
   // Load the current options ...
   try {
     Path optionsPath =
         context.getValueFactories().getPathFactory().create(path, ModeShapeLexicon.OPTIONS);
     Subgraph options = batch.getGraph().getSubgraphOfDepth(2).at(optionsPath);
     for (Location optionChild : options.getRoot().getChildren()) {
       Node option = options.getNode(optionChild);
       Property property = option.getProperty(ModeShapeLexicon.VALUE);
       if (property != null && property.isEmpty()) {
         try {
           Option key =
               Option.findOption(
                   optionChild
                       .getPath()
                       .getLastSegment()
                       .getString(context.getNamespaceRegistry()));
           String value =
               context.getValueFactories().getStringFactory().create(property.getFirstValue());
           optionValues.put(key, value);
         } catch (IllegalArgumentException e) {
           // the key is not valid, so skip it ...
         }
       }
     }
   } catch (PathNotFoundException e) {
     // No current options
   }
 }
Example #3
0
  /**
   * {@inheritDoc}
   *
   * @see org.modeshape.repository.ModeShapeEngine#checkConfiguration(org.modeshape.graph.Subgraph)
   */
  @Override
  protected void checkConfiguration(Subgraph configuration) {
    super.checkConfiguration(configuration);

    // Get the list of sources ...
    Set<String> sourceNames = new HashSet<String>();
    for (Location child : configuration.getNode(ModeShapeLexicon.SOURCES)) {
      String name = child.getPath().getLastSegment().getName().getLocalName();
      sourceNames.add(name);
    }
    // Verify all of the repositories reference valid sources ...
    for (Location child : configuration.getNode(ModeShapeLexicon.REPOSITORIES)) {
      String repositoryName = readable(child.getPath().getLastSegment().getName());
      Node repositoryNode = configuration.getNode(child);
      Property property = repositoryNode.getProperty(ModeShapeLexicon.SOURCE_NAME);
      if (property == null) {
        getProblems()
            .addError(JcrI18n.repositoryReferencesNonExistantSource, repositoryName, "null");
      } else {
        String sourceName = string(property.getFirstValue());
        if (!sourceNames.contains(sourceName)) {
          getProblems()
              .addError(JcrI18n.repositoryReferencesNonExistantSource, repositoryName, sourceName);
        }
      }
    }
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.modeshape.graph.request.processor.RequestProcessor#process(org.modeshape.graph.request.ReadNodeRequest)
  */
 @Override
 public void process(ReadNodeRequest request) {
   if (request == null) return;
   try {
     Workspace workspace = workspaceFor(request.inWorkspace());
     Node node = workspace.node(request.at());
     Location actualLocation = workspace.locationFor(node);
     request.setActualLocationOfNode(actualLocation);
     // Read the children ...
     for (NodeIterator iter = node.getNodes(); iter.hasNext(); ) {
       request.addChild(workspace.locationFor(iter.nextNode()));
     }
     // Read the properties ...
     for (PropertyIterator iter = node.getProperties(); iter.hasNext(); ) {
       request.addProperty(workspace.propertyFor(iter.nextProperty()));
     }
     // Add in the 'jcr:uuid' property ...
     if (actualLocation.hasIdProperties()) {
       request.addProperty(workspace.propertyFor(ModeShapeLexicon.UUID, actualLocation.getUuid()));
     }
     setCacheableInfo(request);
   } catch (Throwable e) {
     request.setError(e);
   }
 }
Example #5
0
 /**
  * Sets the actual and complete location of the node being created. This method must be called
  * when processing the request, and the actual location must have a {@link Location#getPath()
  * path}.
  *
  * @param actual the actual location of the node being created, or null if the {@link #under()
  *     current location} should be used
  * @throws IllegalArgumentException the actual location is null or does not have a path
  * @throws IllegalStateException if the request is frozen
  */
 public void setActualLocationOfNode(Location actual) {
   checkNotFrozen();
   CheckArg.isNotNull(actual, "actual");
   if (!actual.hasPath()) {
     throw new IllegalArgumentException(GraphI18n.actualLocationMustHavePath.text(actual));
   }
   assert actual.hasPath();
   this.actualLocation = actual;
 }
Example #6
0
 /**
  * {@inheritDoc}
  *
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   String parent = under() + "/";
   if (under.hasPath() && under.getPath().isRoot()) parent = "/";
   return "create in the \""
       + workspaceName
       + "\" workspace the node \""
       + parent
       + childName
       + "\" with properties "
       + properties();
 }
Example #7
0
 /**
  * Get the names of each of the JCR repositories.
  *
  * @return the immutable names of the repositories that exist at the time this method is called
  */
 public Set<String> getRepositoryNames() {
   checkRunning();
   Set<String> results = new HashSet<String>();
   // Read the names of the JCR repositories from the configuration (not from the Repository
   // objects used so far) ...
   PathFactory pathFactory = getExecutionContext().getValueFactories().getPathFactory();
   Path repositoriesPath =
       pathFactory.create(configuration.getPath(), ModeShapeLexicon.REPOSITORIES);
   Graph configuration = getConfigurationGraph();
   for (Location child : configuration.getChildren().of(repositoriesPath)) {
     Name repositoryName = child.getPath().getLastSegment().getName();
     results.add(readable(repositoryName));
   }
   return Collections.unmodifiableSet(results);
 }
    /**
     * Obtain the actual location for the supplied node.
     *
     * @param node the existing node; may not be null
     * @return the actual location, with UUID if the node is "mix:referenceable"
     * @throws RepositoryException if there is an error
     */
    public Location locationFor(Node node) throws RepositoryException {
      // Get the path to the node ...
      String pathStr = node.getPath();
      Path path = factories.getPathFactory().create(pathStr);

      // Does the node have a UUID ...
      String uuidStr = node.getIdentifier();
      if (uuidStr != null) {
        try {
          UUID uuid = UUID.fromString(uuidStr);
          return Location.create(path, uuid);
        } catch (IllegalArgumentException e) {
          // Ignore, since the identifier is not a valid UUID
        }
      }
      return Location.create(path);
    }
 /**
  * Find the existing node given the location.
  *
  * @param location the location of the node, which must have a {@link Location#getPath() path}
  *     and/or {@link Location#getUuid() UUID}
  * @return the existing node; never null
  * @throws RepositoryException if there is an error working with the session
  * @throws PathNotFoundException if the node could not be found by its path
  */
 public Node node(Location location) throws RepositoryException {
   Node root = session.getRootNode();
   UUID uuid = location.getUuid();
   if (uuid != null) {
     try {
       return session.getNodeByIdentifier(uuid.toString());
     } catch (ItemNotFoundException e) {
       if (!location.hasPath()) {
         String msg = JcrConnectorI18n.unableToFindNodeWithUuid.text(getSourceName(), uuid);
         throw new PathNotFoundException(
             location, factories.getPathFactory().createRootPath(), msg);
       }
       // Otherwise, try to find it by its path ...
     }
   }
   if (location.hasPath()) {
     Path relativePath = location.getPath().relativeToRoot();
     ValueFactory<String> stringFactory = factories.getStringFactory();
     String relativePathStr = stringFactory.create(relativePath);
     try {
       return root.getNode(relativePathStr);
     } catch (javax.jcr.PathNotFoundException e) {
       // Figure out the lowest existing path ...
       Node node = root;
       for (Path.Segment segment : relativePath) {
         try {
           node = node.getNode(stringFactory.create(segment));
         } catch (javax.jcr.PathNotFoundException e2) {
           String pathStr = stringFactory.create(location.getPath());
           Path lowestPath = factories.getPathFactory().create(node.getPath());
           throw new PathNotFoundException(
               location,
               lowestPath,
               JcrConnectorI18n.nodeDoesNotExist.text(
                   getSourceName(), session.getWorkspace().getName(), pathStr));
         }
       }
     }
   }
   // Otherwise, we can't find the node ...
   String msg =
       JcrConnectorI18n.unableToFindNodeWithoutPathOrUuid.text(getSourceName(), location);
   throw new IllegalArgumentException(msg);
 }
Example #10
0
 /**
  * Create a request to create a node with the given properties under the supplied location.
  *
  * @param parentLocation the location of the existing parent node, under which the new child
  *     should be created
  * @param workspaceName the name of the workspace containing the parent
  * @param childName the name of the new child to create under the existing parent
  * @param properties the properties of the new node, which should include any {@link
  *     Location#getIdProperties() identification properties} for the new node
  * @param conflictBehavior the expected behavior if an equivalently-named child already exists
  *     under the <code>into</code> location
  * @throws IllegalArgumentException if the location, workspace name, child name, or the conflict
  *     behavior is null
  */
 public CreateNodeRequest(
     Location parentLocation,
     String workspaceName,
     Name childName,
     NodeConflictBehavior conflictBehavior,
     Property... properties) {
   CheckArg.isNotNull(parentLocation, "parentLocation");
   CheckArg.isNotNull(workspaceName, "workspaceName");
   CheckArg.isNotNull(conflictBehavior, "conflictBehavior");
   CheckArg.isNotNull(childName, "childName");
   this.under = parentLocation;
   this.workspaceName = workspaceName;
   this.childName = childName;
   this.conflictBehavior = conflictBehavior;
   int number = properties.length + (under.hasIdProperties() ? under.getIdProperties().size() : 0);
   List<Property> props = new ArrayList<Property>(number);
   for (Property property : properties) {
     if (property != null) props.add(property);
   }
   this.properties = Collections.unmodifiableList(props);
 }
Example #11
0
 /**
  * {@inheritDoc}
  *
  * @see org.modeshape.graph.request.ChangeRequest#changes(java.lang.String,
  *     org.modeshape.graph.property.Path)
  */
 @Override
 public boolean changes(String workspace, Path path) {
   return this.workspaceName.equals(workspace)
       && under.hasPath()
       && under.getPath().isAtOrBelow(path);
 }
Example #12
0
 @Test
 public void shouldRepeatedlyFindRootNodeByLocationWithoutPath() throws Exception {
   AbstractJcrNode root = cache.findJcrRootNode();
   AbstractJcrNode root2 = cache.findJcrNode(Location.create(root.location.getIdProperties()));
   assertThat(root2, is(sameInstance(root)));
 }
Example #13
0
 @Test
 public void shouldRepeatedlyFindNodeByLocationWithoutPath() throws Exception {
   AbstractJcrNode hybrid = cache.findJcrNode(null, path("/Cars/Hybrid"));
   AbstractJcrNode hybrid2 = cache.findJcrNode(Location.create(hybrid.location.getIdProperties()));
   assertThat(hybrid2, is(sameInstance(hybrid)));
 }
Example #14
0
 protected final String readable(Location location) {
   return location.getString(context.getNamespaceRegistry());
 }
Example #15
0
  protected JcrRepository doCreateJcrRepository(String repositoryName)
      throws RepositoryException, PathNotFoundException {
    RepositoryConnectionFactory connectionFactory = getRepositoryConnectionFactory();
    Map<String, String> descriptors = new HashMap<String, String>();
    Map<Option, String> options = new HashMap<Option, String>();

    // Read the subgraph that represents the repository ...
    PathFactory pathFactory = getExecutionContext().getValueFactories().getPathFactory();
    Path repositoriesPath =
        pathFactory.create(configuration.getPath(), ModeShapeLexicon.REPOSITORIES);
    Path repositoryPath = pathFactory.create(repositoriesPath, repositoryName);
    Name repoName =
        getExecutionContext().getValueFactories().getNameFactory().create(repositoryName);
    Graph configuration = null;
    Subgraph subgraph = getConfigurationSubgraph(false);

    // Read the options ...
    Path optionsPath =
        pathFactory.createRelativePath(
            ModeShapeLexicon.REPOSITORIES, repoName, ModeShapeLexicon.OPTIONS);
    Node optionsNode = subgraph.getNode(optionsPath);
    if (optionsNode != null) {
      for (Location optionLocation : optionsNode.getChildren()) {
        Node optionNode = subgraph.getNode(optionLocation);
        Path.Segment segment = optionLocation.getPath().getLastSegment();
        Property valueProperty = optionNode.getProperty(ModeShapeLexicon.VALUE);
        if (valueProperty == null) {
          log.warn(JcrI18n.noOptionValueProvided, segment.getName().getLocalName());
          continue;
        }
        Option option = Option.findOption(segment.getName().getLocalName());
        if (option == null) {
          log.warn(JcrI18n.invalidOptionProvided, segment.getName().getLocalName());
          continue;
        }
        options.put(option, valueProperty.getFirstValue().toString());
      }
    }

    // Disable the derived content removal option if not explicitly set and no sequencers ...
    if (!options.containsKey(Option.REMOVE_DERIVED_CONTENT_WITH_ORIGINAL)
        && getSequencingService().getSequencers().isEmpty()) {
      options.put(Option.REMOVE_DERIVED_CONTENT_WITH_ORIGINAL, Boolean.FALSE.toString());
    }

    // Read the descriptors ...
    Path descriptorsPath =
        pathFactory.createRelativePath(
            ModeShapeLexicon.REPOSITORIES, repoName, ModeShapeLexicon.DESCRIPTORS);
    Node descriptorsNode = subgraph.getNode(descriptorsPath);
    if (descriptorsNode != null) {
      for (Location descriptorLocation : descriptorsNode.getChildren()) {
        Node optionNode = subgraph.getNode(descriptorLocation);
        Path.Segment segment = descriptorLocation.getPath().getLastSegment();
        Property valueProperty = optionNode.getProperty(ModeShapeLexicon.VALUE);
        if (valueProperty == null) continue;
        descriptors.put(segment.getName().getLocalName(), valueProperty.getFirstValue().toString());
      }
    }

    // Read the namespaces ...
    ExecutionContext context = getExecutionContext();
    Path namespacesPath =
        pathFactory.createRelativePath(
            ModeShapeLexicon.REPOSITORIES, repoName, ModeShapeLexicon.NAMESPACES);
    Node namespacesNode = subgraph.getNode(namespacesPath);
    descriptors.put(org.modeshape.jcr.api.Repository.REPOSITORY_NAME, repositoryName);
    if (namespacesNode != null) {
      configuration = getConfigurationGraph();
      GraphNamespaceRegistry registry =
          new GraphNamespaceRegistry(
              configuration,
              namespacesNode.getLocation().getPath(),
              ModeShapeLexicon.URI,
              ModeShapeLexicon.GENERATED);
      context = context.with(registry);
    }

    // Get the name of the source ...
    Path repoPath = pathFactory.createRelativePath(ModeShapeLexicon.REPOSITORIES, repoName);
    Node repoNode = subgraph.getNode(repoPath);
    if (repoNode == null) {
      // There is no repository with the supplied name ...
      throw new PathNotFoundException(
          Location.create(repoPath),
          repositoriesPath,
          JcrI18n.repositoryDoesNotExist.text(readable(repoName)));
    }
    Property property = repoNode.getProperty(ModeShapeLexicon.SOURCE_NAME);
    if (property == null || property.isEmpty()) {
      if (configuration == null) configuration = getConfigurationGraph();
      String readableName = readable(ModeShapeLexicon.SOURCE_NAME);
      String readablePath = readable(subgraph.getLocation());
      String msg =
          JcrI18n.propertyNotFoundOnNode.text(
              readableName, readablePath, configuration.getCurrentWorkspaceName());
      throw new RepositoryException(msg);
    }
    String sourceName =
        context.getValueFactories().getStringFactory().create(property.getFirstValue());

    // Verify the sourc exists ...
    RepositorySource source = getRepositorySource(sourceName);
    if (source == null) {
      throw new RepositoryException(
          JcrI18n.repositoryReferencesNonExistantSource.text(repositoryName, sourceName));
    }

    // Read the initial content ...
    String initialContentForNewWorkspaces = null;
    for (Location initialContentLocation : repoNode.getChildren(ModeShapeLexicon.INITIAL_CONTENT)) {
      Node initialContent = subgraph.getNode(initialContentLocation);
      if (initialContent == null) continue;

      // Determine where to load the initial content from ...
      Property contentReference = initialContent.getProperty(ModeShapeLexicon.CONTENT);
      if (contentReference == null || contentReference.isEmpty()) {
        if (configuration == null) configuration = getConfigurationGraph();
        String readableName = readable(ModeShapeLexicon.CONTENT);
        String readablePath = readable(initialContentLocation);
        String msg =
            JcrI18n.propertyNotFoundOnNode.text(
                readableName, readablePath, configuration.getCurrentWorkspaceName());
        throw new RepositoryException(msg);
      }
      String contentRef = string(contentReference.getFirstValue());

      // Determine which workspaces this should apply to ...
      Property workspaces = initialContent.getProperty(ModeShapeLexicon.WORKSPACES);
      if (workspaces == null || workspaces.isEmpty()) {
        if (configuration == null) configuration = getConfigurationGraph();
        String readableName = readable(ModeShapeLexicon.WORKSPACES);
        String readablePath = readable(initialContentLocation);
        String msg =
            JcrI18n.propertyNotFoundOnNode.text(
                readableName, readablePath, configuration.getCurrentWorkspaceName());
        throw new RepositoryException(msg);
      }

      // Load the initial content into a transient source ...
      XmlFileRepositorySource initialContentSource = new XmlFileRepositorySource();
      initialContentSource.setName("Initial content for " + repositoryName);
      initialContentSource.setContentLocation(contentRef);
      Graph initialContentGraph = Graph.create(initialContentSource, context);
      Graph sourceGraph = Graph.create(sourceName, connectionFactory, context);

      // And initialize the source with the content (if not already there) ...
      for (Object value : workspaces) {
        String workspaceName = string(value);
        if (workspaceName != null && workspaceName.trim().length() != 0) {
          // Load the content into the workspace with this name ...
          sourceGraph.useWorkspace(workspaceName);
          try {
            sourceGraph.merge(initialContentGraph);
          } catch (RuntimeException e) {
            throw new RepositoryException(
                JcrI18n.unableToImportInitialContent.text(readable(repoName), contentRef), e);
          }
        }
      }

      // Determine if this initial content should apply to new workspaces ...
      Property applyToNewWorkspaces =
          initialContent.getProperty(ModeShapeLexicon.APPLY_TO_NEW_WORKSPACES);
      if (applyToNewWorkspaces != null
          && !applyToNewWorkspaces.isEmpty()
          && isTrue(applyToNewWorkspaces.getFirstValue())) {
        initialContentForNewWorkspaces =
            contentRef; // may overwrite the value if seen more than once!
      }
    }

    // Find the capabilities ...
    RepositorySourceCapabilities capabilities = source.getCapabilities();
    // Create the repository ...
    JcrRepository repository =
        new JcrRepository(
            context,
            connectionFactory,
            sourceName,
            getRepositoryService().getRepositoryLibrary(),
            capabilities,
            descriptors,
            options,
            initialContentForNewWorkspaces);

    // Register all the the node types ...
    Path nodeTypesPath =
        pathFactory.createRelativePath(
            ModeShapeLexicon.REPOSITORIES, repoName, JcrLexicon.NODE_TYPES);
    Node nodeTypesNode = subgraph.getNode(nodeTypesPath);
    if (nodeTypesNode != null) {
      boolean needToRefreshSubgraph = false;
      if (configuration == null) configuration = getConfigurationGraph();

      // Expand any references to a CND file
      Property resourceProperty = nodeTypesNode.getProperty(ModeShapeLexicon.RESOURCE);
      if (resourceProperty != null) {
        ClassLoader classLoader = this.context.getClassLoader();
        for (Object resourceValue : resourceProperty) {
          String resources =
              this.context.getValueFactories().getStringFactory().create(resourceValue);

          for (String resource : resources.split("\\s*,\\s*")) {
            Graph.Batch batch = configuration.batch();
            GraphBatchDestination destination = new GraphBatchDestination(batch);

            Path nodeTypesAbsPath = pathFactory.create(repositoryPath, JcrLexicon.NODE_TYPES);
            CndImporter importer = new CndImporter(destination, nodeTypesAbsPath, true, false);
            InputStream is = IoUtil.getResourceAsStream(resource, classLoader, getClass());
            Problems cndProblems = new SimpleProblems();
            if (is == null) {
              String msg =
                  JcrI18n.unableToFindNodeTypeDefinitionsOnClasspathOrFileOrUrl.text(resource);
              throw new RepositoryException(msg);
            }
            try {
              importer.importFrom(is, cndProblems, resource);
              batch.execute();
              needToRefreshSubgraph = true;
            } catch (IOException ioe) {
              String msg = JcrI18n.errorLoadingNodeTypeDefintions.text(resource, ioe.getMessage());
              throw new RepositoryException(msg, ioe);
            }
            if (!cndProblems.isEmpty()) {
              // Add any warnings or information to this engine's list ...
              getProblems().addAll(cndProblems);
              if (cndProblems.hasErrors()) {
                String msg = null;
                Throwable cause = null;
                for (Problem problem : cndProblems) {
                  if (problem.getStatus() == Status.ERROR) {
                    msg = problem.getMessageString();
                    cause = problem.getThrowable();
                    break;
                  }
                }
                throw new RepositoryException(
                    JcrI18n.errorLoadingNodeTypeDefintions.text(resource, msg), cause);
              }
            }
          }
        }
      }

      // Load any namespaces from the configuration into the repository's context ...
      NamespaceRegistry repoRegistry = repository.getExecutionContext().getNamespaceRegistry();
      repoRegistry.register(configuration.getContext().getNamespaceRegistry().getNamespaces());

      // Re-read the subgraph, in case any new nodes were added
      Subgraph nodeTypesSubgraph = subgraph;
      if (needToRefreshSubgraph) {
        nodeTypesSubgraph =
            configuration.getSubgraphOfDepth(4).at(nodeTypesNode.getLocation().getPath());
      }

      repository
          .getRepositoryTypeManager()
          .registerNodeTypes(nodeTypesSubgraph, nodeTypesNode.getLocation(), false);
    }

    return repository;
  }