001 /*
002 * JBoss DNA (http://www.jboss.org/dna)
003 * See the COPYRIGHT.txt file distributed with this work for information
004 * regarding copyright ownership. Some portions may be licensed
005 * to Red Hat, Inc. under one or more contributor license agreements.
006 * See the AUTHORS.txt file in the distribution for a full listing of
007 * individual contributors.
008 *
009 * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
010 * is licensed to you under the terms of the GNU Lesser General Public License as
011 * published by the Free Software Foundation; either version 2.1 of
012 * the License, or (at your option) any later version.
013 *
014 * JBoss DNA is distributed in the hope that it will be useful,
015 * but WITHOUT ANY WARRANTY; without even the implied warranty of
016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
017 * Lesser General Public License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this software; if not, write to the Free
021 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
022 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
023 */
024 package org.jboss.dna.connector.federation;
025
026 import java.io.Serializable;
027 import java.lang.reflect.Method;
028 import java.util.ArrayList;
029 import java.util.Collections;
030 import java.util.HashSet;
031 import java.util.Iterator;
032 import java.util.LinkedList;
033 import java.util.List;
034 import java.util.Set;
035 import java.util.concurrent.CopyOnWriteArrayList;
036 import java.util.regex.Matcher;
037 import java.util.regex.Pattern;
038 import net.jcip.annotations.Immutable;
039 import org.jboss.dna.common.text.TextEncoder;
040 import org.jboss.dna.common.util.CheckArg;
041 import org.jboss.dna.common.util.HashCode;
042 import org.jboss.dna.common.util.Logger;
043 import org.jboss.dna.graph.ExecutionContext;
044 import org.jboss.dna.graph.connector.RepositorySource;
045 import org.jboss.dna.graph.property.NamespaceRegistry;
046 import org.jboss.dna.graph.property.Path;
047 import org.jboss.dna.graph.property.PathFactory;
048
049 /**
050 * A projection of content from a source into the integrated/federated repository. Each project consists of a set of {@link Rule
051 * rules} for a particular source, where each rule defines how content within a source is
052 * {@link Rule#getPathInRepository(Path, PathFactory) is project into the repository} and how the repository content is
053 * {@link Rule#getPathInSource(Path, PathFactory) projected into the source}. Different rule subclasses are used for different
054 * types.
055 *
056 * @author Randall Hauch
057 */
058 @Immutable
059 public class Projection implements Comparable<Projection>, Serializable {
060
061 /**
062 * Initial version
063 */
064 private static final long serialVersionUID = 1L;
065 protected static final List<Method> parserMethods;
066 static {
067 parserMethods = new CopyOnWriteArrayList<Method>();
068 try {
069 parserMethods.add(Projection.class.getDeclaredMethod("parsePathRule", String.class, ExecutionContext.class));
070 } catch (Throwable err) {
071 Logger.getLogger(Projection.class).error(err, FederationI18n.errorAddingProjectionRuleParseMethod);
072 }
073 }
074
075 /**
076 * Add a static method that can be used to parse {@link Rule#getString(NamespaceRegistry, TextEncoder) rule definition
077 * strings}. These methods must be static, must accept a {@link String} definition as the first parameter and an
078 * {@link ExecutionContext} environment reference as the second parameter, and should return the resulting {@link Rule} (or
079 * null if the definition format could not be understood by the method. Any exceptions during
080 * {@link Method#invoke(Object, Object...) invocation} will be logged at the
081 * {@link Logger#trace(Throwable, String, Object...) trace} level.
082 *
083 * @param method the method to be added
084 * @see #addRuleParser(ClassLoader, String, String)
085 */
086 public static void addRuleParser( Method method ) {
087 if (method != null) parserMethods.add(method);
088 }
089
090 /**
091 * Add a static method that can be used to parse {@link Rule#getString(NamespaceRegistry, TextEncoder) rule definition
092 * strings}. These methods must be static, must accept a {@link String} definition as the first parameter and an
093 * {@link ExecutionContext} environment reference as the second parameter, and should return the resulting {@link Rule} (or
094 * null if the definition format could not be understood by the method. Any exceptions during
095 * {@link Method#invoke(Object, Object...) invocation} will be logged at the
096 * {@link Logger#trace(Throwable, String, Object...) trace} level.
097 *
098 * @param classLoader the class loader that should be used to load the class on which the method is defined; may not be null
099 * @param className the name of the class on which the static method is defined; may not be null
100 * @param methodName the name of the method
101 * @throws SecurityException if there is a security exception while loading the class or getting the method
102 * @throws NoSuchMethodException if the method does not exist on the class
103 * @throws ClassNotFoundException if the class could not be found given the supplied class loader
104 * @throws IllegalArgumentException if the class loader reference is null, or if the class name or method name are null or
105 * empty
106 * @see #addRuleParser(Method)
107 */
108 public static void addRuleParser( ClassLoader classLoader,
109 String className,
110 String methodName ) throws SecurityException, NoSuchMethodException, ClassNotFoundException {
111 CheckArg.isNotNull(classLoader, "classLoader");
112 CheckArg.isNotEmpty(className, "className");
113 CheckArg.isNotEmpty(methodName, "methodName");
114 Class<?> clazz = Class.forName(className, true, classLoader);
115 parserMethods.add(clazz.getMethod(className, String.class, ExecutionContext.class));
116 }
117
118 /**
119 * Remove the rule parser method.
120 *
121 * @param method the method to remove
122 * @return true if the method was removed, or false if the method was not a registered rule parser method
123 */
124 public static boolean removeRuleParser( Method method ) {
125 return parserMethods.remove(method);
126 }
127
128 /**
129 * Remove the rule parser method.
130 *
131 * @param declaringClassName the name of the class on which the static method is defined; may not be null
132 * @param methodName the name of the method
133 * @return true if the method was removed, or false if the method was not a registered rule parser method
134 * @throws IllegalArgumentException if the class loader reference is null, or if the class name or method name are null or
135 * empty
136 */
137 public static boolean removeRuleParser( String declaringClassName,
138 String methodName ) {
139 CheckArg.isNotEmpty(declaringClassName, "declaringClassName");
140 CheckArg.isNotEmpty(methodName, "methodName");
141 for (Method method : parserMethods) {
142 if (method.getName().equals(methodName) && method.getDeclaringClass().getName().equals(declaringClassName)) {
143 return parserMethods.remove(method);
144 }
145 }
146 return false;
147 }
148
149 /**
150 * Parse the string form of a rule definition and return the rule
151 *
152 * @param definition the definition of the rule that is to be parsed
153 * @param context the environment in which this method is being executed; may not be null
154 * @return the rule, or null if the definition could not be parsed
155 */
156 public static Rule fromString( String definition,
157 ExecutionContext context ) {
158 CheckArg.isNotNull(context, "env");
159 definition = definition != null ? definition.trim() : "";
160 if (definition.length() == 0) return null;
161 for (Method method : parserMethods) {
162 try {
163 Rule rule = (Rule)method.invoke(null, definition, context);
164 if (rule != null) return rule;
165 } catch (Throwable err) {
166 String msg = "Error while parsing project rule definition \"{0}\" using {1}";
167 context.getLogger(Projection.class).trace(err, msg, definition, method);
168 }
169 }
170 return null;
171 }
172
173 /**
174 * Pattern that identifies the form:
175 *
176 * <pre>
177 * repository_path => source_path [$ exception ]*
178 * </pre>
179 *
180 * where the following groups are captured on the first call to {@link Matcher#find()}:
181 * <ol>
182 * <li><code>repository_path</code></li>
183 * <li><code>source_path</code></li>
184 * </ol>
185 * and the following groups are captured on subsequent calls to {@link Matcher#find()}:
186 * <ol>
187 * <li>exception</code></li>
188 * </ol>
189 * <p>
190 * The regular expression is:
191 *
192 * <pre>
193 * ((?:[ˆ=$]|=(?!>))+)(?:(?:=>((?:[ˆ=$]|=(?!>))+))( \$ (?:(?:[ˆ=]|=(?!>))+))*)?
194 * </pre>
195 *
196 * </p>
197 */
198 protected static final String PATH_RULE_PATTERN_STRING = "((?:[^=$]|=(?!>))+)(?:(?:=>((?:[^=$]|=(?!>))+))( \\$ (?:(?:[^=]|=(?!>))+))*)?";
199 protected static final Pattern PATH_RULE_PATTERN = Pattern.compile(PATH_RULE_PATTERN_STRING);
200
201 /**
202 * Parse the string definition of a {@link PathRule}. This method is automatically registered in the {@link #parserMethods
203 * parser methods} by the static initializer of {@link Projection}.
204 *
205 * @param definition the definition
206 * @param context the environment
207 * @return the path rule, or null if the definition is not in the right form
208 */
209 public static PathRule parsePathRule( String definition,
210 ExecutionContext context ) {
211 definition = definition != null ? definition.trim() : "";
212 if (definition.length() == 0) return null;
213 Matcher matcher = PATH_RULE_PATTERN.matcher(definition);
214 if (!matcher.find()) return null;
215 String reposPathStr = matcher.group(1);
216 String sourcePathStr = matcher.group(2);
217 if (reposPathStr == null || sourcePathStr == null) return null;
218 reposPathStr = reposPathStr.trim();
219 sourcePathStr = sourcePathStr.trim();
220 if (reposPathStr.length() == 0 || sourcePathStr.length() == 0) return null;
221 PathFactory pathFactory = context.getValueFactories().getPathFactory();
222 Path repositoryPath = pathFactory.create(reposPathStr);
223 Path sourcePath = pathFactory.create(sourcePathStr);
224
225 // Grab the exceptions ...
226 List<Path> exceptions = new LinkedList<Path>();
227 while (matcher.find()) {
228 String exceptionStr = matcher.group(1);
229 Path exception = pathFactory.create(exceptionStr);
230 exceptions.add(exception);
231 }
232 return new PathRule(repositoryPath, sourcePath, exceptions);
233 }
234
235 private final String sourceName;
236 private final String workspaceName;
237 private final List<Rule> rules;
238 private final boolean simple;
239 private final int hc;
240
241 /**
242 * Create a new federated projection for the supplied source, using the supplied rules.
243 *
244 * @param sourceName the name of the source
245 * @param workspaceName the name of the workspace in the source; may be null if the default workspace is to be used
246 * @param rules the projection rules
247 * @throws IllegalArgumentException if the source name or rule array is null, empty, or contains all nulls
248 */
249 public Projection( String sourceName,
250 String workspaceName,
251 Rule... rules ) {
252 CheckArg.isNotEmpty(sourceName, "sourceName");
253 CheckArg.isNotEmpty(rules, "rules");
254 this.sourceName = sourceName;
255 this.workspaceName = workspaceName;
256 List<Rule> rulesList = new ArrayList<Rule>();
257 for (Rule rule : rules) {
258 if (rule != null) rulesList.add(rule);
259 }
260 this.rules = Collections.unmodifiableList(rulesList);
261 CheckArg.isNotEmpty(this.rules, "rules");
262 this.simple = computeSimpleProjection(this.rules);
263 this.hc = HashCode.compute(this.sourceName, this.workspaceName);
264 }
265
266 /**
267 * Get the name of the source to which this projection applies.
268 *
269 * @return the source name
270 * @see RepositorySource#getName()
271 */
272 public String getSourceName() {
273 return sourceName;
274 }
275
276 /**
277 * Get the name of the workspace in the source to which this projection applies.
278 *
279 * @return the workspace name, or null if the default workspace of the {@link #getSourceName() source} is to be used
280 */
281 public String getWorkspaceName() {
282 return workspaceName;
283 }
284
285 /**
286 * Get the rules that define this projection.
287 *
288 * @return the unmodifiable list of immutable rules; never null
289 */
290 public List<Rule> getRules() {
291 return rules;
292 }
293
294 /**
295 * Get the paths in the source that correspond to the supplied path within the repository. This method computes the paths
296 * given all of the rules. In general, most sources will probably project a node onto a single repository node. However, some
297 * sources may be configured such that the same node in the repository is a projection of multiple nodes within the source.
298 *
299 * @param canonicalPathInRepository the canonical path of the node within the repository; may not be null
300 * @param factory the path factory; may not be null
301 * @return the set of unique paths in the source projected from the repository path; never null
302 * @throws IllegalArgumentException if the factory reference is null
303 */
304 public Set<Path> getPathsInSource( Path canonicalPathInRepository,
305 PathFactory factory ) {
306 CheckArg.isNotNull(factory, "factory");
307 assert canonicalPathInRepository == null ? true : canonicalPathInRepository.equals(canonicalPathInRepository.getCanonicalPath());
308 Set<Path> paths = new HashSet<Path>();
309 for (Rule rule : getRules()) {
310 Path pathInSource = rule.getPathInSource(canonicalPathInRepository, factory);
311 if (pathInSource != null) paths.add(pathInSource);
312 }
313 return paths;
314 }
315
316 /**
317 * Get the paths in the repository that correspond to the supplied path within the source. This method computes the paths
318 * given all of the rules. In general, most sources will probably project a node onto a single repository node. However, some
319 * sources may be configured such that the same node in the source is projected into multiple nodes within the repository.
320 *
321 * @param canonicalPathInSource the canonical path of the node within the source; may not be null
322 * @param factory the path factory; may not be null
323 * @return the set of unique paths in the repository projected from the source path; never null
324 * @throws IllegalArgumentException if the factory reference is null
325 */
326 public Set<Path> getPathsInRepository( Path canonicalPathInSource,
327 PathFactory factory ) {
328 CheckArg.isNotNull(factory, "factory");
329 assert canonicalPathInSource == null ? true : canonicalPathInSource.equals(canonicalPathInSource.getCanonicalPath());
330 Set<Path> paths = new HashSet<Path>();
331 for (Rule rule : getRules()) {
332 Path pathInRepository = rule.getPathInRepository(canonicalPathInSource, factory);
333 if (pathInRepository != null) paths.add(pathInRepository);
334 }
335 return paths;
336 }
337
338 /**
339 * Get the paths in the repository that serve as top-level nodes exposed by this projection.
340 *
341 * @param factory the path factory that can be used to create new paths; may not be null
342 * @return the list of top-level paths, in the proper order and containing no duplicates; never null
343 */
344 public List<Path> getTopLevelPathsInRepository( PathFactory factory ) {
345 CheckArg.isNotNull(factory, "factory");
346 List<Rule> rules = getRules();
347 Set<Path> uniquePaths = new HashSet<Path>();
348 List<Path> paths = new ArrayList<Path>(rules.size());
349 for (Rule rule : getRules()) {
350 for (Path path : rule.getTopLevelPathsInRepository(factory)) {
351 if (!uniquePaths.contains(path)) {
352 paths.add(path);
353 uniquePaths.add(path);
354 }
355 }
356 }
357 return paths;
358 }
359
360 /**
361 * Determine whether this project is a simple projection that only involves for any one repository path no more than a single
362 * source path.
363 *
364 * @return true if this projection is a simple projection, or false if the projection is not simple (or it cannot be
365 * determined if it is simple)
366 */
367 public boolean isSimple() {
368 return simple;
369 }
370
371 protected boolean computeSimpleProjection( List<Rule> rules ) {
372 // Get the set of repository paths for the rules, and see if they overlap ...
373 Set<Path> repositoryPaths = new HashSet<Path>();
374 for (Rule rule : rules) {
375 if (rule instanceof PathRule) {
376 PathRule pathRule = (PathRule)rule;
377 Path repoPath = pathRule.getPathInRepository();
378 if (!repositoryPaths.isEmpty()) {
379 if (repositoryPaths.contains(repoPath)) return false;
380 for (Path path : repositoryPaths) {
381 if (path.isAtOrAbove(repoPath)) return false;
382 if (repoPath.isAtOrAbove(path)) return false;
383 }
384 }
385 repositoryPaths.add(repoPath);
386 } else {
387 return false;
388 }
389 }
390 return true;
391 }
392
393 /**
394 * {@inheritDoc}
395 *
396 * @see java.lang.Object#hashCode()
397 */
398 @Override
399 public int hashCode() {
400 return this.hc;
401 }
402
403 /**
404 * {@inheritDoc}
405 *
406 * @see java.lang.Object#equals(java.lang.Object)
407 */
408 @Override
409 public boolean equals( Object obj ) {
410 if (obj == this) return true;
411 if (obj instanceof Projection) {
412 Projection that = (Projection)obj;
413 if (this.hashCode() != that.hashCode()) return false;
414 if (!this.getSourceName().equals(that.getSourceName())) return false;
415 if (!this.getWorkspaceName().equals(that.getWorkspaceName())) return false;
416 if (!this.getRules().equals(that.getRules())) return false;
417 return true;
418 }
419 return false;
420 }
421
422 /**
423 * {@inheritDoc}
424 *
425 * @see java.lang.Comparable#compareTo(java.lang.Object)
426 */
427 public int compareTo( Projection that ) {
428 if (this == that) return 0;
429 int diff = this.getSourceName().compareTo(that.getSourceName());
430 if (diff != 0) return diff;
431 diff = this.getWorkspaceName().compareTo(that.getWorkspaceName());
432 if (diff != 0) return diff;
433 Iterator<Rule> thisIter = this.getRules().iterator();
434 Iterator<Rule> thatIter = that.getRules().iterator();
435 while (thisIter.hasNext() && thatIter.hasNext()) {
436 diff = thisIter.next().compareTo(thatIter.next());
437 if (diff != 0) return diff;
438 }
439 if (thisIter.hasNext()) return 1;
440 if (thatIter.hasNext()) return -1;
441 return 0;
442 }
443
444 /**
445 * {@inheritDoc}
446 *
447 * @see java.lang.Object#toString()
448 */
449 @Override
450 public String toString() {
451 StringBuilder sb = new StringBuilder();
452 sb.append(this.sourceName);
453 sb.append("::");
454 sb.append(this.workspaceName);
455 sb.append(" { ");
456 boolean first = true;
457 for (Rule rule : this.getRules()) {
458 if (!first) sb.append(" ; ");
459 sb.append(rule.toString());
460 first = false;
461 }
462 sb.append(" }");
463 return sb.toString();
464 }
465
466 /**
467 * A rule used within a project do define how content within a source is projected into the federated repository. This mapping
468 * is bi-directional, meaning it's possible to determine
469 * <ul>
470 * <li>the path in repository given a path in source; and</li>
471 * <li>the path in source given a path in repository.</li>
472 * </ul>
473 *
474 * @author Randall Hauch
475 */
476 @Immutable
477 public static abstract class Rule implements Comparable<Rule> {
478
479 /**
480 * Get the paths in the repository that serve as top-level nodes exposed by this rule.
481 *
482 * @param factory the path factory that can be used to create new paths; may not be null
483 * @return the list of top-level paths, which are ordered and which must be unique; never null
484 */
485 public abstract List<Path> getTopLevelPathsInRepository( PathFactory factory );
486
487 /**
488 * Get the path in source that is projected from the supplied repository path, or null if the supplied repository path is
489 * not projected into the source.
490 *
491 * @param pathInRepository the path in the repository; may not be null
492 * @param factory the path factory; may not be null
493 * @return the path in source if it is projected by this rule, or null otherwise
494 */
495 public abstract Path getPathInSource( Path pathInRepository,
496 PathFactory factory );
497
498 /**
499 * Get the path in repository that is projected from the supplied source path, or null if the supplied source path is not
500 * projected into the repository.
501 *
502 * @param pathInSource the path in the source; may not be null
503 * @param factory the path factory; may not be null
504 * @return the path in repository if it is projected by this rule, or null otherwise
505 */
506 public abstract Path getPathInRepository( Path pathInSource,
507 PathFactory factory );
508
509 public abstract String getString( NamespaceRegistry registry,
510 TextEncoder encoder );
511
512 public abstract String getString( TextEncoder encoder );
513
514 public abstract String getString();
515 }
516
517 /**
518 * A rule that is defined with a single {@link #getPathInSource() path in source} and a single {@link #getPathInRepository()
519 * path in repository}, and which has a set of {@link #getExceptionsToRule() path exceptions} (relative paths below the path
520 * in source).
521 *
522 * @author Randall Hauch
523 */
524 @Immutable
525 public static class PathRule extends Rule {
526 /** The path of the content as known to the source */
527 private final Path sourcePath;
528 /** The path where the content is to be placed ("projected") into the repository */
529 private final Path repositoryPath;
530 /** The paths (relative to the source path) that identify exceptions to this rule */
531 private final List<Path> exceptions;
532 private final int hc;
533 private final List<Path> topLevelRepositoryPaths;
534
535 public PathRule( Path repositoryPath,
536 Path sourcePath ) {
537 this(repositoryPath, sourcePath, (Path[])null);
538 }
539
540 public PathRule( Path repositoryPath,
541 Path sourcePath,
542 Path... exceptions ) {
543 assert sourcePath != null;
544 assert repositoryPath != null;
545 this.sourcePath = sourcePath;
546 this.repositoryPath = repositoryPath;
547 if (exceptions == null || exceptions.length == 0) {
548 this.exceptions = Collections.emptyList();
549 } else {
550 List<Path> exceptionList = new ArrayList<Path>();
551 for (Path exception : exceptions) {
552 if (exception != null) exceptionList.add(exception);
553 }
554 this.exceptions = Collections.unmodifiableList(exceptionList);
555 }
556 this.hc = HashCode.compute(sourcePath, repositoryPath, exceptions);
557 assert exceptionPathsAreRelative();
558 this.topLevelRepositoryPaths = Collections.singletonList(getPathInRepository());
559 }
560
561 public PathRule( Path repositoryPath,
562 Path sourcePath,
563 List<Path> exceptions ) {
564 assert sourcePath != null;
565 assert repositoryPath != null;
566 this.sourcePath = sourcePath;
567 this.repositoryPath = repositoryPath;
568 if (exceptions == null || exceptions.isEmpty()) {
569 this.exceptions = Collections.emptyList();
570 } else {
571 this.exceptions = Collections.unmodifiableList(new ArrayList<Path>(exceptions));
572 }
573 this.hc = HashCode.compute(sourcePath, repositoryPath, exceptions);
574 assert exceptionPathsAreRelative();
575 this.topLevelRepositoryPaths = Collections.singletonList(getPathInRepository());
576 }
577
578 private boolean exceptionPathsAreRelative() {
579 if (this.exceptions != null) {
580 for (Path path : this.exceptions) {
581 if (path.isAbsolute()) return false;
582 }
583 }
584 return true;
585 }
586
587 /**
588 * The path where the content is to be placed ("projected") into the repository.
589 *
590 * @return the projected path of the content in the repository; never null
591 */
592 public Path getPathInRepository() {
593 return repositoryPath;
594 }
595
596 /**
597 * The path of the content as known to the source
598 *
599 * @return the source-specific path of the content; never null
600 */
601 public Path getPathInSource() {
602 return sourcePath;
603 }
604
605 /**
606 * Get whether this rule has any exceptions.
607 *
608 * @return true if this rule has exceptions, or false if it has none.
609 */
610 public boolean hasExceptionsToRule() {
611 return exceptions.size() != 0;
612 }
613
614 /**
615 * Get the paths that define the exceptions to this rule. These paths are always relative to the
616 * {@link #getPathInSource() path in source}.
617 *
618 * @return the unmodifiable exception paths; never null but possibly empty
619 */
620 public List<Path> getExceptionsToRule() {
621 return exceptions;
622 }
623
624 /**
625 * @param pathInSource
626 * @return true if the source path is included by this rule
627 */
628 protected boolean includes( Path pathInSource ) {
629 // Check whether the path is outside the source-specific path ...
630 if (pathInSource != null && this.sourcePath.isAtOrAbove(pathInSource)) {
631
632 // The path is inside the source-specific region, so check the exceptions ...
633 List<Path> exceptions = getExceptionsToRule();
634 if (exceptions.size() != 0) {
635 Path subpathInSource = pathInSource.relativeTo(this.sourcePath);
636 if (subpathInSource.size() != 0) {
637 for (Path exception : exceptions) {
638 if (subpathInSource.isAtOrBelow(exception)) return false;
639 }
640 }
641 }
642 return true;
643 }
644 return false;
645 }
646
647 /**
648 * {@inheritDoc}
649 *
650 * @see org.jboss.dna.connector.federation.Projection.Rule#getTopLevelPathsInRepository(org.jboss.dna.graph.property.PathFactory)
651 */
652 @Override
653 public List<Path> getTopLevelPathsInRepository( PathFactory factory ) {
654 return topLevelRepositoryPaths;
655 }
656
657 /**
658 * {@inheritDoc}
659 * <p>
660 * This method considers a path that is at or below the rule's {@link #getPathInSource() source path} to be included,
661 * except if there are {@link #getExceptionsToRule() exceptions} that explicitly disallow the path.
662 * </p>
663 *
664 * @see org.jboss.dna.connector.federation.Projection.Rule#getPathInSource(Path, PathFactory)
665 */
666 @Override
667 public Path getPathInSource( Path pathInRepository,
668 PathFactory factory ) {
669 assert pathInRepository.equals(pathInRepository.getCanonicalPath());
670 // Project the repository path into the equivalent source path ...
671 Path pathInSource = projectPathInRepositoryToPathInSource(pathInRepository, factory);
672
673 // Check whether the source path is included by this rule ...
674 return includes(pathInSource) ? pathInSource : null;
675 }
676
677 /**
678 * {@inheritDoc}
679 *
680 * @see org.jboss.dna.connector.federation.Projection.Rule#getPathInRepository(org.jboss.dna.graph.property.Path,
681 * org.jboss.dna.graph.property.PathFactory)
682 */
683 @Override
684 public Path getPathInRepository( Path pathInSource,
685 PathFactory factory ) {
686 assert pathInSource.equals(pathInSource.getCanonicalPath());
687 // Check whether the source path is included by this rule ...
688 if (!includes(pathInSource)) return null;
689
690 // Project the repository path into the equivalent source path ...
691 return projectPathInSourceToPathInRepository(pathInSource, factory);
692 }
693
694 /**
695 * Convert a path defined in the source system into an equivalent path in the repository system.
696 *
697 * @param pathInSource the path in the source system, which may include the {@link #getPathInSource()}
698 * @param factory the path factory; may not be null
699 * @return the path in the repository system, which will be normalized and absolute (including the
700 * {@link #getPathInRepository()}), or null if the path is not at or under the {@link #getPathInSource()}
701 */
702 protected Path projectPathInSourceToPathInRepository( Path pathInSource,
703 PathFactory factory ) {
704 if (!this.sourcePath.isAtOrAbove(pathInSource)) return null;
705 // Remove the leading source path ...
706 Path relativeSourcePath = pathInSource.relativeTo(this.sourcePath);
707 // Prepend the region's root path ...
708 Path result = factory.create(this.repositoryPath, relativeSourcePath);
709 return result.getNormalizedPath();
710 }
711
712 /**
713 * Convert a path defined in the repository system into an equivalent path in the source system.
714 *
715 * @param pathInRepository the path in the repository system, which may include the {@link #getPathInRepository()}
716 * @param factory the path factory; may not be null
717 * @return the path in the source system, which will be normalized and absolute (including the {@link #getPathInSource()}
718 * ), or null if the path is not at or under the {@link #getPathInRepository()}
719 */
720 protected Path projectPathInRepositoryToPathInSource( Path pathInRepository,
721 PathFactory factory ) {
722 if (!this.repositoryPath.isAtOrAbove(pathInRepository)) return null;
723 // Find the relative path from the root of this region ...
724 Path pathInRegion = pathInRepository.relativeTo(this.repositoryPath);
725 // Prepend the path in source ...
726 Path result = factory.create(this.sourcePath, pathInRegion);
727 return result.getNormalizedPath();
728 }
729
730 @Override
731 public String getString( NamespaceRegistry registry,
732 TextEncoder encoder ) {
733 StringBuilder sb = new StringBuilder();
734 sb.append(this.getPathInRepository().getString(registry, encoder));
735 sb.append(" => ");
736 sb.append(this.getPathInSource().getString(registry, encoder));
737 if (this.getExceptionsToRule().size() != 0) {
738 for (Path exception : this.getExceptionsToRule()) {
739 sb.append(" $ ");
740 sb.append(exception.getString(registry, encoder));
741 }
742 }
743 return sb.toString();
744 }
745
746 /**
747 * {@inheritDoc}
748 *
749 * @see org.jboss.dna.connector.federation.Projection.Rule#getString(org.jboss.dna.common.text.TextEncoder)
750 */
751 @Override
752 public String getString( TextEncoder encoder ) {
753 StringBuilder sb = new StringBuilder();
754 sb.append(this.getPathInRepository().getString(encoder));
755 sb.append(" => ");
756 sb.append(this.getPathInSource().getString(encoder));
757 if (this.getExceptionsToRule().size() != 0) {
758 for (Path exception : this.getExceptionsToRule()) {
759 sb.append(" $ ");
760 sb.append(exception.getString(encoder));
761 }
762 }
763 return sb.toString();
764 }
765
766 /**
767 * {@inheritDoc}
768 *
769 * @see org.jboss.dna.connector.federation.Projection.Rule#getString()
770 */
771 @Override
772 public String getString() {
773 return getString(Path.JSR283_ENCODER);
774 }
775
776 /**
777 * {@inheritDoc}
778 *
779 * @see java.lang.Object#hashCode()
780 */
781 @Override
782 public int hashCode() {
783 return hc;
784 }
785
786 /**
787 * {@inheritDoc}
788 *
789 * @see java.lang.Object#equals(java.lang.Object)
790 */
791 @Override
792 public boolean equals( Object obj ) {
793 if (obj == this) return true;
794 if (obj instanceof PathRule) {
795 PathRule that = (PathRule)obj;
796 if (!this.getPathInRepository().equals(that.getPathInRepository())) return false;
797 if (!this.getPathInSource().equals(that.getPathInSource())) return false;
798 if (!this.getExceptionsToRule().equals(that.getExceptionsToRule())) return false;
799 return true;
800 }
801 return false;
802 }
803
804 /**
805 * {@inheritDoc}
806 *
807 * @see java.lang.Comparable#compareTo(java.lang.Object)
808 */
809 public int compareTo( Rule other ) {
810 if (other == this) return 0;
811 if (other instanceof PathRule) {
812 PathRule that = (PathRule)other;
813 int diff = this.getPathInRepository().compareTo(that.getPathInRepository());
814 if (diff != 0) return diff;
815 diff = this.getPathInSource().compareTo(that.getPathInSource());
816 if (diff != 0) return diff;
817 Iterator<Path> thisIter = this.getExceptionsToRule().iterator();
818 Iterator<Path> thatIter = that.getExceptionsToRule().iterator();
819 while (thisIter.hasNext() && thatIter.hasNext()) {
820 diff = thisIter.next().compareTo(thatIter.next());
821 if (diff != 0) return diff;
822 }
823 if (thisIter.hasNext()) return 1;
824 if (thatIter.hasNext()) return -1;
825 return 0;
826 }
827 return other.getClass().getName().compareTo(this.getClass().getName());
828 }
829
830 /**
831 * {@inheritDoc}
832 *
833 * @see java.lang.Object#toString()
834 */
835 @Override
836 public String toString() {
837 return getString();
838 }
839 }
840 }