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
19 import com.ibm.nosql.json.api.BasicDBList;
\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 import com.ibm.nosql.json.api.QueryBuilder;
\r
27 import user.commons.CalendarUtils;
\r
28 import user.commons.ListUtils;
\r
29 import user.commons.StoreUri;
\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
39 public class CopyForArchiveNEXIORecordingsStep extends JobStep {
\r
40 private static final String MEDIATYPE_RECORDING = "Visszarögzített";
\r
41 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
42 private static final String STARTTIME_FORMAT = "HHmm";
\r
43 private static final Logger logger = LogManager.getLogger();
\r
44 private static final String UTF_8 = "utf-8";
\r
45 private static final String JSON_EXT = ".json";
\r
46 private static final String XML_EXT = ".xml";
\r
47 private static final String DURATION = "duration";
\r
48 private static final String MXFEXT = ".MXF";
\r
49 private static final String NEXIOCLIPS = "nexioclips";
\r
50 private static final String LONGNAMEID = "longnameid";
\r
51 private static final String ID = "id";
\r
52 private static final String EXTAGENCY = "extagency";
\r
53 private static final String RECORDDATE = "recorddate";
\r
54 private static final SimpleDateFormat startTimeformat = new SimpleDateFormat(STARTTIME_FORMAT);
\r
56 private OctopusAPI octopusAPI;
\r
57 private IItemManager manager;
\r
60 private FTPClient sourceFtp;
\r
61 private FTPClient targetFtp;
\r
62 private StoreUri sourceUri;
\r
63 private StoreUri targetUri;
\r
64 private int nexioKillDateDays;
\r
65 private String nexioAgency;
\r
66 private Object[] filterAgencies;
\r
68 private int check(int value, String name) {
\r
70 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere 0.", name);
\r
71 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
76 private String check(String value, String name) {
\r
77 if (StringUtils.isBlank(value)) {
\r
78 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere üres.", name);
\r
79 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
84 private void copy(RundownArchive rundownArchive) {
\r
85 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
86 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
88 copyFile(fileArchive, rundownArchive, storyArchive);
\r
89 logger.info(getMarker(), "Sikeres anyag archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());
\r
90 } catch (Exception e) {
\r
91 logger.error(getMarker(), "Az '{}' anyag archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
97 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
98 String origFileName = fileArchive.getFileName();
\r
99 String videoFileName = origFileName + MXFEXT;
\r
101 transferFile(videoFileName, videoFileName);
\r
102 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
103 transferMetadata(videoFileName, metadata);
\r
104 createSourceKillDateFile(rundownArchive, origFileName);
\r
107 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
108 BasicDBObject result = new BasicDBObject();
\r
109 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
110 result.put("itemTitle", rundownArchive.getItemTitle());
\r
111 result.put("itemDescription", rundownArchive.getItemDesc());
\r
112 result.put("userName", "mediacube");
\r
114 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
115 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
116 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
118 result.put("duration", fileArchive.getDuration());
\r
119 result.put("mediaType", MEDIATYPE_RECORDING);
\r
123 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
124 logger.info("Create killdate/agency for {}", fileName);
\r
125 OutputStream outStream = null;
\r
127 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
128 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
129 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
130 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
131 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
132 if (outStream == null) {
\r
133 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
135 outStream.write(killDateFile);
\r
137 } catch (Exception e) {
\r
138 logger.catching(e);
\r
141 if (outStream != null)
\r
143 sourceUri.cleanUp();
\r
148 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
149 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
150 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, agencies, limit, nexioKillDateDays, nexioAgency,
\r
152 octopusAPI = new OctopusAPI();
\r
153 List<BasicDBObject> clips = queryClips();
\r
154 processClips(clips, limit);
\r
158 private Date getScheduledStart(String clipName, Date recordDate) {
\r
159 if (StringUtils.isBlank(clipName))
\r
160 logger.warn(getMarker(), "A anyagnak nincs neve, ezért nem archiválható.", clipName);
\r
161 if (recordDate == null)
\r
162 logger.warn(getMarker(), "A {} anyag rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);
\r
164 Date timePart = null;
\r
166 String clipNameTime = clipName.split("_")[0];
\r
167 timePart = startTimeformat.parse(clipNameTime);
\r
168 } catch (ParseException e) {
\r
169 logger.warn(getMarker(), "A {} anyag neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);
\r
172 return CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart).getTime();
\r
175 private RundownArchive processClip(BasicDBObject clip) {
\r
176 RundownArchive result = null;
\r
177 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);
\r
178 Date recordDate = clip.getDate(RECORDDATE);
\r
179 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
180 logger.info("Processing {} {}", clipName, recordDate);
\r
181 Date scheduledStart = getScheduledStart(clipName, recordDate);
\r
182 if (scheduledStart == null)
\r
184 DBObject rundown = octopusAPI.getRundown(scheduledStart);
\r
185 if (rundown == null) {
\r
186 logger.warn(getMarker(), "A '{}' anyaghoz nem talllható tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
191 result = processRundow(rundown, clipName, duration);
\r
192 } catch (Exception e) {
\r
193 logger.catching(e);
\r
194 logger.error(getMarker(), "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
201 private void processClips(List<BasicDBObject> clips, int limit) {
\r
202 logger.info(getMarker(), "A folyamat {} archiválható anyagot érzékelt.", clips.size());
\r
204 for (BasicDBObject clip : clips) {
\r
205 RundownArchive rundownArchive = processClip(clip);
\r
206 if (rundownArchive == null)
\r
209 copy(rundownArchive);
\r
212 if (current == limit)
\r
214 setProgress(current * 100 / limit);
\r
218 private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {
\r
219 BasicDBObject rundown = (BasicDBObject) r;
\r
220 long rundownID = rundown.getLong(ID);
\r
221 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
223 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
224 if (stories == null)
\r
226 RundownArchive result = new RundownArchive();
\r
228 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
231 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
232 if (StringUtils.isBlank(name))
\r
234 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
235 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
236 if (scheduledStart == null)
\r
238 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
239 result.setScheduleDate(scheduledStart);
\r
240 result.setItemHouseId(String.valueOf(id));
\r
241 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
243 StringBuilder sb = new StringBuilder();
\r
244 for (DBObject s : stories) {
\r
245 BasicDBObject story = (BasicDBObject) s;
\r
246 sb.append(story.getString(IOctopusAPI.PARENT_STORY_ID));
\r
247 sb.append(" [" + story.getString(IOctopusAPI.FORMAT) + "] ");
\r
248 sb.append(story.getString(IOctopusAPI.NAME));
\r
251 StoryArchive storyArchive = new StoryArchive();
\r
252 storyArchive.setMediaHouseId(result.getItemHouseId());
\r
253 storyArchive.setMediaTitle(clipName);
\r
254 storyArchive.setMediaDesc(sb.toString());
\r
255 result.addStoryArchive(storyArchive);
\r
256 storyArchive.addFileArchive(new FileArchive(clipName, duration));
\r
260 private List<BasicDBObject> queryClips() {
\r
261 DBCollection collection = db.getCollection(NEXIOCLIPS);
\r
262 BasicDBList agencies = new BasicDBList(filterAgencies);
\r
264 Calendar now = CalendarUtils.createZeroCalendar();
\r
265 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());
\r
266 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());
\r
267 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);
\r
268 if (!cursor.hasNext())
\r
270 return ListUtils.cast(cursor.toArray());
\r
273 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
274 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
275 db = NoSQLUtils.getNoSQLDB();
\r
277 logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");
\r
278 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
281 if (jobEngine == null) {
\r
282 logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");
\r
283 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
285 manager = jobEngine.getItemManager();
\r
286 if (manager == null) {
\r
287 logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");
\r
288 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
290 String nexioHost = System.getProperty("nexio.host");
\r
291 if (StringUtils.isBlank(nexioHost)) {
\r
292 logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");
\r
293 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
295 check(nexioPort, "nexioPort");
\r
296 check(nexioUserName, "nexioUserName");
\r
297 check(nexioPassword, "nexioPassword");
\r
299 check(agencies, "agencies");
\r
300 filterAgencies = agencies.split(",");
\r
302 check(limit, "limit");
\r
304 check(nexioKillDateDays, "nexioKillDateDays");
\r
305 this.nexioKillDateDays = nexioKillDateDays;
\r
306 check(nexioAgency, "nexioAgency");
\r
307 this.nexioAgency = nexioAgency;
\r
309 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
310 sourceUri.setPortNumber(nexioPort);
\r
311 sourceUri.setUserName(nexioUserName);
\r
312 sourceUri.setPassword(nexioPassword);
\r
313 if (sourceUri == null) {
\r
314 logger.error(getMarker(), "A forrás nem elérhető.");
\r
315 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
318 check(archiveFtp, "archiveFtp");
\r
319 check(archiveUserName, "archiveUserName");
\r
320 check(archivePassword, "archivePassword");
\r
322 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
323 targetUri.setUserName(archiveUserName);
\r
324 targetUri.setPassword(archivePassword);
\r
325 if (targetUri == null) {
\r
326 logger.error(getMarker(), "A cél nem elérhető.");
\r
327 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
332 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
334 logger.info("Transfer clip {}", sourceFileName);
\r
336 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
337 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
338 if (!targetFtp.enterRemotePassiveMode())
\r
339 throw new Exception("!PASV");
\r
341 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
342 if (!FTPReply.isPositiveCompletion(reply))
\r
343 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
345 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
346 throw new Exception("!SOURCE TYPE");
\r
348 reply = sourceFtp.retr(sourceFileName);
\r
349 if (!FTPReply.isPositivePreliminary(reply))
\r
350 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
352 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
353 throw new Exception("!TARGET TYPE");
\r
355 reply = targetFtp.stor(targetFileName);
\r
356 if (!FTPReply.isPositivePreliminary(reply))
\r
357 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
360 reply = sourceFtp.stat();
\r
361 if (!FTPReply.isPositiveCompletion(reply))
\r
362 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
364 logger.info("Status: {}", sourceFtp.getReplyString());
\r
365 if (reply == 226) {
\r
368 Thread.sleep(1000);
\r
370 } catch (Exception e) {
\r
371 logger.catching(e);
\r
374 sourceUri.cleanUp();
\r
375 targetUri.cleanUp();
\r
380 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
381 logger.info("Transfer metadata {}", fileName);
\r
382 OutputStream outStream = null;
\r
384 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
385 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
386 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
387 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
388 throw new Exception("!STATUSFOLDER");
\r
391 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
392 if (outStream == null) {
\r
393 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
395 outStream.write(metadata.toString().getBytes(UTF_8));
\r
397 //targetFtp.changeToParentDirectory();
\r
398 } catch (Exception e) {
\r
399 logger.catching(e);
\r
402 if (outStream != null)
\r
404 targetUri.cleanUp();
\r