|
| 1 | +package com.marklogic.client.ext.datamovement.consumer; |
| 2 | + |
| 3 | +import com.marklogic.client.document.DocumentRecord; |
| 4 | +import com.marklogic.client.ext.helper.LoggingObject; |
| 5 | +import com.marklogic.client.io.InputStreamHandle; |
| 6 | +import org.springframework.util.FileCopyUtils; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.io.FileOutputStream; |
| 10 | +import java.io.IOException; |
| 11 | +import java.util.function.Consumer; |
| 12 | + |
| 13 | +/** |
| 14 | + * Consumer implementation that is intended to be used with DMSDK's ExportListener. Writes each document to a File based |
| 15 | + * on the directory passed to this class's constructor plus the document's URI. |
| 16 | + */ |
| 17 | +public class WriteToFileConsumer extends LoggingObject implements Consumer<DocumentRecord> { |
| 18 | + |
| 19 | + private File baseDir; |
| 20 | + private boolean logErrors = true; |
| 21 | + |
| 22 | + public WriteToFileConsumer(File baseDir) { |
| 23 | + this.baseDir = baseDir; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void accept(DocumentRecord documentRecord) { |
| 28 | + String uri = documentRecord.getUri(); |
| 29 | + File outputFile = getOutputFile(documentRecord); |
| 30 | + if (logger.isDebugEnabled()) { |
| 31 | + logger.debug("Writing document with URI " + uri + " to file: " + outputFile.getAbsolutePath()); |
| 32 | + } |
| 33 | + try { |
| 34 | + writeDocumentToFile(documentRecord, outputFile); |
| 35 | + } catch (IOException e) { |
| 36 | + String message = "Unable to write document to file; URI: " + uri + "; file: " + outputFile.getAbsolutePath(); |
| 37 | + if (logErrors) { |
| 38 | + logger.warn(message, e); |
| 39 | + } else { |
| 40 | + throw new RuntimeException(message, e); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + protected File getOutputFile(DocumentRecord documentRecord) { |
| 46 | + return new File(baseDir, documentRecord.getUri()); |
| 47 | + } |
| 48 | + |
| 49 | + protected void writeDocumentToFile(DocumentRecord documentRecord, File file) throws IOException { |
| 50 | + file.getParentFile().mkdirs(); |
| 51 | + FileOutputStream fos = new FileOutputStream(file); |
| 52 | + try { |
| 53 | + InputStreamHandle handle = documentRecord.getContent(new InputStreamHandle()); |
| 54 | + FileCopyUtils.copy(handle.get(), fos); |
| 55 | + } finally { |
| 56 | + fos.close(); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + protected File getBaseDir() { |
| 61 | + return baseDir; |
| 62 | + } |
| 63 | + |
| 64 | + protected boolean isLogErrors() { |
| 65 | + return logErrors; |
| 66 | + } |
| 67 | + |
| 68 | + public void setLogErrors(boolean logErrors) { |
| 69 | + this.logErrors = logErrors; |
| 70 | + } |
| 71 | +} |
0 commit comments