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.configuration.SystemConfiguration;
\r
33 import user.commons.nexio.NexioDispatcher;
\r
34 import user.commons.nosql.NoSQLUtils;
\r
35 import user.commons.octopus.IOctopusAPI;
\r
36 import user.commons.octopus.OctopusAPI;
\r
37 import user.commons.remotestore.FtpDirectoryLister;
\r
38 import user.commons.remotestore.RemoteStoreProtocol;
\r
39 import user.jobengine.db.IItemManager;
\r
40 import user.jobengine.server.IJobEngine;
\r
41 import user.jobengine.server.IJobRuntime;
\r
43 public class CopyForArchiveNEXIORecordingsStep extends JobStep {
\r
44 private static final String MEDIATYPE = "Visszarögzített";
\r
45 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
46 private static final String STARTTIME_FORMAT = "HHmm";
\r
47 private static final String RUNDOWNDATE_FORMAT = "yyyyMMdd";
\r
48 private static final Logger logger = LogManager.getLogger();
\r
49 private static final String UTF_8 = "utf-8";
\r
50 private static final String JSON_EXT = ".json";
\r
51 private static final String XML_EXT = ".xml";
\r
52 private static final String DURATION = "duration";
\r
53 private static final String MXFEXT = ".MXF";
\r
54 private static final String NEXIOCLIPS = NexioDispatcher.CLIP_COLLECTION_NAME;
\r
55 private static final String LONGNAMEID = "longnameid";
\r
56 private static final String EXTAGENCY = "extagency";
\r
57 private static final String RECORDDATE = "recorddate";
\r
58 private static final SimpleDateFormat startTimeformat = new SimpleDateFormat(STARTTIME_FORMAT);
\r
59 private static final SimpleDateFormat rundownDateformat = new SimpleDateFormat(RUNDOWNDATE_FORMAT);
\r
60 private static String NEXIO_HOST = SystemConfiguration.getInstance().value("services.nexio.host");
\r
62 private OctopusAPI octopusAPI;
\r
63 private IItemManager manager;
\r
66 private FTPClient sourceFtp;
\r
67 private FTPClient targetFtp;
\r
68 private StoreUri sourceUri;
\r
69 private StoreUri targetUri;
\r
70 private int nexioKillDateDays;
\r
71 private String nexioAgency;
\r
72 private Object[] filterAgencies;
\r
73 private Marker systemMarker;
\r
75 private int check(int value, String name) {
\r
77 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
78 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
83 private String check(String value, String name) {
\r
84 if (StringUtils.isBlank(value)) {
\r
85 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
86 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
91 private void copy(RundownArchive rundownArchive) {
\r
92 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
93 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
95 copyFile(fileArchive, rundownArchive, storyArchive);
\r
96 logger.info(systemMarker, "Sikeres fájl archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());
\r
97 } catch (Exception e) {
\r
98 logger.error(systemMarker, "Az '{}' fájl archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
104 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
105 String sourceFileName = fileArchive.getFileName();
\r
106 String targetFileName = getTargetFileName(rundownArchive, sourceFileName);
\r
107 transferFile(sourceFileName, targetFileName);
\r
108 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
109 transferMetadata(targetFileName, metadata);
\r
110 createSourceKillDateFile(rundownArchive, sourceFileName);
\r
113 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
114 BasicDBObject result = new BasicDBObject();
\r
115 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
116 result.put("itemTitle", rundownArchive.getItemTitle());
\r
117 result.put("itemDescription", rundownArchive.getItemDesc());
\r
118 result.put("userName", "mediacube");
\r
120 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
121 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
122 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
124 result.put("duration", fileArchive.getDuration());
\r
125 result.put("mediaType", MEDIATYPE);
\r
129 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
130 logger.info("Create killdate/agency for {}", fileName);
\r
131 OutputStream outStream = null;
\r
133 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
134 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
135 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
136 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
137 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
138 if (outStream == null) {
\r
139 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
141 outStream.write(killDateFile);
\r
143 } catch (Exception e) {
\r
144 logger.catching(e);
\r
147 if (outStream != null)
\r
149 sourceUri.cleanUp();
\r
154 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
155 String filterAgencies, int limit, int nexioKillDateDays, String targetAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
156 systemMarker = jobRuntime.getSessionMarker();
\r
157 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, filterAgencies, limit, nexioKillDateDays,
\r
158 targetAgency, jobEngine);
\r
159 octopusAPI = new OctopusAPI();
\r
160 List<BasicDBObject> clips = queryClips();
\r
161 processClips(clips, limit);
\r
165 private Date getScheduledStart(String clipName, Date recordDate) {
\r
166 if (StringUtils.isBlank(clipName)) {
\r
167 logger.warn(systemMarker, "A fájlnak nincs neve, ezért nem archiválható.");
\r
170 if (recordDate == null) {
\r
171 logger.warn(systemMarker, "Az '{}' fájl rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);
\r
175 Date timePart = null;
\r
177 String clipNameTime = clipName.split("_")[0];
\r
178 timePart = startTimeformat.parse(clipNameTime);
\r
179 } catch (ParseException e) {
\r
180 logger.warn(systemMarker, "A '{}' fájl neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);
\r
183 Calendar dateCal = CalendarUtils.createCalendar(recordDate);
\r
184 dateCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));
\r
185 Calendar wholeCal = CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart);
\r
186 wholeCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));
\r
187 return wholeCal.getTime();
\r
190 private String getTargetFileName(RundownArchive rundownArchive, String sourceFileName) {
\r
191 String date = rundownDateformat.format(rundownArchive.getScheduleDate());
\r
192 return String.format("%s-%s%s", date, sourceFileName, MXFEXT);
\r
195 private RundownArchive processClip(BasicDBObject clip) {
\r
196 RundownArchive result = null;
\r
197 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);
\r
198 Date recordDate = clip.getDate(RECORDDATE);
\r
199 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
200 logger.info("Processing {} {}", clipName, recordDate);
\r
201 Date scheduledStart = getScheduledStart(clipName, recordDate);
\r
202 if (scheduledStart == null)
\r
204 DBObject rundown = octopusAPI.getRundown(scheduledStart);
\r
205 if (rundown == null) {
\r
206 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
211 result = processRundow(rundown, clipName, duration);
\r
212 } catch (Exception e) {
\r
213 logger.catching(e);
\r
214 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
219 if (clipName.startsWith("1900_")) {
\r
220 String clipNameNext = clipName.replace("1900_", "1908_");
\r
221 scheduledStart = getScheduledStart(clipNameNext, recordDate);
\r
222 rundown = octopusAPI.getRundown(scheduledStart);
\r
223 if (rundown == null) {
\r
224 Calendar calendar = CalendarUtils.createCalendar(scheduledStart);
\r
225 int dow = calendar.get(Calendar.DAY_OF_WEEK);
\r
226 if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) {
\r
227 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
231 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
236 RundownArchive item2 = null;
\r
239 item2 = processRundow(rundown, clipName, duration);
\r
240 } catch (Exception e) {
\r
241 logger.catching(e);
\r
242 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
247 result.setItemTitle(result.getItemTitle() + " + NAPIAKT");
\r
248 StoryArchive storyArchive = result.getStoryArchives().get(0);
\r
249 StoryArchive storyArchive2 = item2.getStoryArchives().get(0);
\r
250 storyArchive.setMediaDesc(storyArchive.getMediaDesc() + "\r\n\r\n****** NAPIAKT ******\r\n\r\n" + storyArchive2.getMediaDesc());
\r
256 private void processClips(List<BasicDBObject> clips, int limit) {
\r
257 logger.info(systemMarker, "A folyamat {} archiválható anyagot érzékelt.", clips.size());
\r
259 for (BasicDBObject clip : clips) {
\r
260 RundownArchive rundownArchive = processClip(clip);
\r
261 if (rundownArchive == null)
\r
264 copy(rundownArchive);
\r
267 if (current == limit)
\r
269 setProgress(current * 100 / limit);
\r
273 private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {
\r
274 BasicDBObject rundown = (BasicDBObject) r;
\r
275 long rundownID = rundown.getLong(IOctopusAPI.ID);
\r
276 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
278 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
279 if (stories == null)
\r
281 RundownArchive result = new RundownArchive();
\r
283 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
284 if (StringUtils.isBlank(name))
\r
286 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
287 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
288 if (scheduledStart == null)
\r
290 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
291 result.setScheduleDate(scheduledStart);
\r
292 result.setItemHouseId(String.valueOf(rundownID));
\r
293 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
295 StoryArchive storyArchive = new StoryArchive();
\r
296 storyArchive.setMediaHouseId(result.getItemHouseId());
\r
297 storyArchive.setMediaTitle(clipName);
\r
298 storyArchive.setMediaDesc(octopusAPI.getRundownContent(stories));
\r
299 result.addStoryArchive(storyArchive);
\r
300 storyArchive.addFileArchive(new FileArchive(clipName, duration));
\r
304 private List<BasicDBObject> queryClips() {
\r
305 DBCollection collection = db.getCollection(NEXIOCLIPS);
\r
306 BasicDBList agencies = new BasicDBList(filterAgencies);
\r
308 Calendar now = CalendarUtils.createZeroCalendar();
\r
309 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());
\r
310 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());
\r
311 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);
\r
312 if (!cursor.hasNext())
\r
314 return ListUtils.cast(cursor.toArray());
\r
317 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
318 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
319 db = NoSQLUtils.getNoSQLDB();
\r
321 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
322 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
325 if (jobEngine == null) {
\r
326 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
327 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
329 manager = jobEngine.getItemManager();
\r
330 if (manager == null) {
\r
331 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
332 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
335 if (StringUtils.isBlank(NEXIO_HOST)) {
\r
336 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
337 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
339 check(nexioPort, "nexioPort");
\r
340 check(nexioUserName, "nexioUserName");
\r
341 check(nexioPassword, "nexioPassword");
\r
343 check(agencies, "filterAgencies");
\r
344 filterAgencies = agencies.split(",");
\r
346 check(limit, "limit");
\r
348 check(nexioKillDateDays, "nexioKillDateDays");
\r
349 this.nexioKillDateDays = nexioKillDateDays;
\r
350 check(nexioAgency, "nexioAgency");
\r
351 this.nexioAgency = nexioAgency;
\r
353 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, NEXIO_HOST);
\r
354 sourceUri.setPortNumber(nexioPort);
\r
355 sourceUri.setUserName(nexioUserName);
\r
356 sourceUri.setPassword(nexioPassword);
\r
357 if (sourceUri == null) {
\r
358 logger.error(systemMarker, "A forrás nem elérhető.");
\r
359 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
362 check(archiveFtp, "archiveFtp");
\r
363 check(archiveUserName, "archiveUserName");
\r
364 check(archivePassword, "archivePassword");
\r
366 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
367 targetUri.setUserName(archiveUserName);
\r
368 targetUri.setPassword(archivePassword);
\r
369 if (targetUri == null) {
\r
370 logger.error(systemMarker, "A cél nem elérhető.");
\r
371 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
376 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
378 logger.info("Transfer clip {}", sourceFileName);
\r
380 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
381 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
383 if (!targetFtp.enterRemotePassiveMode())
\r
384 throw new Exception("!PASV");
\r
386 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
387 if (!FTPReply.isPositiveCompletion(reply))
\r
388 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
390 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
391 throw new Exception("!SOURCE TYPE");
\r
393 reply = sourceFtp.retr(sourceFileName);
\r
394 if (!FTPReply.isPositivePreliminary(reply))
\r
395 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
397 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
398 throw new Exception("!TARGET TYPE");
\r
400 reply = targetFtp.stor(targetFileName);
\r
401 if (!FTPReply.isPositivePreliminary(reply))
\r
402 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
405 reply = sourceFtp.stat();
\r
406 if (!FTPReply.isPositiveCompletion(reply))
\r
407 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
409 //logger.info("Status: {}", sourceFtp.getReplyString());
\r
410 if (reply == 226) {
\r
413 Thread.sleep(1000);
\r
415 } catch (Exception e) {
\r
416 logger.catching(e);
\r
419 sourceUri.cleanUp();
\r
420 targetUri.cleanUp();
\r
425 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
426 logger.info("Transfer metadata {}", fileName);
\r
427 OutputStream outStream = null;
\r
429 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
430 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
431 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
432 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
433 throw new Exception("!STATUSFOLDER");
\r
436 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
437 if (outStream == null) {
\r
438 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
440 outStream.write(metadata.toString().getBytes(UTF_8));
\r
442 //targetFtp.changeToParentDirectory();
\r
443 } catch (Exception e) {
\r
444 logger.catching(e);
\r
447 if (outStream != null)
\r
449 targetUri.cleanUp();
\r