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