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