Esempio n. 1
0
  /** @return descriptors */
  public Map<String, Object> initDescriptors() {
    ValueFactories factories = this.getExecutionContext().getValueFactories();
    descriptors.put(Repository.SPEC_NAME_DESC, valueFor(factories, JcrI18n.SPEC_NAME_DESC.text()));
    descriptors.put(Repository.SPEC_VERSION_DESC, valueFor(factories, "2.0"));

    if (!descriptors.containsKey(Repository.REP_NAME_DESC)) {
      descriptors.put(
          Repository.REP_NAME_DESC,
          valueFor(factories, JcrRepository.getBundleProperty(Repository.REP_NAME_DESC, true)));
    }
    if (!descriptors.containsKey(Repository.REP_VENDOR_DESC)) {
      descriptors.put(
          Repository.REP_VENDOR_DESC,
          valueFor(factories, JcrRepository.getBundleProperty(Repository.REP_VENDOR_DESC, true)));
    }
    if (!descriptors.containsKey(Repository.REP_VENDOR_URL_DESC)) {
      descriptors.put(
          Repository.REP_VENDOR_URL_DESC,
          valueFor(
              factories, JcrRepository.getBundleProperty(Repository.REP_VENDOR_URL_DESC, true)));
    }
    if (!descriptors.containsKey(Repository.REP_VERSION_DESC)) {
      descriptors.put(Repository.REP_VERSION_DESC, valueFor(factories, getEngineVersion()));
    }
    return descriptors;
  }
  private void assertContentInWorkspace(
      JcrRepository newRepository, String workspaceName, String... paths)
      throws RepositoryException {
    JcrSession session =
        workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();

    try {
      session.getRootNode();
      session.getNode("/Cars");
      session.getNode("/Cars/Hybrid");
      session.getNode("/Cars/Hybrid/Toyota Prius");
      session.getNode("/Cars/Hybrid/Toyota Highlander");
      session.getNode("/Cars/Hybrid/Nissan Altima");
      session.getNode("/Cars/Sports/Aston Martin DB9");
      session.getNode("/Cars/Sports/Infiniti G37");
      session.getNode("/Cars/Luxury/Cadillac DTS");
      session.getNode("/Cars/Luxury/Bentley Continental");
      session.getNode("/Cars/Luxury/Lexus IS350");
      session.getNode("/Cars/Utility/Land Rover LR2");
      session.getNode("/Cars/Utility/Land Rover LR3");
      session.getNode("/Cars/Utility/Hummer H3");
      session.getNode("/Cars/Utility/Ford F-150");
      session.getNode("/Cars/Utility/Toyota Land Cruiser");
      for (String path : paths) {
        session.getNode(path);
      }
    } finally {
      session.logout();
    }
  }
  @Test
  public void shouldBackupRepositoryWithMultipleWorkspaces() throws Exception {
    loadContent();
    Problems problems =
        session().getWorkspace().getRepositoryManager().backupRepository(backupDirectory);
    assertNoProblems(problems);

    // Make some changes that will not be in the backup ...
    session().getRootNode().addNode("node-not-in-backup");
    session().save();

    assertContentInWorkspace(repository(), "default", "/node-not-in-backup");
    assertContentInWorkspace(repository(), "ws2");
    assertContentInWorkspace(repository(), "ws3");

    // Start up a new repository
    ((LocalEnvironment) environment).setShared(true);
    RepositoryConfiguration config =
        RepositoryConfiguration.read("config/restore-repo-config.json").with(environment);
    JcrRepository newRepository = new JcrRepository(config);
    try {
      newRepository.start();

      // And restore it from the contents ...
      JcrSession newSession = newRepository.login();
      try {
        Problems restoreProblems =
            newSession.getWorkspace().getRepositoryManager().restoreRepository(backupDirectory);
        assertNoProblems(restoreProblems);
      } finally {
        newSession.logout();
      }

      // Check that the node that was added *after* the backup is not there ...
      assertContentNotInWorkspace(newRepository, "default", "/node-not-in-backup");

      // Before we assert the content, create a backup of it (for comparison purposes when
      // debugging) ...
      newSession = newRepository.login();
      try {
        Problems backupProblems =
            newSession.getWorkspace().getRepositoryManager().backupRepository(backupDirectory2);
        assertNoProblems(backupProblems);
      } finally {
        newSession.logout();
      }

      assertWorkspaces(newRepository, "default", "ws2", "ws3");

      assertContentInWorkspace(newRepository, null);
      assertContentInWorkspace(newRepository, "ws2");
      assertContentInWorkspace(newRepository, "ws3");
      queryContentInWorkspace(newRepository, null);
    } finally {
      newRepository.shutdown().get(10, TimeUnit.SECONDS);
    }
  }
Esempio n. 4
0
 @Before
 public void beforeEach() throws Exception {
   config = new RepositoryConfiguration("repoName");
   repository = new JcrRepository(config);
   repository.start();
   SessionCache systemCache =
       repository.createSystemSession(repository.runningState().context(), false);
   system = new SystemContent(systemCache);
 }
Esempio n. 5
0
 @Test
 public void shouldStoreNodeTypeDefinitionsInSystemCatalog() {
   Collection<JcrNodeType> nodeTypes =
       repository.nodeTypeManager().getNodeTypes().getAllNodeTypes();
   for (int i = 0; i != 3; ++i) {
     system.store(nodeTypes, true);
     assertThat(repository.nodeTypeManager().refreshFromSystem(), is(true));
   }
 }
Esempio n. 6
0
 public synchronized void cleanUpLocks() {
   // only need to do this on repositories that have been used; i.e., not including
   // just-initialized repositories
   if (repository != null) {
     try {
       repository.getRepositoryLockManager().cleanUpLocks();
     } catch (Throwable t) {
       getLogger().error(t, JcrI18n.errorCleaningUpLocks, repository.getRepositorySourceName());
     }
   }
 }
Esempio n. 7
0
  private void fireSequencingEvent(
      AbstractJcrNode sequencedNode,
      List<AbstractJcrNode> outputNodes,
      JcrSession outputSession,
      String sequencerName)
      throws RepositoryException {

    RecordingChanges sequencingChanges =
        new RecordingChanges(
            outputSession.context().getProcessId(),
            outputSession.getRepository().repositoryKey(),
            outputSession.workspaceName());
    for (AbstractJcrNode outputNode : outputNodes) {
      sequencingChanges.nodeSequenced(
          sequencedNode.key(),
          sequencedNode.path(),
          outputNode.key(),
          outputNode.path(),
          work.getOutputPath(),
          work.getUserId(),
          work.getSelectedPath(),
          sequencerName);
    }

    repository.changeBus().notify(sequencingChanges);
  }
Esempio n. 8
0
 @After
 public void afterEach() throws Exception {
   try {
     repository.shutdown().get(3L, TimeUnit.SECONDS);
   } finally {
     repository = null;
     config = null;
   }
 }
  private void assertContentNotInWorkspace(
      JcrRepository newRepository, String workspaceName, String... paths)
      throws RepositoryException {
    JcrSession session =
        workspaceName != null ? newRepository.login(workspaceName) : newRepository.login();

    try {
      session.getRootNode();
      for (String path : paths) {
        try {
          session.getNode(path);
          fail("Should not have found '" + path + "'");
        } catch (PathNotFoundException e) {
          // expected
        }
      }
    } finally {
      session.logout();
    }
  }
 private void queryContentInWorkspace(JcrRepository newRepository, String workspaceName)
     throws RepositoryException {
   JcrSession session = newRepository.login();
   try {
     String statement = "SELECT [car:model], [car:year], [car:msrp] FROM [car:Car] AS car";
     Query query = session.getWorkspace().getQueryManager().createQuery(statement, Query.JCR_SQL2);
     QueryResult results = query.execute();
     assertThat(results.getRows().getSize(), is(13L));
   } finally {
     session.logout();
   }
 }
