Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.dshare.kolumbus.gui.deployment.mediaset.listener.sportmediaset;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.jms.Message;
- import javax.jms.MessageListener;
- import org.apache.activemq.command.ActiveMQTextMessage;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpMethod;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import it.elemedia.kpm3.client.Kpm3Client;
- import it.elemedia.kpm3.client.Kpm3ClientException;
- import it.elemedia.kpm3.core.model.Categories;
- import it.elemedia.kpm3.core.model.Category;
- import it.elemedia.kpm3.core.model.Entry;
- import it.elemedia.kpm3.core.model.Feed;
- import it.elemedia.kpm3.core.model.Link;
- import it.elemedia.kpm3.core.model.Status;
- import it.elemedia.kpm3.core.model.Type;
- public class MediaVideoMessageReceiver implements MessageListener {
- @Autowired
- private Kpm3Client kpm3Client;
- private static Logger logger = LoggerFactory.getLogger(MediaVideoMessageReceiver.class);
- @Value("${sportmediaset.video.mediaset.url}")
- private String mediaVideoUrl;
- @Value("${mediavideo.cms.host}")
- private String cmsHsot;
- @Value("${mediavideo.hp.max.size}")
- private int numberOfHpMediavideoSize;
- @Value("${mediavideo.start.sequence}")
- private int numberOfSequenceDefault;
- @Value("${mediavideo.strillo.template}")
- private String templateStrillo;
- @Value("${mediavideo.category.term}")
- private String categoryTermMediavideo;
- private final String ZONEMEDIAVIDEO="mediavideo";
- private final String CATEGORY_TERM = "categoryTerm";
- private final String DRAFT = "draft";
- private final String CATEGORY = "category";
- private final String TEMPLATE = "template";
- private final String ZONE = "zone";
- private final String collectionName="sportmediaset";
- @Override
- public void onMessage(Message message) {
- logger.info("BEGIN NewsPublishedMessageReceiver.onMessage");
- if (message instanceof ActiveMQTextMessage) {
- try {
- ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
- Map<String, Object> mapJsonResult = textMessage.getProperties();
- if (mapJsonResult.size() != 0) {
- logger.info("id: " + mapJsonResult.get("id"));
- Long id = (Long) mapJsonResult.get("id");
- Map params=new HashMap();
- params.put("ids", id);
- Feed feed = kpm3Client.getContents(params);
- if (feed != null && feed.getEntries() != null
- && !feed.getEntries().isEmpty()) {
- for (Entry entry: feed.getEntries()) {
- Entry completeEntry = kpm3Client.getContent(entry.getId()).getEntries().get(0);
- logger.info("enumediavideopag: " + completeEntry.get("enumediavideopag"));
- if(completeEntry.get("enumediavideopag")!=null && "Pag.tlv".equalsIgnoreCase((String)completeEntry.get("enumediavideopag"))) {
- //Mediavideo attivo
- logger.info("update HP Mediavideo sportmediaset");
- Map<String, String> paramsHp = new HashMap<String, String>();
- paramsHp.put("categoryTerm",categoryTermMediavideo);
- Categories categories = kpm3Client.getCategories(collectionName, paramsHp);
- if (categories != null && categories.getCategories() != null && categories.getCategories().size() > 0) {
- Feed feedMediaVideo=getCover(collectionName,categoryTermMediavideo,false,null,null);
- if(feedMediaVideo!=null){
- List<Entry> listOfEntryInToZone = feedMediaVideo.getEntries();
- List<Entry> storicoMediaVideo=listOfEntryInToZone;
- //pub new strillo
- Entry strillo=this.createStrilloFromEntry(completeEntry,"4",listOfEntryInToZone);
- if(strillo!=null){
- logger.info("STRILLO CREATO CON ID:"+strillo.getKpm3id());
- //check se esistono strilli nel HP
- if(storicoMediaVideo!=null){
- if(storicoMediaVideo.size()==0){
- //add strillo prima pos
- storicoMediaVideo.add(strillo);
- }
- else{
- //shifto lista
- storicoMediaVideo=shiftList(storicoMediaVideo,numberOfHpMediavideoSize,strillo);
- }
- //metodo che verifica se aggiornare sequenza degli strilli
- verifyAndUpdateSequenceOfStrilli(storicoMediaVideo);
- //pub lista strilli
- publishListOfStrilliZoneMediavideo(storicoMediaVideo);
- }
- }
- }
- }
- //TODO: aggiornare la HP aggiungendo in cima l'articolo corrente (ed eventualmente eliminando l'ultimo)
- //TODO: recuperare i primi 5 strilli nella HP e inviarli al bercgi per chiamare il controller che genera il bacino
- //TODO: recuperare i successivi 10 strilli nella HP e inviarli al bercgi per chiamare il controller che genera il secondo bacino
- //TODO per ogni strillo presente nella HP chiamare la cgi per generare la singola pagina
- // String collectionName = Utility.getCollectionNameByIdContent(feed.getEntries().get(0).getId());
- //
- // String path = completeEntry.getLink(Link.REL_ALTERNATE).getPath();
- // path = path.replaceAll(".shtml", "");
- // String sectPath = path.substring(1, path.lastIndexOf("/"));
- // String pagName = path.substring(path.lastIndexOf("/")+1, path.length());
- // String mode="p";
- // call(String.format(mediaVideoUrl, cmsHsot, collectionName+"/mediavideo", collectionName, sectPath, pagName, completeEntry.getKpm3id(),mode));
- //modifico il valore del flag mediavideo su NO
- completeEntry.set("enumediavideopag",null);
- kpm3Client.modifyContent(completeEntry);
- }
- }
- }
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- logger.info("END NewsPublishedMessageReceiver.onMessage ");
- }
- /**
- * Metodo che verifica se updatare lista strilli HP mediavideo
- * @param storicoMediaVideo
- */
- private void verifyAndUpdateSequenceOfStrilli(List<Entry> storicoMediaVideo) {
- List<Entry> updatedStrilliList=new ArrayList<Entry>();
- boolean update=false;
- //controllo se primo strilli(pag 201) contiene sequenza=2, se si aggiornare tutti strilli con num sequenza agg
- if (storicoMediaVideo!=null && storicoMediaVideo.size()>0) {
- Entry firstStrillo=storicoMediaVideo.get(0);
- if(firstStrillo!=null && firstStrillo.getCategories("true")!=null && firstStrillo.getCategories("true").size()>0){
- String sequence=firstStrillo.getCategories("true").get(0).getSequence();
- if("2".equalsIgnoreCase(sequence)){
- update=true;
- }
- }
- }
- //se update =true aggiorno lista strilli
- if(update){
- int startSequence=numberOfSequenceDefault;
- for (Entry strlToUpdate : storicoMediaVideo) {
- if(strlToUpdate!=null && strlToUpdate.getCategories("true")!=null && strlToUpdate.getCategories("true").size()>0){
- //add 50 al proprio num di sequenza
- String sequence=strlToUpdate.getCategories("true").get(0).getSequence();
- int nowSequence = Integer.parseInt(sequence);
- nowSequence=nowSequence+startSequence;
- String updateSequence=Integer.toString(nowSequence);
- strlToUpdate.getCategories("true").get(0).setSequence(updateSequence);
- updatedStrilliList.add(strlToUpdate);
- }
- }
- //update entry Strilli
- updateStrilli( updatedStrilliList);
- }
- }
- /**
- * Metodo che aggiorna strilli nel HP mediavideo
- * @param storicoMediaVideo
- */
- private void updateStrilli(List<Entry> storicoMediaVideo) {
- for (Entry strlToUpdate : storicoMediaVideo) {
- Entry res =null;
- try{
- strlToUpdate.setUpdated(strlToUpdate.getCreated());
- res=kpm3Client.modifyContent(strlToUpdate);
- }catch(Exception e){
- logger.info("errore nella pubblciazone"+ e);
- }
- if (res != null) {
- logger.info("Success updated strillo nella hp mediavideo: "+res.getId());
- }else{
- logger.error("Error when updated strillo nella hp mediavideo: "+res.getKpm3id());
- }
- }
- }
- /**
- * Rimuovo strilli, per non visualizzarli nel hp mediavideo
- * @param storicoMediaVideo
- */
- private void clearZoneMediaVideoAndRemoveStrilli(List<Entry> storicoMediaVideo){
- for (Entry strlToRemove : storicoMediaVideo) {
- Entry res =null;
- try{
- res=kpm3Client.deleteContent(strlToRemove.getId());
- }catch(Exception e){
- logger.info("errore nella pubblciazone"+ e);
- }
- if (res != null) {
- logger.info("Success removed strillo nella hp mediavideo: "+strlToRemove.getId());
- }else{
- logger.error("Error when removed strillo nella hp mediavideo: "+strlToRemove.getKpm3id());
- }
- }
- }
- /**
- * Metodo che pubblica lista storico mediavideo
- * @param storicoMediaVideo
- */
- private void publishListOfStrilliZoneMediavideo(List<Entry> storicoMediaVideo) {
- for (Entry strillo : storicoMediaVideo) {
- Entry res =null;
- try{
- //setto data update, per rippubblicare strillo
- strillo.setUpdated(strillo.getCreated());
- res=kpm3Client.modifyContent(strillo);
- }catch(Exception e){
- logger.info("errore nella pubblciazone"+ e);
- }
- if (res != null) {
- logger.info("Success publish strillo nella hp mediavideo: "+strillo.getId());
- }else{
- logger.error("Error when publish strillo nella hp mediavideo: "+strillo.getKpm3id());
- }
- }
- }
- /**
- * Metodo che ritorna tutti i feed all'internzo della zona
- * @param collectionName
- * @param category
- * @param draft
- * @param template
- * @param zone
- * @return
- * @throws Exception
- */
- private Feed getCover(String collectionName, String category, boolean draft,
- String template, String zone) throws Exception {
- Feed feed = null;
- try {
- HashMap<String, String> map = new HashMap<String, String>();
- map.put(CATEGORY_TERM, category);
- map.put(DRAFT, Boolean.toString(draft));
- map.put(CATEGORY, Boolean.TRUE.toString());
- if(template!=null && !"".equals(template)
- && zone!=null && !"".equals(zone)) {
- map.put(TEMPLATE, template);
- map.put(ZONE, zone);
- }
- feed = kpm3Client.getContents(collectionName, map);
- } catch (Exception ex) {
- throw new Exception("Impossibile ottenere il contenuto",ex);
- }
- return feed;
- }
- /**
- * Metodo che ritorna entry di tipo strillo,partendo da entry di tipo articolo
- * @param e entry
- * @return
- */
- private Entry createStrilloFromEntry(Entry e,String idBlock,List<Entry> listOfEntryInToZone){
- //logica gestione sequenza degli strilli
- String sequenceOfStrillo=Integer.toString(this.numberOfSequenceDefault);
- //se esiste gia contenuto , calcolo sequenza corretta
- if(listOfEntryInToZone!=null && listOfEntryInToZone.size()>0){
- Entry firstStrillo=listOfEntryInToZone.get(0);
- if(firstStrillo!=null && firstStrillo.getCategories("true")!=null && firstStrillo.getCategories("true").size()>0){
- Category cat=firstStrillo.getCategories("true").get(0);
- //get ultimo strillo con sequenza minore(pagina 201) e rimuovo 1 per inserire il nuovo strillo in prima pos nel HP
- String tempSequnce=cat.getSequence();
- int initSequence = Integer.parseInt(tempSequnce);
- int newValueOfSequence=initSequence-1;
- sequenceOfStrillo=Integer.toString(newValueOfSequence);
- }
- }
- Entry strillo=new Entry();
- strillo.setType(Type.TYPE_STRILLO);
- if(e.get("titlemv")!=null){
- strillo.setTitle(e.get("titlemv").toString());
- }else{
- strillo.setTitle(e.getTitle());
- }
- strillo.setSummary(e.getSummary());
- Category cat =null;
- try{
- cat = getCategory(categoryTermMediavideo);
- }
- catch(Exception ecc){
- logger.info("Errore nella creazione dellac categoria dello strillo "+ecc.getMessage());
- }
- if(cat!=null && e.getCategories()!=null && e.getCategories("true")!=null && e.getCategories("true").size()>0){
- cat.setTemplate(templateStrillo);
- cat.setPrimary("true");
- cat.setZone(this.ZONEMEDIAVIDEO);
- cat.setBlock(idBlock);
- cat.setEnabled("true");
- cat.setSequence(sequenceOfStrillo);
- cat.setPubFromDate(getKolumbusPubFromDateFromCategory(e.getCategories("true").get(0)));
- strillo.addCategory(cat);
- strillo.setCreated(getKolumbusPubFromDateFromCategory(e.getCategories("true").get(0)));
- strillo.setDraft(false);
- strillo.setStatus(Status.PUBBLICATO);
- Link redEdit=e.getLink(Link.REL_EDIT);
- if(redEdit==null){
- logger.error("ERRORE GRAVE il Link rel-edit is empty from entry"+e.getKpm3id());
- }
- //creo link con entry principale
- Link linkEdit=new Link();
- linkEdit.setRel(Link.REL_RELATED);
- linkEdit.setHref(redEdit.getHref());
- linkEdit.setCollection("sportmediaset");
- linkEdit.setPath(this.CATEGORY_TERM);
- linkEdit.setPos(1);
- //add link with principal entry
- strillo.addLink(linkEdit);
- try {
- return kpm3Client.publishContent(strillo);
- } catch (Kpm3ClientException ecc) {
- logger.info("Errore nella creazione dello strillo "+ecc.getMessage());
- }
- }
- return null;
- }
- /**
- * Metodo che shifta lista verso sx
- * @param listOfEntryInToZone
- * @param maxSizeOfList
- * @param strilloToPub
- * @return
- */
- private List<Entry> shiftList(List<Entry> listOfEntryInToZone,int maxSizeOfList,Entry strilloToPub){
- List<Entry> storico=new ArrayList<Entry>();
- List<Entry> listEntryToRemove=new ArrayList<Entry>();
- //add new strillo to list
- storico.add(0, strilloToPub);
- storico.addAll(1, listOfEntryInToZone.subList(0,listOfEntryInToZone.size()));
- //se numero strilli = max,allora shift a sx eliminando ultimo
- if(storico.size()>maxSizeOfList){
- List<Entry> storicoUpdated=new ArrayList<Entry>();
- //copio tutti gli strilli da rimuovere
- storicoUpdated.addAll(0,storico.subList(0,maxSizeOfList));
- //creo lista con elementi da rimuovere
- listEntryToRemove.addAll(0,storico.subList(maxSizeOfList,maxSizeOfList+1));
- storico=storicoUpdated;
- //rimuovo lista di strilli in eccesso
- clearZoneMediaVideoAndRemoveStrilli(listEntryToRemove);
- }
- return storico;
- }
- public Integer call(String url) throws Exception {
- logger.info("calling: " + url);
- String body = "";
- HttpClient httpClient = new HttpClient();
- HttpMethod httpMethod = new GetMethod(url);
- int responseCode = httpClient.executeMethod(httpMethod);
- byte[] responseBody = httpMethod.getResponseBody();
- body = new String(responseBody, "UTF-8");
- httpMethod.releaseConnection();
- logger.info("response : " + responseCode);
- return responseCode;
- }
- /**
- * Metodo che trasforma le date lette dal xml in date accettate da kolumbus
- * @param dateToParse
- * @return
- */
- private String getKolumbusPubFromDateFromCategory(Category cat){
- return cat.getPubFromDate();
- }
- /**
- * Metodo che restituisce categoria
- * @param categoryToPublish
- * @return
- * @throws Exception
- */
- private Category getCategory(String categoryToPublish) throws Exception{
- Map<String, String> params=new HashMap<String, String>();
- params.put("categoryTerm", categoryToPublish);
- Categories newCategories = null;
- try {
- String collection = categoryToPublish.split("/")[1];
- newCategories = kpm3Client.getCategories(collection, params);
- } catch (Kpm3ClientException e) {
- logger.error(e.getMessage(),e);
- }
- if (newCategories != null && newCategories.getCategories() != null && newCategories.getCategories().size() > 0) {
- return (Category) newCategories.getCategories().get(0);
- }
- throw new Exception("category not found => "+categoryToPublish);
- }
- // /**
- // * Riordino la sequenza di tutte le entry del Hp, per tenerla aggiornata
- // * @param listOfEntryInToZone
- // * @return
- // */
- // private List<Entry> reorderSequence(List<Entry> listOfEntryInToZone) {
- // List<Entry> tempListStorico=new ArrayList<Entry>();
- //
- // for(Entry entry:listOfEntryInToZone){
- // if(entry.getCategories()!=null && entry.getCategories().size()>0){
- // Category cat = entry.getCategories().get(0);
- // int nowSequence=Integer.parseInt(cat.getSequence())+2;
- // cat.setSequence(Integer.toString(nowSequence));
- // List<Category> list=new ArrayList<Category>();
- // list.add(cat);
- // entry.setCategories(list);
- // tempListStorico.add(entry);
- // }
- // }
- // return tempListStorico;
- // }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement