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 } }
public String getSource() { Property property = getProperty(ModeShapeLexicon.SOURCE_NAME); if (property != null && !property.isEmpty()) { return context.getValueFactories().getStringFactory().create(property.getFirstValue()); } return null; }
/** * {@inheritDoc} * * @see * org.modeshape.graph.request.processor.RequestProcessor#process(org.modeshape.graph.request.CreateNodeRequest) */ @Override public void process(CreateNodeRequest request) { if (request == null) return; try { Workspace workspace = workspaceFor(request.inWorkspace()); Node parent = workspace.node(request.under()); String childName = workspace.stringFor(request.named()); // Look for the primary type, if it was set on the request ... String primaryTypeName = null; for (Property property : request.properties()) { if (property.getName().equals(JcrLexicon.PRIMARY_TYPE)) { primaryTypeName = workspace.stringFor(property.getFirstValue()); break; } } // Create the child node ... Node child = null; if (primaryTypeName != null) { child = parent.addNode(childName, primaryTypeName); } else { child = parent.addNode(childName); } assert child != null; // And set all of the properties on the new node ... workspace.setProperties(child, request); // Set up the actual results on the request ... request.setActualLocationOfNode(workspace.locationFor(child)); } catch (Throwable e) { request.setError(e); } }
protected void setProperty(Node node, Property property, boolean isMultiValued) throws RepositoryException { Name name = property.getName(); if (name.equals(JcrLexicon.PRIMARY_TYPE)) return; if (name.equals(ModeShapeIntLexicon.NODE_DEFINITON)) return; if (name.equals(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES)) return; if (name.equals(JcrLexicon.MIXIN_TYPES)) { for (Object mixinVvalue : property.getValuesAsArray()) { String mixinTypeName = stringFor(mixinVvalue); node.addMixin(mixinTypeName); } return; } // Otherwise, just set the normal property. First determine the expected type ... String propertyName = stringFor(name); if (isMultiValued) { Value[] values = new Value[property.size()]; int index = 0; PropertyType propertyType = null; for (Object value : property) { if (value == null) continue; if (propertyType == null) propertyType = PropertyType.discoverType(value); values[index] = convertToJcrValue(propertyType, value); ++index; } node.setProperty(propertyName, values); } else { Object firstValue = property.getFirstValue(); PropertyType propertyType = PropertyType.discoverType(firstValue); Value value = convertToJcrValue(propertyType, firstValue); node.setProperty(propertyName, value); } }
/** * {@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); } } } }
public void setProperties(Node node, Iterable<Property> properties) throws RepositoryException { // Look for the internal property that ModeShape uses to track which properties are // multi-valued w/r/t JCR ... Set<Name> multiValued = null; for (Property property : properties) { if (property.getName().equals(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES)) { // Go through the properties and see which properties are multi-valued ... multiValued = getMultiValuedProperties(property); break; } } if (multiValued == null) multiValued = Collections.emptySet(); // Now set each of the properties ... for (Property property : properties) { setProperty(node, property, multiValued.contains(property.getName())); } }
/** * Add a request to update the property on the node at the supplied location. This request will * create the property if it does not yet exist. * * @param on the location of the node to be read * @param workspaceName the name of the workspace containing the node * @param property the new property on the node * @return this builder for method chaining; never null * @throws IllegalArgumentException if the location or workspace name is null or if there are no * properties to update */ public BatchRequestBuilder setProperty(Location on, String workspaceName, Property property) { // If there's a pending request ... if (pendingRequest != null) { // Compare the supplied location with that of the pending request if (pendingRequest.location.isSame(on)) { // They are the same location, so we can add the properties to the pending request ... pendingRequest.pendingProperties.put(property.getName(), property); return this; } // Not the exact same location, so push the existing pending request ... addPending(); } // Record this operation as a pending change ... pendingRequest = new NodeChange(on, workspaceName); pendingRequest.pendingProperties.put(property.getName(), property); return this; }
protected Map<Name, Property> load(File propertiesFile, ExecutionContext context) throws RepositorySourceException { if (!propertiesFile.exists() || !propertiesFile.canRead()) return NO_PROPERTIES_MAP; try { String content = IoUtil.read(propertiesFile); ValueFactories factories = context.getValueFactories(); PropertyFactory propFactory = context.getPropertyFactory(); Map<Name, Property> result = new HashMap<Name, Property>(); for (String line : StringUtil.splitLines(content)) { // Parse each line ... Property property = parse(line, factories, propFactory); if (property != null) { result.put(property.getName(), property); } } return result; } catch (IOException e) { throw new RepositorySourceException(sourceName, e); } }
protected void assertMatchesStore(AbstractJcrNode jcrNode) throws RepositoryException { // Find the corresponding session node ... Node<JcrNodePayload, JcrPropertyPayload> nodeInfo = cache.findNode(jcrNode.nodeId, jcrNode.path()); // And the graph node ... org.modeshape.graph.Node dnaNode = store.getNodeAt(jcrNode.location); assertThat(nodeInfo.getLocation(), is(dnaNode.getLocation())); Set<Name> propertyNames = nodeInfo.getPropertyNames(); for (Name propertyName : propertyNames) { PropertyInfo<JcrPropertyPayload> info = nodeInfo.getProperty(propertyName); assertThat(info.getName(), is(propertyName)); assertThat(info.getProperty().getName(), is(propertyName)); Property actual = dnaNode.getProperty(propertyName); if (actual != null) { assertThat(info.getProperty().size(), is(actual.size())); assertThat(info.getProperty().getValuesAsArray(), is(actual.getValuesAsArray())); } else { if (propertyName.equals(JcrLexicon.UUID)) { // check for a ModeShape UUID property ... actual = dnaNode.getProperty(ModeShapeLexicon.UUID); if (actual != null) { assertThat(info.getProperty().size(), is(actual.size())); assertThat(info.getProperty().getValuesAsArray(), is(actual.getValuesAsArray())); } else { fail("missing property \"" + propertyName + "\" on " + dnaNode); } } else if (propertyName.equals(JcrLexicon.PRIMARY_TYPE)) { // This is okay } else if (propertyName.equals(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES)) { // This is okay } else { fail("missing property \"" + propertyName + "\" on " + dnaNode); } } } }
protected void write(Property property, Writer stream, ValueFactory<String> strings) throws IOException { String name = strings.create(property.getName()); stream.append(encoder.encode(name)); if (property.isEmpty()) return; stream.append(" ("); PropertyType type = PropertyType.discoverType(property.getFirstValue()); stream.append(type.getName().toLowerCase()); stream.append(") "); if (property.isMultiple()) { stream.append('['); } boolean first = true; boolean quote = type == PropertyType.STRING; for (Object value : property) { if (first) first = false; else stream.append(", "); String str = null; if (value instanceof Binary) { str = StringUtil.getHexString(((Binary) value).getBytes()); } else { str = strings.create(value); } if (quote) { stream.append('"'); stream.append(quoter.encode(str)); stream.append('"'); } else { stream.append(str); } } if (property.isMultiple()) { stream.append(']'); } stream.append('\n'); stream.flush(); }
protected Set<Name> write( File propertiesFile, ExecutionContext context, Map<Name, Property> properties) throws RepositorySourceException { if (properties.isEmpty()) { if (propertiesFile.exists()) { // Delete the file ... propertiesFile.delete(); } return Collections.emptySet(); } Set<Name> names = new HashSet<Name>(); try { ValueFactory<String> strings = context.getValueFactories().getStringFactory(); Writer fileWriter = new FileWriter(propertiesFile); try { // Write the primary type first ... Property primaryType = properties.get(JcrLexicon.PRIMARY_TYPE); if (primaryType != null) { write(primaryType, fileWriter, strings); names.add(primaryType.getName()); } // Then write the mixin types ... Property mixinTypes = properties.get(JcrLexicon.MIXIN_TYPES); if (mixinTypes != null) { write(mixinTypes, fileWriter, strings); names.add(mixinTypes.getName()); } // Then write the UUID ... Property uuid = properties.get(JcrLexicon.UUID); if (uuid != null) { write(uuid, fileWriter, strings); names.add(uuid.getName()); } // Then all the others ... for (Property property : properties.values()) { if (property == primaryType || property == mixinTypes || property == uuid) continue; write(property, fileWriter, strings); names.add(property.getName()); } } finally { fileWriter.close(); } } catch (IOException e) { throw new RepositorySourceException(sourceName, e); } return names; }
/** * {@inheritDoc} * * @see * org.modeshape.graph.request.processor.RequestProcessor#process(org.modeshape.graph.request.UpdatePropertiesRequest) */ @Override public void process(UpdatePropertiesRequest request) { if (request == null) return; try { Workspace workspace = workspaceFor(request.inWorkspace()); Node node = workspace.node(request.on()); Set<Name> newProperties = new HashSet<Name>(); for (Map.Entry<Name, Property> entry : request.properties().entrySet()) { Name propertyName = entry.getKey(); String name = workspace.stringFor(propertyName); Property property = entry.getValue(); // We need to remove the existing property (if there is one) in case the // old property has a different cardinality than the new property ... javax.jcr.Property existing = node.hasProperty(name) ? node.getProperty(name) : null; if (existing != null && (property == null || existing.getDefinition().isMultiple() == property.isSingle())) { // Remove the property ... if (!existing.getDefinition().isProtected()) { existing.remove(); } } if (property != null) { if (property.size() == 1) { // Try setting as a single-valued property ... try { workspace.setProperty(node, property, false); } catch (ValueFormatException e) { workspace.setProperty(node, property, true); } } else { // Set as a multi-valued property ... workspace.setProperty(node, property, true); } if (existing == null) newProperties.add(propertyName); } } if (request.removeOtherProperties()) { Set<String> stringNames = new HashSet<String>(); for (Name name : request.properties().keySet()) { stringNames.add(workspace.stringFor(name)); } stringNames.add(workspace.stringFor(JcrLexicon.PRIMARY_TYPE)); stringNames.add(workspace.stringFor(JcrLexicon.MIXIN_TYPES)); PropertyIterator propertyIter = node.getProperties(); while (propertyIter.hasNext()) { javax.jcr.Property property = propertyIter.nextProperty(); if (!stringNames.contains(property.getName()) && !property.getDefinition().isProtected()) { property.remove(); } } } // Set up the actual results on the request ... request.setActualLocationOfNode(workspace.locationFor(node)); request.setNewProperties(newProperties); } catch (Throwable e) { request.setError(e); } }
/** * Add a property that was read from the {@link RepositoryConnection} * * @param properties the properties that were read * @throws IllegalArgumentException if the property is null * @throws IllegalStateException if the request is frozen */ public void addProperties(Iterable<Property> properties) { checkNotFrozen(); for (Property property : properties) { this.properties.put(property.getName(), property); } }
/** * Add a property that was read from the {@link RepositoryConnection} * * @param property the property that was read * @return the previous property that had the same name, or null if there was no * previously-recorded property with the same name * @throws IllegalArgumentException if the property is null * @throws IllegalStateException if the request is frozen */ public Property addProperty(Property property) { checkNotFrozen(); return this.properties.put(property.getName(), property); }
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; }