Esempio n. 11
0
 @Test
 public void shouldReadNodeTypeDefinitionsFromSystemCatalog() {
   NodeTypes nodeTypes = repository.nodeTypeManager().getNodeTypes();
   Set<Name> builtInNodeTypes = new HashSet<Name>(nodeTypes.getAllNodeTypeNames());
   for (NodeTypeDefinition type : system.readAllNodeTypes()) {
     Name name = name(type.getName());
     JcrNodeType actual = nodeTypes.getNodeType(name);
     assertThat(
         "Did not find actual node type for name \"" + type.getName() + "\"",
         actual,
         is(notNullValue()));
     assertThat(builtInNodeTypes.remove(name), is(true));
   }
   assertThat(builtInNodeTypes.isEmpty(), is(true));
 }
Esempio n. 12
0
 public synchronized void close() {
   if (future != null) {
     try {
       future.cancel(false);
     } finally {
       future = null;
     }
   }
   if (repository != null) {
     try {
       repository.close();
     } finally {
       repository = null;
     }
   }
 }
  private void assertWorkspaces(JcrRepository newRepository, String... workspaceNames)
      throws RepositoryException {
    Set<String> expectedNames = new HashSet<String>();
    for (String expectedName : workspaceNames) {
      expectedNames.add(expectedName);
    }

    Set<String> actualNames = new HashSet<String>();
    JcrSession session = newRepository.login();
    try {
      for (String actualName : session.getWorkspace().getAccessibleWorkspaceNames()) {
        actualNames.add(actualName);
      }
    } finally {
      session.logout();
    }

    assertThat(actualNames, is(expectedNames));
  }
Esempio n. 14
0
 private void fireSequencingFailureEvent(
     AbstractJcrNode sequencedNode, JcrSession inputSession, Throwable cause, String sequencerName)
     throws RepositoryException {
   assert sequencedNode != null;
   assert inputSession != null;
   RecordingChanges sequencingChanges =
       new RecordingChanges(
           inputSession.context().getProcessId(),
           inputSession.getRepository().repositoryKey(),
           inputSession.workspaceName());
   sequencingChanges.nodeSequencingFailure(
       sequencedNode.key(),
       sequencedNode.path(),
       work.getOutputPath(),
       work.getUserId(),
       work.getSelectedPath(),
       sequencerName,
       cause);
   repository.changeBus().notify(sequencingChanges);
 }
Esempio n. 15
0
 private final Name name(String name) {
   return repository.runningState().context().getValueFactories().getNameFactory().create(name);
 }
