StoryLocation.java

  1. package org.jbehave.core.io;

  2. import static org.apache.commons.lang3.StringUtils.removeStart;

  3. import java.net.MalformedURLException;
  4. import java.net.URL;

  5. import org.apache.commons.lang3.builder.ToStringBuilder;
  6. import org.apache.commons.lang3.builder.ToStringStyle;

  7. /**
  8.  * <p>
  9.  * Abstraction of a story location, handling cases in which story path is defined
  10.  * as a resource in classpath or as a URL.
  11.  * </p>
  12.  * <p>Given a code location URL and a story path, it provides the methods:
  13.  * <ul>
  14.  * <li>{@link #getURL()}: the story location URL, prefixing the code location external form if story path is not a
  15.  * URL</li>
  16.  * <li>{@link #getPath()}: the story location path, removing the code location external form if story path is a URL</li>
  17.  * </ul>
  18.  * </p>
  19.  */
  20. public class StoryLocation {

  21.     private final URL codeLocation;
  22.     private final String storyPath;
  23.     private final boolean storyPathIsURL;

  24.     public StoryLocation(URL codeLocation, String storyPath) {
  25.         this.codeLocation = codeLocation;
  26.         this.storyPath = storyPath;
  27.         this.storyPathIsURL = isURL(storyPath);
  28.     }

  29.     public URL getCodeLocation() {
  30.         return codeLocation;
  31.     }

  32.     public String getStoryPath() {
  33.         return storyPath;
  34.     }

  35.     public String getURL() {
  36.         if (storyPathIsURL) {
  37.             return storyPath;
  38.         } else {
  39.             return codeLocation.toExternalForm() + storyPath;
  40.         }
  41.     }

  42.     public String getPath() {
  43.         if (storyPathIsURL) {
  44.             return removeStart(storyPath, codeLocation.toExternalForm());
  45.         } else {
  46.             return storyPath;
  47.         }
  48.     }

  49.     private boolean isURL(String path) {
  50.         try {
  51.             new URL(path);
  52.             return true;
  53.         } catch (MalformedURLException e) {
  54.             return false;
  55.         }
  56.     }

  57.     @Override
  58.     public String toString() {
  59.         return ToStringBuilder.reflectionToString(this,
  60.                 ToStringStyle.SHORT_PREFIX_STYLE);
  61.     }
  62. }