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