ImportToFilesystem.java

  1. package org.jbehave.core.io.rest.filesystem;

  2. import static org.jbehave.core.io.rest.filesystem.FilesystemUtils.asFile;

  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.Map;

  7. import org.jbehave.core.io.ResourceLoader;
  8. import org.jbehave.core.io.rest.Resource;
  9. import org.jbehave.core.io.rest.ResourceImporter;
  10. import org.jbehave.core.io.rest.ResourceIndexer;

  11. /**
  12.  * <p>Implementation that writes to filesystem the imported resources, using the target file path and extension
  13.  * specified.</p>
  14.  *
  15.  * <p>The importer requires an instance of a {@link ResourceIndexer} and of a {@link ResourceLoader}.</p>
  16.  */
  17. public class ImportToFilesystem implements ResourceImporter {

  18.     private final ResourceIndexer indexer;
  19.     private final ResourceLoader loader;
  20.     private final String targetPath;
  21.     private final String targetExt;

  22.     public ImportToFilesystem(ResourceIndexer indexer, ResourceLoader loader, String targetPath, String targetExt) {
  23.         this.indexer = indexer;
  24.         this.loader = loader;
  25.         this.targetPath = targetPath;
  26.         this.targetExt = targetExt;
  27.     }

  28.     @Override
  29.     public void importResources(String rootURI) {
  30.         Map<String, Resource> index = indexer.indexResources(rootURI);
  31.         loadResources(index);
  32.         writeResources(index, targetPath, targetExt);
  33.     }

  34.     private void loadResources(Map<String, Resource> index) {
  35.         for (String name : index.keySet()) {
  36.             Resource resource = index.get(name);
  37.             String text = loader.loadResourceAsText(resource.getURI());
  38.             resource.setContent(text);
  39.         }
  40.     }

  41.     private void writeResources(Map<String, Resource> index, String targetPath, String targetExt) {
  42.         for (String name : index.keySet()) {
  43.             Resource resource = index.get(name);
  44.             writeResource(resource, asFile(resource, targetPath, targetExt));
  45.         }
  46.     }

  47.     private void writeResource(Resource resource, File file) {
  48.         try {
  49.             file.getParentFile().mkdirs();
  50.             if (resource.hasContent()) {
  51.                 FileWriter writer = new FileWriter(file);
  52.                 writer.write(resource.getContent());
  53.                 writer.close();
  54.             }
  55.         } catch (IOException e) {
  56.             throw new RuntimeException("Failed to write resource " + resource + " to file " + file, e);
  57.         }
  58.     }

  59. }