008369b1340402a4d5b7218d000c902dc5575674
[mediacube.git] /
1 package user.jobengine.server.steps;\r
2 \r
3 import java.io.OutputStream;\r
4 import java.net.InetAddress;\r
5 import java.net.URI;\r
6 import java.util.ArrayList;\r
7 import java.util.Arrays;\r
8 import java.util.Calendar;\r
9 import java.util.Date;\r
10 import java.util.List;\r
11 \r
12 import org.apache.commons.lang.StringUtils;\r
13 import org.apache.commons.net.ftp.FTP;\r
14 import org.apache.commons.net.ftp.FTPClient;\r
15 import org.apache.commons.net.ftp.FTPReply;\r
16 import org.apache.logging.log4j.LogManager;\r
17 import org.apache.logging.log4j.Logger;\r
18 import org.apache.logging.log4j.Marker;\r
19 \r
20 import com.ibm.nosql.json.api.BasicDBObject;\r
21 import com.ibm.nosql.json.api.DB;\r
22 import com.ibm.nosql.json.api.DBCollection;\r
23 import com.ibm.nosql.json.api.DBCursor;\r
24 import com.ibm.nosql.json.api.DBObject;\r
25 \r
26 import user.commons.CalendarUtils;\r
27 import user.commons.ListUtils;\r
28 import user.commons.StoreUri;\r
29 import user.commons.nosql.NoSQLUtils;\r
30 import user.commons.octopus.IOctopusAPI;\r
31 import user.commons.octopus.OctopusAPI;\r
32 import user.commons.remotestore.FtpDirectoryLister;\r
33 import user.commons.remotestore.RemoteStoreProtocol;\r
34 import user.jobengine.db.IItemManager;\r
35 import user.jobengine.server.IJobEngine;\r
36 import user.jobengine.server.IJobRuntime;\r
37 \r
38 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {\r
39         private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";\r
40         private static final Logger logger = LogManager.getLogger();\r
41         private static final String UTF_8 = "utf-8";\r
42         private static final String JSON_EXT = ".json";\r
43         private static final String XML_EXT = ".xml";\r
44         private static final String DURATION = "duration";\r
45         private static final String MXFEXT = ".MXF";\r
46         private static final String NEXIOCLIPS = "nexioclips";\r
47         private static final String LONGNAMEID = "longnameid";\r
48         private static final String ARCHIVEDRUNDOWNS = "archivedrundowns";\r
49         private static final String ID = "id";\r
50         private static final String MEDIATYPE = "Hír bejátszó";\r
51         private OctopusAPI octopusAPI;\r
52         private IItemManager manager;\r
53 \r
54         private DB db;\r
55         private FTPClient sourceFtp;\r
56         private FTPClient targetFtp;\r
57         private StoreUri sourceUri;\r
58         private StoreUri targetUri;\r
59         private int nexioKillDateDays;\r
60         private String nexioAgency;\r
61         private Marker systemMarker;\r
62         private List<String> transferredFileNames = null;\r
63         private boolean demo = false;\r
64 \r
65         private int check(int value, String name) {\r
66                 if (value == 0) {\r
67                         logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);\r
68                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
69                 }\r
70                 return value;\r
71         }\r
72 \r
73         private String check(String value, String name) {\r
74                 if (value == null) {\r
75                         logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);\r
76                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
77                 }\r
78                 return value;\r
79         }\r
80 \r
81         private void copy(RundownArchive rundownArchive) throws Exception {\r
82                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
83                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
84                                 try {\r
85                                         copyFile(fileArchive, rundownArchive, storyArchive);\r
86                                 } catch (Exception e) {\r
87                                         logger.error(systemMarker, "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());\r
88                                         throw e;\r
89                                 }\r
90                         }\r
91                 }\r
92         }\r
93 \r
94         private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {\r
95                 String origFileName = fileArchive.getFileName();\r
96                 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());\r
97                 String videoFileName = fileName + MXFEXT;\r
98 \r
99                 if (transferredFileNames == null)\r
100                         transferredFileNames = new ArrayList<>();\r
101 \r
102                 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot\r
103                 long existingMediaId = 0;\r
104                 boolean transferDone = false;\r
105                 if (transferredFileNames.contains(origFileName)) {\r
106                         logger.info(systemMarker, "A '{}' file archiválásra felkészítése egy másik story kapcsán már megtörtént, ezért csak metaadat archiválás szükséges.",\r
107                                         origFileName);\r
108                         if (!demo)\r
109                                 transferDone = transferChunk(videoFileName);\r
110                 } else {\r
111                         existingMediaId = ItemManagerExtensions.getExistingRundownMedia(manager, origFileName);\r
112                         if (existingMediaId == 0) {\r
113                                 transferredFileNames.add(origFileName);\r
114                                 if (!demo)\r
115                                         transferDone = transferFile(origFileName + MXFEXT, videoFileName);\r
116                                 logger.info(systemMarker, "A '{}' file archiválásra felkészítése sikeres volt.", origFileName);\r
117                         } else {\r
118 \r
119                                 logger.info(systemMarker, "A '{}' file archiválása már megtörtént, ezért csak metaadat archiválás szükséges.", origFileName);\r
120                                 if (!demo)\r
121                                         transferDone = transferChunk(videoFileName);\r
122                         }\r
123                 }\r
124 \r
125                 if (!demo && transferDone) {\r
126                         BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);\r
127                         transferMetadata(videoFileName, metadata);\r
128                         createSourceKillDateFile(rundownArchive, origFileName);\r
129                 }\r
130         }\r
131 \r
132         private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {\r
133                 BasicDBObject result = new BasicDBObject();\r
134                 result.put("itemHouseId", rundownArchive.getItemHouseId());\r
135                 result.put("itemTitle", rundownArchive.getItemTitle());\r
136                 result.put("itemDescription", rundownArchive.getItemDesc());\r
137                 result.put("userName", "mediacube");\r
138                 result.put("mediaHouseId", storyArchive.getMediaHouseId());\r
139                 result.put("mediaTitle", storyArchive.getMediaTitle());\r
140                 result.put("mediaDescription", storyArchive.getMediaDesc());\r
141                 result.put("mediaType", MEDIATYPE);\r
142                 result.put("duration", fileArchive.getDuration());\r
143                 result.put("existingMediaId", existingMediaId);\r
144                 return result;\r
145         }\r
146 \r
147         private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {\r
148                 logger.info("Create killdate/agency for {}", fileName);\r
149                 OutputStream outStream = null;\r
150                 try {\r
151                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
152                         Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());\r
153                         killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);\r
154                         byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);\r
155                         outStream = sourceFtp.storeFileStream(fileName + XML_EXT);\r
156                         if (outStream == null) {\r
157                                 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());\r
158                         }\r
159                         outStream.write(killDateFile);\r
160                         outStream.flush();\r
161                 } catch (Exception e) {\r
162                         logger.catching(e);\r
163                         throw e;\r
164                 } finally {\r
165                         if (outStream != null)\r
166                                 outStream.close();\r
167                         sourceUri.cleanUp();\r
168                 }\r
169         }\r
170 \r
171         @StepEntry\r
172         public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
173                         int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {\r
174                 systemMarker = jobRuntime.getSessionMarker();\r
175                 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);\r
176                 octopusAPI = new OctopusAPI();\r
177                 Calendar scheduledDate = Calendar.getInstance();\r
178                 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);\r
179                 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());\r
180                 if (rundowns == null) {\r
181                         logger.warn(systemMarker, "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));\r
182                         return null;\r
183                 }\r
184 \r
185                 processRundowns(rundowns);\r
186                 return null;\r
187         }\r
188 \r
189         //      private String getVersionedFileName(String fileName, String extension) throws Exception {\r
190         //              String result = fileName;\r
191         //              try {\r
192         //                      targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
193         //                      FTPFile[] listFiles = targetFtp.listFiles();\r
194         //                      List<String> fileNames = new ArrayList<>();\r
195         //                      for (FTPFile ftpFile : listFiles) {\r
196         //                              fileNames.add(ftpFile.getName());\r
197         //                      }\r
198         //                      while (fileNames.contains(result + extension)) {\r
199         //\r
200         //                      }\r
201         //\r
202         //              } catch (Exception e) {\r
203         //                      logger.catching(e);\r
204         //                      throw e;\r
205         //              } finally {\r
206         //                      targetUri.cleanUp();\r
207         //              }\r
208         //              return result;\r
209         //      }\r
210 \r
211         private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {\r
212                 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);\r
213                 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OctopusPlaceholder) {\r
214                         logger.trace("Skipping MOS object {}", mosID);\r
215                         return null;\r
216                 }\r
217                 DBCollection clips = db.getCollection(NEXIOCLIPS);\r
218                 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));\r
219                 if (clip == null) {\r
220                         logger.debug("File {} NOT exists", mosID);\r
221                         return null;\r
222                         //throw new Exception(String.format("File NOT exists %s", mosID));\r
223                 } else {\r
224                         logger.debug("File {} exists", mosID);\r
225                 }\r
226                 long duration = NoSQLUtils.asLong(clip, DURATION);\r
227 \r
228                 if (duration == 0) {\r
229                         logger.debug("File {} exists with 0 frame length", mosID);\r
230                         return null;\r
231                 }\r
232                 if (duration == 1) {\r
233                         logger.debug("File {} exists with 1 frame length", mosID);\r
234                         return null;\r
235                 }\r
236                 return new FileArchive(mosID, duration);\r
237         }\r
238 \r
239         private RundownArchive processRundow(DBObject r) throws Exception {\r
240                 BasicDBObject rundown = (BasicDBObject) r;\r
241                 long rundownID = rundown.getLong(ID);\r
242                 if (!demo)\r
243                         logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
244                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
245                 if (stories == null)\r
246                         return null;\r
247                 RundownArchive result = new RundownArchive();\r
248 \r
249                 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
250                 if (id == 0)\r
251                         return null;\r
252                 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);\r
253                 if (StringUtils.isBlank(name))\r
254                         return null;\r
255                 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);\r
256                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
257                 if (scheduledStart == null)\r
258                         return null;\r
259                 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);\r
260                 result.setScheduleDate(scheduledStart);\r
261                 result.setItemHouseId(String.valueOf(id));\r
262                 result.setItemTitle(String.format("%s %s %s", start, name, channel));\r
263 \r
264                 for (DBObject s : stories) {\r
265                         StoryArchive storyArchive = processStory(rundown, s);\r
266                         if (storyArchive == null)\r
267                                 continue;\r
268                         result.addStoryArchive(storyArchive);\r
269                 }\r
270                 return result;\r
271         }\r
272 \r
273         private void processRundowns(List<DBObject> rundowns) {\r
274 \r
275                 //TODO kiveni publikálás előtt\r
276                 //db.getCollection(ARCHIVEDRUNDOWNS).drop();\r
277                 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();\r
278 \r
279                 int index = 1;\r
280 \r
281                 for (DBObject r : rundowns) {\r
282                         BasicDBObject rundown = (BasicDBObject) r;\r
283                         setProgress(index * 100 / rundowns.size());\r
284                         long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
285                         String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);\r
286                         try {\r
287                                 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);\r
288                                 if (!demo && archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {\r
289                                         logger.info("Skipping archived rundown {} {}", rundownID, rundownName);\r
290                                         continue;\r
291                                 }\r
292 \r
293                                 RundownArchive rundownArchive = processRundow(r);\r
294                                 if (rundownArchive == null || rundownArchive.isEmpty()) {\r
295                                         if (!demo)\r
296                                                 logger.info("Skipping rundown {} {}", rundownID, rundownName);\r
297                                         continue;\r
298                                 }\r
299 \r
300                                 if (!demo)\r
301                                         logger.info("Saving rundown {} {}", rundownID, rundownName);\r
302                                 copy(rundownArchive);\r
303                                 if (!demo)\r
304                                         logger.info(systemMarker, "A '{}' tükör {}db bejátszójának archiválása sikeres volt", rundownArchive.getItemTitle(),\r
305                                                         rundownArchive.getStoryArchives().size());\r
306 \r
307                                 if (!demo)\r
308                                         db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);\r
309                         } catch (Exception e) {\r
310                                 logger.catching(e);\r
311                                 logger.error(systemMarker,\r
312                                                 String.format("A %s %s tükör archiválása nem lehetséges, mert a annak ellenőrzése hibát jelzett. A rendszer üzenete: %s", rundownID,\r
313                                                                 rundownName, e.getMessage()));\r
314                         }\r
315                         index++;\r
316                 }\r
317 \r
318         }\r
319 \r
320         private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {\r
321                 BasicDBObject story = (BasicDBObject) s;\r
322                 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);\r
323                 if (StringUtils.isBlank(parentStoryID)) {\r
324                         logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));\r
325                         return null;\r
326                 } else\r
327                         logger.debug("Processing story {}", parentStoryID);\r
328                 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);\r
329                 if (mosObjects == null)\r
330                         return null;\r
331                 StoryArchive storyArchive = null;\r
332                 for (BasicDBObject mosObject : mosObjects) {\r
333                         FileArchive fileArchive = processMosObject(rundown, story, mosObject);\r
334                         if (fileArchive == null)\r
335                                 continue;\r
336                         if (storyArchive == null) {\r
337                                 storyArchive = new StoryArchive();\r
338                                 storyArchive.setMediaHouseId(parentStoryID);\r
339                                 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));\r
340                                 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));\r
341 \r
342                         }\r
343                         storyArchive.addFileArchive(fileArchive);\r
344                 }\r
345                 return storyArchive;\r
346 \r
347         }\r
348 \r
349         private List<BasicDBObject> queryArchivedRundowns() {\r
350                 List<BasicDBObject> result = null;\r
351                 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);\r
352                 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));\r
353                 if (find.hasNext())\r
354                         result = ListUtils.cast(find.toArray());\r
355                 return result;\r
356         }\r
357 \r
358         private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
359                         int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {\r
360                 db = NoSQLUtils.getNoSQLDB();\r
361                 if (db == null) {\r
362                         logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");\r
363                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
364                 }\r
365 \r
366                 if (jobEngine == null) {\r
367                         logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");\r
368                         throw new NullPointerException("Internal error, missing JobEngine reference.");\r
369                 }\r
370                 manager = jobEngine.getItemManager();\r
371                 if (manager == null) {\r
372                         logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");\r
373                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
374                 }\r
375                 String nexioHost = System.getProperty("nexio.host");\r
376                 if (StringUtils.isBlank(nexioHost)) {\r
377                         logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");\r
378                         throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");\r
379                 }\r
380                 check(nexioPort, "nexioPort");\r
381                 check(nexioUserName, "nexioUserName");\r
382                 check(nexioPassword, "nexioPassword");\r
383 \r
384                 check(nexioKillDateDays, "nexioKillDateDays");\r
385                 this.nexioKillDateDays = nexioKillDateDays;\r
386                 check(nexioAgency, "nexioAgency");\r
387                 this.nexioAgency = nexioAgency;\r
388 \r
389                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);\r
390                 sourceUri.setPortNumber(nexioPort);\r
391                 sourceUri.setUserName(nexioUserName);\r
392                 sourceUri.setPassword(nexioPassword);\r
393                 if (sourceUri == null) {\r
394                         logger.error(systemMarker, "A forrás nem elérhető.");\r
395                         throw new NullPointerException("Internal error, missing 'sourceUri'.");\r
396                 }\r
397 \r
398                 check(archiveFtp, "archiveFtp");\r
399                 check(archiveUserName, "archiveUserName");\r
400                 check(archivePassword, "archivePassword");\r
401 \r
402                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
403                 targetUri.setUserName(archiveUserName);\r
404                 targetUri.setPassword(archivePassword);\r
405                 if (targetUri == null) {\r
406                         logger.error(systemMarker, "A cél nem elérhető.");\r
407                         throw new NullPointerException("Internal error, missing 'targetUri'.");\r
408                 }\r
409 \r
410         }\r
411 \r
412         private boolean transferChunk(String fileName) throws Exception {\r
413                 logger.info("Transfer chunk {}", fileName);\r
414                 OutputStream outStream = null;\r
415                 try {\r
416                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
417 \r
418                         //ha ugyan abban a tukorben szerepel meg 1x a mozi, akkor a chunk felulirja a tenyleges file-t, es az sosem archivalodik\r
419                         String[] names = targetFtp.listNames();\r
420                         if (names != null) {\r
421                                 if (Arrays.asList(names).contains(fileName))\r
422                                         return false;\r
423                         }\r
424 \r
425                         outStream = targetFtp.storeFileStream(fileName);\r
426                         if (outStream == null) {\r
427                                 throw new NullPointerException("Can not open: " + fileName + " Reply:" + targetFtp.getReplyString());\r
428                         }\r
429                 } catch (Exception e) {\r
430                         logger.catching(e);\r
431                         throw e;\r
432                 } finally {\r
433                         if (outStream != null)\r
434                                 outStream.close();\r
435                         targetUri.cleanUp();\r
436                 }\r
437                 return true;\r
438         }\r
439 \r
440         private boolean transferFile(String sourceFileName, String targetFileName) throws Exception {\r
441                 boolean result = true;\r
442                 int reply = 0;\r
443                 logger.info("Transfer clip {}", sourceFileName);\r
444                 try {\r
445                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
446                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
447                         if (!targetFtp.enterRemotePassiveMode())\r
448                                 throw new Exception("!PASV");\r
449 \r
450                         reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());\r
451                         if (!FTPReply.isPositiveCompletion(reply))\r
452                                 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());\r
453 \r
454                         if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
455                                 throw new Exception("!SOURCE TYPE");\r
456 \r
457                         reply = sourceFtp.retr(sourceFileName);\r
458                         if (!FTPReply.isPositivePreliminary(reply))\r
459                                 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());\r
460 \r
461                         if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
462                                 throw new Exception("!TARGET TYPE");\r
463 \r
464                         reply = targetFtp.stor(targetFileName);\r
465                         if (!FTPReply.isPositivePreliminary(reply))\r
466                                 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());\r
467 \r
468                         while (true) {\r
469                                 reply = sourceFtp.stat();\r
470                                 if (!FTPReply.isPositiveCompletion(reply))\r
471                                         throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());\r
472 \r
473                                 logger.info("Status: {}", sourceFtp.getReplyString());\r
474                                 if (reply == 226) {\r
475                                         break;\r
476                                 }\r
477                                 Thread.sleep(1000);\r
478                         }\r
479                 } catch (Exception e) {\r
480                         logger.catching(e);\r
481                         result = false;\r
482                 } finally {\r
483                         sourceUri.cleanUp();\r
484                         targetUri.cleanUp();\r
485                 }\r
486 \r
487                 return result;\r
488         }\r
489 \r
490         private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {\r
491                 logger.info("Transfer metadata {}", fileName);\r
492                 OutputStream outStream = null;\r
493                 try {\r
494                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
495                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {\r
496                                 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);\r
497                                 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
498                                         throw new Exception("!STATUSFOLDER");\r
499                         }\r
500 \r
501                         outStream = targetFtp.storeFileStream(fileName + JSON_EXT);\r
502                         if (outStream == null) {\r
503                                 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());\r
504                         }\r
505                         outStream.write(metadata.toString().getBytes(UTF_8));\r
506                         outStream.flush();\r
507                         //targetFtp.changeToParentDirectory();\r
508                 } catch (Exception e) {\r
509                         logger.catching(e);\r
510                         throw e;\r
511                 } finally {\r
512                         if (outStream != null)\r
513                                 outStream.close();\r
514                         targetUri.cleanUp();\r
515                 }\r
516         }\r
517 \r
518 }\r