Esempio n. 16
0
  @Override
  public void run() {
    JcrSession inputSession = null;
    JcrSession outputSession = null;
    final RunningState state = repository.runningState();
    final RepositoryStatistics stats = state.statistics();
    Sequencer sequencer = null;
    String sequencerName = null;
    try {
      // Create the required session(s) ...
      inputSession = state.loginInternalSession(work.getInputWorkspaceName());
      if (work.getOutputWorkspaceName() != null
          && !work.getOutputWorkspaceName().equals(work.getInputWorkspaceName())) {
        outputSession = state.loginInternalSession(work.getOutputWorkspaceName());
      } else {
        outputSession = inputSession;
      }

      // Get the sequencer ...
      sequencer = state.sequencers().getSequencer(work.getSequencerId());
      if (sequencer == null) return;
      sequencerName = sequencer.getName();

      // Find the selected node ...
      AbstractJcrNode selectedNode = inputSession.getNode(work.getSelectedPath());

      // Find the input that has changed and is to be sequenced ...
      Item inputItem = inputSession.getItem(work.getInputPath());
      Property changedProperty = null;
      if (inputItem instanceof Property) {
        changedProperty = (Property) inputItem;
      } else {
        Node changedNode = (Node) inputItem;
        // now look for a property that was changed or added ...
        changedProperty = changedNode.getProperty(work.getChangedPropertyName());
      }
      assert changedProperty != null;

      if (sequencer.hasAcceptedMimeTypes()) {
        // Get the MIME type, first by looking at the changed property's parent node
        // (or grand-parent node if parent is 'jcr:content') ...
        Node parent = changedProperty.getParent();
        String mimeType = null;
        if (parent.hasProperty(JcrConstants.JCR_MIME_TYPE)) {
          // The parent node has a 'jcr:mimeType' node ...
          Property property = parent.getProperty(JcrConstants.JCR_MIME_TYPE);
          if (!property.isMultiple()) {
            // The standard 'jcr:mimeType' property is single valued, but we're technically not
            // checking if
            // the property has that particular property definition (only by name) ...
            mimeType = property.getString();
          }
        } else if (parent.getName().equals(JcrConstants.JCR_CONTENT)) {
          // There is no 'jcr:mimeType' property, and since the sequenced property is on the
          // 'jcr:content' node,
          // get the parent (probably 'nt:file') node and look for the 'jcr:mimeType' property there
          // ...
          try {
            parent = parent.getParent();
            if (parent.hasProperty(JcrConstants.JCR_MIME_TYPE)) {
              Property property = parent.getProperty(JcrConstants.JCR_MIME_TYPE);
              if (!property.isMultiple()) {
                // The standard 'jcr:mimeType' property is single valued, but we're technically not
                // checking if
                // the property has that particular property definition (only by name) ...
                mimeType = property.getString();
              }
            }
          } catch (ItemNotFoundException e) {
            // must be the root ...
          }
        }
        if (mimeType == null
            && !changedProperty.isMultiple()
            && changedProperty.getType() == PropertyType.BINARY) {
          // Still don't know the MIME type of the property, so if it's a BINARY property we can
          // check it ...
          javax.jcr.Binary binary = changedProperty.getBinary();
          if (binary instanceof org.modeshape.jcr.api.Binary) {
            mimeType = ((org.modeshape.jcr.api.Binary) binary).getMimeType(parent.getName());
          }
        }

        // See if the sequencer accepts the MIME type ...
        if (mimeType != null && !sequencer.isAccepted(mimeType)) {
          return; // nope
        }
      }

      AbstractJcrNode outputNode = null;
      String primaryType = null;
      if (work.getSelectedPath().equals(work.getOutputPath())) {
        // The output is to go directly under the sequenced node ...
        outputNode =
            selectedNode.getName().equals(JcrConstants.JCR_CONTENT)
                ? selectedNode.getParent()
                : selectedNode;
        primaryType = selectedNode.getPrimaryNodeType().getName();
      } else {
        // Find the parent of the output if it exists, or create the node(s) along the path if not
        // ...
        Node parentOfOutput = null;
        try {
          parentOfOutput = outputSession.getNode(work.getOutputPath());
        } catch (PathNotFoundException e) {
          JcrTools tools = new JcrTools();
          parentOfOutput = tools.findOrCreateNode(outputSession, work.getOutputPath());
        }

        // Now determine the name of top node in the output, using the last segment of the selected
        // path ...
        String outputNodeName = computeOutputNodeName(selectedNode);

        // Remove any existing output (from a prior sequencing run on this same input) ...
        removeExistingOutputNodes(parentOfOutput, outputNodeName, work.getSelectedPath());

        // Create the output node
        if (parentOfOutput.isNew() && parentOfOutput.getName().equals(outputNodeName)) {
          // avoid creating a duplicate path with the same name
          outputNode = (AbstractJcrNode) parentOfOutput;
        } else {
          outputNode =
              (AbstractJcrNode)
                  parentOfOutput.addNode(outputNodeName, JcrConstants.NT_UNSTRUCTURED);
        }

        // and make sure the output node has the 'mode:derived' mixin ...
        outputNode.addMixin(DERIVED_NODE_TYPE_NAME);
        outputNode.setProperty(DERIVED_FROM_PROPERTY_NAME, work.getSelectedPath());
      }

      // Execute the sequencer ...
      DateTime now = outputSession.dateFactory().create();
      Sequencer.Context context =
          new SequencingContext(
              now, outputSession.getValueFactory(), outputSession.context().getMimeTypeDetector());
      if (inputSession.isLive() && (inputSession == outputSession || outputSession.isLive())) {
        final long start = System.nanoTime();

        try {
          if (sequencer.execute(changedProperty, outputNode, context)) {
            // Make sure that the sequencer did not change the primary type of the selected node ..
            if (selectedNode == outputNode
                && !selectedNode.getPrimaryNodeType().getName().equals(primaryType)) {
              String msg =
                  RepositoryI18n.sequencersMayNotChangeThePrimaryTypeOfTheSelectedNode.text();
              throw new RepositoryException(msg);
            }

            // find the new nodes created by the sequencing before saving, so we can properly fire
            // the events
            List<AbstractJcrNode> outputNodes = findOutputNodes(outputNode);

            // set the createdBy property (if it applies) to the user which triggered the
            // sequencing, not the context
            // of the saving session
            setCreatedByIfNecessary(outputSession, outputNodes);

            // outputSession
            outputSession.save();

            // fire the sequencing event after save (hopefully by this time the transaction has been
            // committed)
            fireSequencingEvent(selectedNode, outputNodes, outputSession, sequencerName);

            long durationInNanos = System.nanoTime() - start;
            Map<String, String> payload = new HashMap<String, String>();
            payload.put("sequencerName", sequencer.getClass().getName());
            payload.put("sequencedPath", changedProperty.getPath());
            payload.put("outputPath", outputNode.getPath());
            stats.recordDuration(
                DurationMetric.SEQUENCER_EXECUTION_TIME,
                durationInNanos,
                TimeUnit.NANOSECONDS,
                payload);
          }
        } catch (Throwable t) {
          fireSequencingFailureEvent(selectedNode, inputSession, t, sequencerName);
          // let it bubble down, because we still want to log it and update the stats
          throw t;
        }
      }
    } catch (Throwable t) {
      Logger logger = Logger.getLogger(getClass());
      if (work.getOutputWorkspaceName() != null) {
        logger.error(
            t,
            RepositoryI18n.errorWhileSequencingNodeIntoWorkspace,
            sequencerName,
            state.name(),
            work.getInputPath(),
            work.getInputWorkspaceName(),
            work.getOutputPath(),
            work.getOutputWorkspaceName());
      } else {
        logger.error(
            t,
            RepositoryI18n.errorWhileSequencingNode,
            sequencerName,
            state.name(),
            work.getInputPath(),
            work.getInputWorkspaceName(),
            work.getOutputPath());
      }
    } finally {
      stats.increment(ValueMetric.SEQUENCED_COUNT);
      stats.decrement(ValueMetric.SEQUENCER_QUEUE_SIZE);
      if (inputSession != null && inputSession.isLive()) inputSession.logout();
      if (outputSession != null && outputSession != inputSession && outputSession.isLive())
        outputSession.logout();
    }
  }
