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
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
20 import com.ibm.nosql.json.api.BasicDBList;
\r
21 import com.ibm.nosql.json.api.BasicDBObject;
\r
22 import com.ibm.nosql.json.api.DB;
\r
23 import com.ibm.nosql.json.api.DBCollection;
\r
24 import com.ibm.nosql.json.api.DBCursor;
\r
25 import com.ibm.nosql.json.api.DBObject;
\r
26 import com.ibm.nosql.json.api.QueryBuilder;
\r
28 import user.commons.CalendarUtils;
\r
29 import user.commons.ListUtils;
\r
30 import user.commons.StoreUri;
\r
31 import user.commons.nosql.NoSQLUtils;
\r
32 import user.commons.octopus.IOctopusAPI;
\r
33 import user.commons.octopus.OctopusAPI;
\r
34 import user.commons.remotestore.FtpDirectoryLister;
\r
35 import user.commons.remotestore.RemoteStoreProtocol;
\r
36 import user.jobengine.db.IItemManager;
\r
37 import user.jobengine.server.IJobEngine;
\r
38 import user.jobengine.server.IJobRuntime;
\r
40 public class CopyForArchiveNEXIORecordingsStep extends JobStep {
\r
41 private static final String MEDIATYPE = "Visszarögzített";
\r
42 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
43 private static final String STARTTIME_FORMAT = "HHmm";
\r
44 private static final String RUNDOWNDATE_FORMAT = "yyyyMMdd";
\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 ID = "id";
\r
54 private static final String EXTAGENCY = "extagency";
\r
55 private static final String RECORDDATE = "recorddate";
\r
56 private static final SimpleDateFormat startTimeformat = new SimpleDateFormat(STARTTIME_FORMAT);
\r
57 private static final SimpleDateFormat rundownDateformat = new SimpleDateFormat(RUNDOWNDATE_FORMAT);
\r
59 private OctopusAPI octopusAPI;
\r
60 private IItemManager manager;
\r
63 private FTPClient sourceFtp;
\r
64 private FTPClient targetFtp;
\r
65 private StoreUri sourceUri;
\r
66 private StoreUri targetUri;
\r
67 private int nexioKillDateDays;
\r
68 private String nexioAgency;
\r
69 private Object[] filterAgencies;
\r
70 private Marker systemMarker;
\r
72 private int check(int value, String name) {
\r
74 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
75 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
80 private String check(String value, String name) {
\r
81 if (StringUtils.isBlank(value)) {
\r
82 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
83 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
88 private void copy(RundownArchive rundownArchive) {
\r
89 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
90 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
92 copyFile(fileArchive, rundownArchive, storyArchive);
\r
93 logger.info(systemMarker, "Sikeres fájl archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());
\r
94 } catch (Exception e) {
\r
95 logger.error(systemMarker, "Az '{}' fájl archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
101 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
102 String sourceFileName = fileArchive.getFileName();
\r
103 String targetFileName = getTargetFileName(rundownArchive, sourceFileName);
\r
104 transferFile(sourceFileName, targetFileName);
\r
105 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
106 transferMetadata(targetFileName, metadata);
\r
107 createSourceKillDateFile(rundownArchive, sourceFileName);
\r
110 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
111 BasicDBObject result = new BasicDBObject();
\r
112 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
113 result.put("itemTitle", rundownArchive.getItemTitle());
\r
114 result.put("itemDescription", rundownArchive.getItemDesc());
\r
115 result.put("userName", "mediacube");
\r
117 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
118 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
119 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
121 result.put("duration", fileArchive.getDuration());
\r
122 result.put("mediaType", MEDIATYPE);
\r
126 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
127 logger.info("Create killdate/agency for {}", fileName);
\r
128 OutputStream outStream = null;
\r
130 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
131 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
132 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
133 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
134 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
135 if (outStream == null) {
\r
136 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
138 outStream.write(killDateFile);
\r
140 } catch (Exception e) {
\r
141 logger.catching(e);
\r
144 if (outStream != null)
\r
146 sourceUri.cleanUp();
\r
151 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
152 String filterAgencies, int limit, int nexioKillDateDays, String targetAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
153 systemMarker = jobRuntime.getMarker();
\r
154 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, filterAgencies, limit, nexioKillDateDays,
\r
155 targetAgency, jobEngine);
\r
156 octopusAPI = new OctopusAPI();
\r
157 List<BasicDBObject> clips = queryClips();
\r
158 processClips(clips, limit);
\r
162 private Date getScheduledStart(String clipName, Date recordDate) {
\r
163 if (StringUtils.isBlank(clipName)) {
\r
164 logger.warn(systemMarker, "A fájlnak nincs neve, ezért nem archiválható.");
\r
167 if (recordDate == null) {
\r
168 logger.warn(systemMarker, "Az '{}' fájl rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);
\r
172 Date timePart = null;
\r
174 String clipNameTime = clipName.split("_")[0];
\r
175 timePart = startTimeformat.parse(clipNameTime);
\r
176 } catch (ParseException e) {
\r
177 logger.warn(systemMarker, "A '{}' fájl neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);
\r
180 return CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart).getTime();
\r
183 private String getTargetFileName(RundownArchive rundownArchive, String sourceFileName) {
\r
184 String date = rundownDateformat.format(rundownArchive.getScheduleDate());
\r
185 return String.format("%s-%s%s", date, sourceFileName, MXFEXT);
\r
188 private RundownArchive processClip(BasicDBObject clip) {
\r
189 RundownArchive result = null;
\r
190 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);
\r
191 Date recordDate = clip.getDate(RECORDDATE);
\r
192 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
193 logger.info("Processing {} {}", clipName, recordDate);
\r
194 Date scheduledStart = getScheduledStart(clipName, recordDate);
\r
195 if (scheduledStart == null)
\r
197 DBObject rundown = octopusAPI.getRundown(scheduledStart);
\r
198 if (rundown == null) {
\r
199 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
204 result = processRundow(rundown, clipName, duration);
\r
205 } catch (Exception e) {
\r
206 logger.catching(e);
\r
207 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
214 private void processClips(List<BasicDBObject> clips, int limit) {
\r
215 logger.info(systemMarker, "A folyamat {} archiválható anyagot érzékelt.", clips.size());
\r
217 for (BasicDBObject clip : clips) {
\r
218 RundownArchive rundownArchive = processClip(clip);
\r
219 if (rundownArchive == null)
\r
222 copy(rundownArchive);
\r
225 if (current == limit)
\r
227 setProgress(current * 100 / limit);
\r
231 private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {
\r
232 BasicDBObject rundown = (BasicDBObject) r;
\r
233 long rundownID = rundown.getLong(ID);
\r
234 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
236 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
237 if (stories == null)
\r
239 RundownArchive result = new RundownArchive();
\r
241 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
242 if (StringUtils.isBlank(name))
\r
244 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
245 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
246 if (scheduledStart == null)
\r
248 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
249 result.setScheduleDate(scheduledStart);
\r
250 result.setItemHouseId(String.valueOf(rundownID));
\r
251 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
253 StringBuilder sb = new StringBuilder();
\r
254 for (DBObject s : stories) {
\r
255 BasicDBObject story = (BasicDBObject) s;
\r
256 sb.append(story.getString(IOctopusAPI.PARENT_STORY_ID));
\r
257 sb.append(" [" + story.getString(IOctopusAPI.FORMAT) + "] ");
\r
258 sb.append(story.getString(IOctopusAPI.NAME));
\r
261 StoryArchive storyArchive = new StoryArchive();
\r
262 storyArchive.setMediaHouseId(result.getItemHouseId());
\r
263 storyArchive.setMediaTitle(clipName);
\r
264 storyArchive.setMediaDesc(sb.toString());
\r
265 result.addStoryArchive(storyArchive);
\r
266 storyArchive.addFileArchive(new FileArchive(clipName, duration));
\r
270 private List<BasicDBObject> queryClips() {
\r
271 DBCollection collection = db.getCollection(NEXIOCLIPS);
\r
272 BasicDBList agencies = new BasicDBList(filterAgencies);
\r
274 Calendar now = CalendarUtils.createZeroCalendar();
\r
275 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());
\r
276 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());
\r
277 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);
\r
278 if (!cursor.hasNext())
\r
280 return ListUtils.cast(cursor.toArray());
\r
283 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
284 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
285 db = NoSQLUtils.getNoSQLDB();
\r
287 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
288 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
291 if (jobEngine == null) {
\r
292 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
293 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
295 manager = jobEngine.getItemManager();
\r
296 if (manager == null) {
\r
297 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
298 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
300 String nexioHost = System.getProperty("nexio.host");
\r
301 if (StringUtils.isBlank(nexioHost)) {
\r
302 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
303 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
305 check(nexioPort, "nexioPort");
\r
306 check(nexioUserName, "nexioUserName");
\r
307 check(nexioPassword, "nexioPassword");
\r
309 check(agencies, "filterAgencies");
\r
310 filterAgencies = agencies.split(",");
\r
312 check(limit, "limit");
\r
314 check(nexioKillDateDays, "nexioKillDateDays");
\r
315 this.nexioKillDateDays = nexioKillDateDays;
\r
316 check(nexioAgency, "nexioAgency");
\r
317 this.nexioAgency = nexioAgency;
\r
319 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
320 sourceUri.setPortNumber(nexioPort);
\r
321 sourceUri.setUserName(nexioUserName);
\r
322 sourceUri.setPassword(nexioPassword);
\r
323 if (sourceUri == null) {
\r
324 logger.error(systemMarker, "A forrás nem elérhető.");
\r
325 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
328 check(archiveFtp, "archiveFtp");
\r
329 check(archiveUserName, "archiveUserName");
\r
330 check(archivePassword, "archivePassword");
\r
332 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
333 targetUri.setUserName(archiveUserName);
\r
334 targetUri.setPassword(archivePassword);
\r
335 if (targetUri == null) {
\r
336 logger.error(systemMarker, "A cél nem elérhető.");
\r
337 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
342 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
344 logger.info("Transfer clip {}", sourceFileName);
\r
346 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
347 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
349 if (!targetFtp.enterRemotePassiveMode())
\r
350 throw new Exception("!PASV");
\r
352 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
353 if (!FTPReply.isPositiveCompletion(reply))
\r
354 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
356 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
357 throw new Exception("!SOURCE TYPE");
\r
359 reply = sourceFtp.retr(sourceFileName);
\r
360 if (!FTPReply.isPositivePreliminary(reply))
\r
361 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
363 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
364 throw new Exception("!TARGET TYPE");
\r
366 reply = targetFtp.stor(targetFileName);
\r
367 if (!FTPReply.isPositivePreliminary(reply))
\r
368 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
371 reply = sourceFtp.stat();
\r
372 if (!FTPReply.isPositiveCompletion(reply))
\r
373 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
375 //logger.info("Status: {}", sourceFtp.getReplyString());
\r
376 if (reply == 226) {
\r
379 Thread.sleep(1000);
\r
381 } catch (Exception e) {
\r
382 logger.catching(e);
\r
385 sourceUri.cleanUp();
\r
386 targetUri.cleanUp();
\r
391 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
392 logger.info("Transfer metadata {}", fileName);
\r
393 OutputStream outStream = null;
\r
395 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
396 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
397 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
398 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
399 throw new Exception("!STATUSFOLDER");
\r
402 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
403 if (outStream == null) {
\r
404 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
406 outStream.write(metadata.toString().getBytes(UTF_8));
\r
408 //targetFtp.changeToParentDirectory();
\r
409 } catch (Exception e) {
\r
410 logger.catching(e);
\r
413 if (outStream != null)
\r
415 targetUri.cleanUp();
\r