1 package user.jobengine.server.steps;
\r
3 import java.io.OutputStream;
\r
4 import java.net.InetAddress;
\r
6 import java.text.ParseException;
\r
7 import java.text.SimpleDateFormat;
\r
8 import java.util.Calendar;
\r
9 import java.util.Date;
\r
10 import java.util.List;
\r
11 import java.util.TimeZone;
\r
13 import org.apache.commons.lang.StringUtils;
\r
14 import org.apache.commons.net.ftp.FTP;
\r
15 import org.apache.commons.net.ftp.FTPClient;
\r
16 import org.apache.commons.net.ftp.FTPReply;
\r
17 import org.apache.logging.log4j.LogManager;
\r
18 import org.apache.logging.log4j.Logger;
\r
19 import org.apache.logging.log4j.Marker;
\r
21 import com.ibm.nosql.json.api.BasicDBList;
\r
22 import com.ibm.nosql.json.api.BasicDBObject;
\r
23 import com.ibm.nosql.json.api.DB;
\r
24 import com.ibm.nosql.json.api.DBCollection;
\r
25 import com.ibm.nosql.json.api.DBCursor;
\r
26 import com.ibm.nosql.json.api.DBObject;
\r
27 import com.ibm.nosql.json.api.QueryBuilder;
\r
29 import user.commons.CalendarUtils;
\r
30 import user.commons.ListUtils;
\r
31 import user.commons.StoreUri;
\r
32 import user.commons.nexio.NexioDispatcher;
\r
33 import user.commons.nosql.NoSQLUtils;
\r
34 import user.commons.octopus.IOctopusAPI;
\r
35 import user.commons.octopus.OctopusAPI;
\r
36 import user.commons.remotestore.FtpDirectoryLister;
\r
37 import user.commons.remotestore.RemoteStoreProtocol;
\r
38 import user.jobengine.db.IItemManager;
\r
39 import user.jobengine.server.IJobEngine;
\r
40 import user.jobengine.server.IJobRuntime;
\r
42 public class CopyForArchiveNEXIORecordingsStep extends JobStep {
\r
43 private static final String MEDIATYPE = "Visszarögzített";
\r
44 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
45 private static final String STARTTIME_FORMAT = "HHmm";
\r
46 private static final String RUNDOWNDATE_FORMAT = "yyyyMMdd";
\r
47 private static final Logger logger = LogManager.getLogger();
\r
48 private static final String UTF_8 = "utf-8";
\r
49 private static final String JSON_EXT = ".json";
\r
50 private static final String XML_EXT = ".xml";
\r
51 private static final String DURATION = "duration";
\r
52 private static final String MXFEXT = ".MXF";
\r
53 private static final String NEXIOCLIPS = NexioDispatcher.CLIP_COLLECTION_NAME;
\r
54 private static final String LONGNAMEID = "longnameid";
\r
55 private static final String EXTAGENCY = "extagency";
\r
56 private static final String RECORDDATE = "recorddate";
\r
57 private static final SimpleDateFormat startTimeformat = new SimpleDateFormat(STARTTIME_FORMAT);
\r
58 private static final SimpleDateFormat rundownDateformat = new SimpleDateFormat(RUNDOWNDATE_FORMAT);
\r
60 private OctopusAPI octopusAPI;
\r
61 private IItemManager manager;
\r
64 private FTPClient sourceFtp;
\r
65 private FTPClient targetFtp;
\r
66 private StoreUri sourceUri;
\r
67 private StoreUri targetUri;
\r
68 private int nexioKillDateDays;
\r
69 private String nexioAgency;
\r
70 private Object[] filterAgencies;
\r
71 private Marker systemMarker;
\r
73 private int check(int value, String name) {
\r
75 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
76 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
81 private String check(String value, String name) {
\r
82 if (StringUtils.isBlank(value)) {
\r
83 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
84 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
89 private void copy(RundownArchive rundownArchive) {
\r
90 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
91 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
93 copyFile(fileArchive, rundownArchive, storyArchive);
\r
94 logger.info(systemMarker, "Sikeres fájl archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());
\r
95 } catch (Exception e) {
\r
96 logger.error(systemMarker, "Az '{}' fájl archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
102 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
103 String sourceFileName = fileArchive.getFileName();
\r
104 String targetFileName = getTargetFileName(rundownArchive, sourceFileName);
\r
105 transferFile(sourceFileName, targetFileName);
\r
106 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
107 transferMetadata(targetFileName, metadata);
\r
108 createSourceKillDateFile(rundownArchive, sourceFileName);
\r
111 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
112 BasicDBObject result = new BasicDBObject();
\r
113 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
114 result.put("itemTitle", rundownArchive.getItemTitle());
\r
115 result.put("itemDescription", rundownArchive.getItemDesc());
\r
116 result.put("userName", "mediacube");
\r
118 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
119 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
120 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
122 result.put("duration", fileArchive.getDuration());
\r
123 result.put("mediaType", MEDIATYPE);
\r
127 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
128 logger.info("Create killdate/agency for {}", fileName);
\r
129 OutputStream outStream = null;
\r
131 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
132 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
133 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
134 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
135 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
136 if (outStream == null) {
\r
137 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
139 outStream.write(killDateFile);
\r
141 } catch (Exception e) {
\r
142 logger.catching(e);
\r
145 if (outStream != null)
\r
147 sourceUri.cleanUp();
\r
152 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
153 String filterAgencies, int limit, int nexioKillDateDays, String targetAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
154 systemMarker = jobRuntime.getMarker();
\r
155 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, filterAgencies, limit, nexioKillDateDays,
\r
156 targetAgency, jobEngine);
\r
157 octopusAPI = new OctopusAPI();
\r
158 List<BasicDBObject> clips = queryClips();
\r
159 processClips(clips, limit);
\r
163 private Date getScheduledStart(String clipName, Date recordDate) {
\r
164 if (StringUtils.isBlank(clipName)) {
\r
165 logger.warn(systemMarker, "A fájlnak nincs neve, ezért nem archiválható.");
\r
168 if (recordDate == null) {
\r
169 logger.warn(systemMarker, "Az '{}' fájl rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);
\r
173 Date timePart = null;
\r
175 String clipNameTime = clipName.split("_")[0];
\r
176 timePart = startTimeformat.parse(clipNameTime);
\r
177 } catch (ParseException e) {
\r
178 logger.warn(systemMarker, "A '{}' fájl neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);
\r
181 Calendar dateCal = CalendarUtils.createCalendar(recordDate);
\r
182 dateCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));
\r
183 Calendar wholeCal = CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart);
\r
184 wholeCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));
\r
185 return wholeCal.getTime();
\r
188 private String getTargetFileName(RundownArchive rundownArchive, String sourceFileName) {
\r
189 String date = rundownDateformat.format(rundownArchive.getScheduleDate());
\r
190 return String.format("%s-%s%s", date, sourceFileName, MXFEXT);
\r
193 private RundownArchive processClip(BasicDBObject clip) {
\r
194 RundownArchive result = null;
\r
195 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);
\r
196 Date recordDate = clip.getDate(RECORDDATE);
\r
197 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
198 logger.info("Processing {} {}", clipName, recordDate);
\r
199 Date scheduledStart = getScheduledStart(clipName, recordDate);
\r
200 if (scheduledStart == null)
\r
202 DBObject rundown = octopusAPI.getRundown(scheduledStart);
\r
203 if (rundown == null) {
\r
204 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
209 result = processRundow(rundown, clipName, duration);
\r
210 } catch (Exception e) {
\r
211 logger.catching(e);
\r
212 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
217 if (clipName.startsWith("1900_")) {
\r
218 String clipNameNext = clipName.replace("1900_", "1908_");
\r
219 scheduledStart = getScheduledStart(clipNameNext, recordDate);
\r
220 rundown = octopusAPI.getRundown(scheduledStart);
\r
221 if (rundown == null) {
\r
222 Calendar calendar = CalendarUtils.createCalendar(scheduledStart);
\r
223 int dow = calendar.get(Calendar.DAY_OF_WEEK);
\r
224 if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) {
\r
225 logger.info(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, de a hétvégi kivétel miatt archiválható.", clipName,
\r
229 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
234 RundownArchive item2 = null;
\r
237 item2 = processRundow(rundown, clipName, duration);
\r
238 } catch (Exception e) {
\r
239 logger.catching(e);
\r
240 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
245 result.setItemTitle(result.getItemTitle() + " + NAPIAKT");
\r
246 StoryArchive storyArchive = result.getStoryArchives().get(0);
\r
247 StoryArchive storyArchive2 = item2.getStoryArchives().get(0);
\r
248 storyArchive.setMediaDesc(storyArchive.getMediaDesc() + "\r\n\r\n****** NAPIAKT ******\r\n\r\n" + storyArchive2.getMediaDesc());
\r
254 private void processClips(List<BasicDBObject> clips, int limit) {
\r
255 logger.info(systemMarker, "A folyamat {} archiválható anyagot érzékelt.", clips.size());
\r
257 for (BasicDBObject clip : clips) {
\r
258 RundownArchive rundownArchive = processClip(clip);
\r
259 if (rundownArchive == null)
\r
262 copy(rundownArchive);
\r
265 if (current == limit)
\r
267 setProgress(current * 100 / limit);
\r
271 private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {
\r
272 BasicDBObject rundown = (BasicDBObject) r;
\r
273 long rundownID = rundown.getLong(IOctopusAPI.ID);
\r
274 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
276 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
277 if (stories == null)
\r
279 RundownArchive result = new RundownArchive();
\r
281 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
282 if (StringUtils.isBlank(name))
\r
284 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
285 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
286 if (scheduledStart == null)
\r
288 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
289 result.setScheduleDate(scheduledStart);
\r
290 result.setItemHouseId(String.valueOf(rundownID));
\r
291 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
293 StoryArchive storyArchive = new StoryArchive();
\r
294 storyArchive.setMediaHouseId(result.getItemHouseId());
\r
295 storyArchive.setMediaTitle(clipName);
\r
296 storyArchive.setMediaDesc(octopusAPI.getRundownContent(stories));
\r
297 result.addStoryArchive(storyArchive);
\r
298 storyArchive.addFileArchive(new FileArchive(clipName, duration));
\r
302 private List<BasicDBObject> queryClips() {
\r
303 DBCollection collection = db.getCollection(NEXIOCLIPS);
\r
304 BasicDBList agencies = new BasicDBList(filterAgencies);
\r
306 Calendar now = CalendarUtils.createZeroCalendar();
\r
307 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());
\r
308 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());
\r
309 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);
\r
310 if (!cursor.hasNext())
\r
312 return ListUtils.cast(cursor.toArray());
\r
315 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
316 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
317 db = NoSQLUtils.getNoSQLDB();
\r
319 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
320 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
323 if (jobEngine == null) {
\r
324 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
325 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
327 manager = jobEngine.getItemManager();
\r
328 if (manager == null) {
\r
329 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
330 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
332 String nexioHost = System.getProperty("nexio.host");
\r
333 if (StringUtils.isBlank(nexioHost)) {
\r
334 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
335 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
337 check(nexioPort, "nexioPort");
\r
338 check(nexioUserName, "nexioUserName");
\r
339 check(nexioPassword, "nexioPassword");
\r
341 check(agencies, "filterAgencies");
\r
342 filterAgencies = agencies.split(",");
\r
344 check(limit, "limit");
\r
346 check(nexioKillDateDays, "nexioKillDateDays");
\r
347 this.nexioKillDateDays = nexioKillDateDays;
\r
348 check(nexioAgency, "nexioAgency");
\r
349 this.nexioAgency = nexioAgency;
\r
351 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
352 sourceUri.setPortNumber(nexioPort);
\r
353 sourceUri.setUserName(nexioUserName);
\r
354 sourceUri.setPassword(nexioPassword);
\r
355 if (sourceUri == null) {
\r
356 logger.error(systemMarker, "A forrás nem elérhető.");
\r
357 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
360 check(archiveFtp, "archiveFtp");
\r
361 check(archiveUserName, "archiveUserName");
\r
362 check(archivePassword, "archivePassword");
\r
364 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
365 targetUri.setUserName(archiveUserName);
\r
366 targetUri.setPassword(archivePassword);
\r
367 if (targetUri == null) {
\r
368 logger.error(systemMarker, "A cél nem elérhető.");
\r
369 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
374 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
376 logger.info("Transfer clip {}", sourceFileName);
\r
378 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
379 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
381 if (!targetFtp.enterRemotePassiveMode())
\r
382 throw new Exception("!PASV");
\r
384 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
385 if (!FTPReply.isPositiveCompletion(reply))
\r
386 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
388 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
389 throw new Exception("!SOURCE TYPE");
\r
391 reply = sourceFtp.retr(sourceFileName);
\r
392 if (!FTPReply.isPositivePreliminary(reply))
\r
393 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
395 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
396 throw new Exception("!TARGET TYPE");
\r
398 reply = targetFtp.stor(targetFileName);
\r
399 if (!FTPReply.isPositivePreliminary(reply))
\r
400 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
403 reply = sourceFtp.stat();
\r
404 if (!FTPReply.isPositiveCompletion(reply))
\r
405 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
407 //logger.info("Status: {}", sourceFtp.getReplyString());
\r
408 if (reply == 226) {
\r
411 Thread.sleep(1000);
\r
413 } catch (Exception e) {
\r
414 logger.catching(e);
\r
417 sourceUri.cleanUp();
\r
418 targetUri.cleanUp();
\r
423 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
424 logger.info("Transfer metadata {}", fileName);
\r
425 OutputStream outStream = null;
\r
427 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
428 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
429 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
430 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
431 throw new Exception("!STATUSFOLDER");
\r
434 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
435 if (outStream == null) {
\r
436 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
438 outStream.write(metadata.toString().getBytes(UTF_8));
\r
440 //targetFtp.changeToParentDirectory();
\r
441 } catch (Exception e) {
\r
442 logger.catching(e);
\r
445 if (outStream != null)
\r
447 targetUri.cleanUp();
\r