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