Esempio n. 17
0
  @SuppressWarnings("deprecation")
  @Test
  public void shouldAllowSpecifyingOptions() throws Exception {
    configuration
        .repositorySource("Source2")
        .usingClass(InMemoryRepositorySource.class.getName())
        .loadedFromClasspath()
        .setDescription("description")
        .and()
        .repository("JCR Repository")
        .setSource("Source2")
        .setOption(Option.JAAS_LOGIN_CONFIG_NAME, "test");

    engine = configuration.build();
    engine.start();

    // Verify that the graph has been updated correctly ...
    Graph config = engine.getGraph(JcrConfiguration.DEFAULT_CONFIGURATION_SOURCE_NAME);
    Subgraph subgraph = config.getSubgraphOfDepth(6).at("/");
    assertThat(subgraph.getNode("/mode:sources"), is(notNullValue()));
    assertThat(subgraph.getNode("/mode:sources/Source2"), is(notNullValue()));
    assertThat(
        subgraph.getNode("/mode:sources/Source2"),
        hasProperty(ModeShapeLexicon.CLASSNAME, InMemoryRepositorySource.class.getName()));
    assertThat(subgraph.getNode("/mode:repositories"), is(notNullValue()));
    assertThat(subgraph.getNode("/mode:repositories/JCR Repository"), is(notNullValue()));
    assertThat(
        subgraph.getNode("/mode:repositories/JCR Repository"),
        hasProperty(ModeShapeLexicon.SOURCE_NAME, "Source2"));
    assertThat(
        subgraph.getNode("/mode:repositories/JCR Repository/mode:options"), is(notNullValue()));
    assertThat(
        subgraph.getNode("/mode:repositories/JCR Repository/mode:options/JAAS_LOGIN_CONFIG_NAME"),
        hasProperty(ModeShapeLexicon.VALUE, "test"));

    JcrRepository repository = engine.getRepository("JCR Repository");

    Map<Option, String> options = new HashMap<Option, String>();
    options.put(Option.JAAS_LOGIN_CONFIG_NAME, "test");
    options.put(Option.PROJECT_NODE_TYPES, DefaultOption.PROJECT_NODE_TYPES);
    options.put(Option.READ_DEPTH, DefaultOption.READ_DEPTH);
    options.put(Option.INDEX_READ_DEPTH, DefaultOption.INDEX_READ_DEPTH);
    options.put(Option.ANONYMOUS_USER_ROLES, DefaultOption.ANONYMOUS_USER_ROLES);
    options.put(
        Option.TABLES_INCLUDE_COLUMNS_FOR_INHERITED_PROPERTIES,
        DefaultOption.TABLES_INCLUDE_COLUMNS_FOR_INHERITED_PROPERTIES);
    options.put(Option.QUERY_EXECUTION_ENABLED, DefaultOption.QUERY_EXECUTION_ENABLED);
    options.put(Option.QUERY_INDEX_DIRECTORY, DefaultOption.QUERY_INDEX_DIRECTORY);
    options.put(
        Option.QUERY_INDEXES_UPDATED_SYNCHRONOUSLY,
        DefaultOption.QUERY_INDEXES_UPDATED_SYNCHRONOUSLY);
    options.put(
        Option.PERFORM_REFERENTIAL_INTEGRITY_CHECKS,
        DefaultOption.PERFORM_REFERENTIAL_INTEGRITY_CHECKS);
    options.put(
        Option.EXPOSE_WORKSPACE_NAMES_IN_DESCRIPTOR,
        DefaultOption.EXPOSE_WORKSPACE_NAMES_IN_DESCRIPTOR);
    options.put(Option.VERSION_HISTORY_STRUCTURE, DefaultOption.VERSION_HISTORY_STRUCTURE);
    options.put(Option.REPOSITORY_JNDI_LOCATION, DefaultOption.REPOSITORY_JNDI_LOCATION);
    options.put(
        Option.USE_ANONYMOUS_ACCESS_ON_FAILED_LOGIN,
        DefaultOption.USE_ANONYMOUS_ACCESS_ON_FAILED_LOGIN);
    options.put(
        Option.REBUILD_QUERY_INDEX_ON_STARTUP, DefaultOption.REBUILD_QUERY_INDEX_ON_STARTUP);
    options.put(
        Option.QUERY_INDEXES_REBUILT_SYNCHRONOUSLY,
        DefaultOption.QUERY_INDEXES_REBUILT_SYNCHRONOUSLY);
    String defaultRemoveDerivedValue = DefaultOption.REMOVE_DERIVED_CONTENT_WITH_ORIGINAL;
    if (engine.getSequencingService().getSequencers().isEmpty()) {
      defaultRemoveDerivedValue = Boolean.FALSE.toString();
    }
    options.put(Option.REMOVE_DERIVED_CONTENT_WITH_ORIGINAL, defaultRemoveDerivedValue);
    options.put(
        Option.USE_SECURITY_CONTEXT_CREDENTIALS, DefaultOption.USE_SECURITY_CONTEXT_CREDENTIALS);
    assertThat(repository.getOptions(), is(options));
  }
Esempio n. 18
0
 /**
  * Get the version of this engine.
  *
  * @return version
  */
 public String getEngineVersion() {
   return JcrRepository.getBundleProperty(Repository.REP_VERSION_DESC, true);
 }
Esempio n. 19
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;
  }
Esempio n. 20
0
 public synchronized void terminateAllSessions() {
   // only need to do this on repositories that have been used; i.e., not including
   // just-initialized repositories
   if (repository != null) repository.terminateAllSessions();
 }