| 1 | |
package org.jbehave.core.io.rest.filesystem; |
| 2 | |
|
| 3 | |
import static org.jbehave.core.io.rest.filesystem.FilesystemUtils.asFile; |
| 4 | |
|
| 5 | |
import java.io.File; |
| 6 | |
import java.io.FileWriter; |
| 7 | |
import java.io.IOException; |
| 8 | |
import java.util.Map; |
| 9 | |
|
| 10 | |
import org.jbehave.core.io.ResourceLoader; |
| 11 | |
import org.jbehave.core.io.rest.Resource; |
| 12 | |
import org.jbehave.core.io.rest.ResourceImporter; |
| 13 | |
import org.jbehave.core.io.rest.ResourceIndexer; |
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
public class ImportToFilesystem implements ResourceImporter { |
| 23 | |
|
| 24 | |
private final ResourceIndexer indexer; |
| 25 | |
private final ResourceLoader loader; |
| 26 | |
private final String targetPath; |
| 27 | |
private final String targetExt; |
| 28 | |
|
| 29 | 2 | public ImportToFilesystem(ResourceIndexer indexer, ResourceLoader loader, String targetPath, String targetExt) { |
| 30 | 2 | this.indexer = indexer; |
| 31 | 2 | this.loader = loader; |
| 32 | 2 | this.targetPath = targetPath; |
| 33 | 2 | this.targetExt = targetExt; |
| 34 | 2 | } |
| 35 | |
|
| 36 | |
public void importResources(String rootURI) { |
| 37 | 2 | Map<String, Resource> index = indexer.indexResources(rootURI); |
| 38 | 2 | loadResources(index); |
| 39 | 2 | writeResources(index, targetPath, targetExt); |
| 40 | 2 | } |
| 41 | |
|
| 42 | |
private void loadResources(Map<String, Resource> index) { |
| 43 | 2 | for (String name : index.keySet()) { |
| 44 | 2 | Resource resource = index.get(name); |
| 45 | 2 | String text = loader.loadResourceAsText(resource.getURI()); |
| 46 | 2 | resource.setText(text); |
| 47 | 2 | } |
| 48 | 2 | } |
| 49 | |
|
| 50 | |
private void writeResources(Map<String, Resource> index, String targetPath, String targetExt) { |
| 51 | 2 | for (String name : index.keySet()) { |
| 52 | 2 | Resource resource = index.get(name); |
| 53 | 2 | writeResource(resource, asFile(resource, targetPath, targetExt)); |
| 54 | 2 | } |
| 55 | 2 | } |
| 56 | |
|
| 57 | |
private void writeResource(Resource resource, File file) { |
| 58 | |
try { |
| 59 | 2 | file.getParentFile().mkdirs(); |
| 60 | 2 | FileWriter writer = new FileWriter(file); |
| 61 | 2 | if (resource.hasText()) { |
| 62 | 2 | writer.write(resource.getText()); |
| 63 | |
} |
| 64 | 2 | writer.close(); |
| 65 | 0 | } catch (IOException e) { |
| 66 | 0 | throw new RuntimeException("Failed to write resource " + resource + " to file " + file, e); |
| 67 | 2 | } |
| 68 | 2 | } |
| 69 | |
|
| 70 | |
} |