Subversion Repositories SmartDukaan

Rev

Rev 455 | Rev 1051 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.creation.controllers;

import in.shop2020.creation.util.ContentValidator;
import in.shop2020.metamodel.util.CreationUtils;
import in.shop2020.metamodel.core.Media;
import in.shop2020.metamodel.core.Entity;
import in.shop2020.metamodel.core.FreeformContent;
import in.shop2020.metamodel.core.Slide;
import in.shop2020.metamodel.definitions.Catalog;
import in.shop2020.metamodel.definitions.EntityContainer;
import in.shop2020.metamodel.util.CN;
import in.shop2020.metamodel.util.ExpandedEntity;
import in.shop2020.util.DBUtils;
import in.shop2020.util.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.io.IOUtils;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import org.apache.struts2.views.xslt.ArrayAdapter;

/**
 * @author naveen
 *
 */
@Results({
    @Result(name="success", type="redirectAction", 
                params = {"actionName" , "media"}),
    @Result(name="redirect", location="${url}", type="redirect")
})
public class MediaController {
        
        /**
         * 
         */
        private static Log log = LogFactory.getLog(MediaController.class);
        
        /**
         * 
         */
        private String id;
        private String entityID;
        private String slideID;
        private String label;
        private String title;
        private String videoType;
        private File pic;
        private String picContentType;
        private String picFileName;
        private String fileSystemPath;
        private String redirectURL;
        private String errorString;
        private String youtubeURL;

        private Map<String, Media> rawMedia;

        
    // GET /media
    public HttpHeaders index() {
        log.info("MediaController.index");
        
        return new DefaultHttpHeaders("index").disableCaching();
    }

    // GET /media
    public String create() {
        log.info("MediaController.create");
        
        try {
                log.info("getPicFileName:" + this.getPicFileName());
                log.info("getFileSystemPath:" + this.getFileSystemPath());
                log.info("getPicContentType:" + this.getPicContentType());
                
                boolean hasdata = false;
                String location = "";
                String type = "";
                if(this.getPic() != null) {
                        type = "image";
                        location = this.storeFile();
                        hasdata = true;
                } 
                else if(this.getYoutubeURL() != null) {
                        type = "youtube";
                        location = this.getYoutubeURL();
                        hasdata = true;
                }
                
                log.info("location:" + location);
                log.info("label:" + this.getLabel());
                log.info("getTitle:" + this.getTitle());
                log.info("getVideoType:" + this.getVideoType());
                
                if(hasdata) {
                        Media media = new Media(this.getLabel(), type, location);
                        media.setTitle(this.getTitle());
                        if(this.getPic() != null) {
                                media.setFileName(this.getPicFileName());
                                media.setContentType(this.getPicContentType());
                                media.setVideoType("");
                        }
                        else {
                                media.setFileName("");
                                media.setContentType("");
                                media.setVideoType(this.getVideoType());
                        }
                        this.addMedia(media);
                        log.info("entity ID:" + this.entityID);
                        log.info("slide ID:" + this.slideID);
                        
                        /*
                        String contentLabel = "";
                        log.info("type filename and location :" + media.getType() + "~!~" + media.getFileName() + media.getLocation());
                        
                        if(media.getType().compareTo("image")==0){
                                contentLabel = media.getLabel() + "~!~" + media.getFileName();
                                log.info("Type is image :" + contentLabel);
                        }
                        if(media.getType().compareTo("youtube")==0){
                                contentLabel = media.getLabel() + "~!~" + media.getLocation();
                                log.info("Type is youtube :" + contentLabel);
                        }
                        */
                        
                        
                        Entity entity = CreationUtils.getEntity(Long.parseLong(this.entityID));
                        
                        Slide slide = entity.getSlide(Long.parseLong(this.slideID));
                        if(slide == null){
                                slide = new Slide(Long.parseLong(this.getSlideID()));
                                entity.addSlide(slide);
                        }
                        FreeformContent freeformContent = slide.getFreeformContent();
                        if(freeformContent == null){
                                freeformContent = new FreeformContent();
                                slide.setFreeformContent(freeformContent);
                        }
                        freeformContent.addMedia(media.getType(), media.getLabel());
                        entity.getSlide(Long.parseLong(slideID)).setFreeformContent(freeformContent);
                        updateEntity(entity);
                        //CreationUtils.storeEntity(entity);
                }

                } catch (Exception e) {
                        log.error(CreationUtils.getStackTrace(e));
                        this.setErrorString(CreationUtils.getStackTrace(e));
                        return "fatal";
                }

                this.redirectURL = "media?entityID=" + this.getEntityID() + "&slideID=" + this.getSlideID();;
        
                return "redirect";
    }

    // DELETE /entity/1000001
    /**
     * 
     */
    public String destroy() {
        log.info("MediaController.destroy");
        try {
                long entityID = Long.parseLong(this.getEntityID());
                long slideID = Long.parseLong(this.getSlideID());
                String label = this.getId();
                log.info("label:" + label);
                log.info("slide:" + label);
                log.info("entity:" + label);
                
                label = URLDecoder.decode(label, "UTF-8");
                
                Media media = CreationUtils.getRawMedia(entityID).get(label);
                CreationUtils.removeMedia(entityID, label);
                /*
                String contentLabel ="";
                if(media.getType().compareTo("image") == 0){
                        contentLabel = media.getLabel() + "~!~" + media.getFileName();
                        log.info("Type is image :" + contentLabel);
                }
                if(media.getType().compareTo("youtube") == 0){
                        contentLabel = media.getLabel() + "~!~" + media.getLocation();
                        log.info("Type is youtube :" + contentLabel);
                }
                        */
                        
                Entity entity = CreationUtils.getEntity(Long.parseLong(this.entityID));
                        FreeformContent freeformContent = entity.getSlide(slideID).getFreeformContent(); 
                        freeformContent.removeMedia(media.getType(), label);
                        entity.getSlide(slideID).setFreeformContent(freeformContent);
                        updateEntity(entity);
                        //CreationUtils.storeEntity(entity);
                        
                } catch (Exception e) {
                        log.error(CreationUtils.getStackTrace(e));
                        this.setErrorString(CreationUtils.getStackTrace(e));
                        return "fatal";
                }

                this.redirectURL = "media?entityID=" + this.getEntityID() + "&slideID=" + this.getSlideID();
        
                return "redirect";
    }
    /**
     * 
     * @return
     * @throws Exception 
     */
    public Collection<Media> getMedia() throws Exception {
        Collection<Media> allMedia = null;
        Entity entity = CreationUtils.getEntity(Long.parseLong(getEntityID()));
        if(entity != null){
                Slide slide = entity.getSlide(Long.parseLong(getSlideID()));
                if(slide != null && slide.getFreeformContent() != null){
                        List<String> labels = slide.getFreeformContent().getAllLabels();
                        
                        if(labels != null){
                                
                                if(this.rawMedia == null) {
                                        this.rawMedia = this.getRawMedia();
                                }
                        
                                if(this.rawMedia != null) {
                                        allMedia = new ArrayList<Media>();
                                        for(String label: labels){
                                                allMedia.add(this.rawMedia.get(label));
                                        }
                                }
                        }
                }
        }
            return allMedia;
    }
        /**
         * @param id the id to set
         */
        public void setSlideID(String id) {
                this.slideID = id;
                log.info("token 2:" + this.slideID);

//              StringTokenizer tokenizer = new StringTokenizer(id,"_");
//              log.info("id:" + id);
//              log.info("token 1:" + tokenizer.nextToken());
//              log.info("token 2:" + tokenizer.nextToken());
//              this.slideID = tokenizer.nextToken();
//              log.info("token 2:" + this.slideID);
        }
        /**
         * @return the id
         */
        public String getSlideID() {
                return slideID;
        }
        /**
         * @param id the id to set
         */
        public void setEntityID(String id) {
                this.entityID = id;
                log.info("token 2:" + this.entityID);
                
//              StringTokenizer tokenizer = new StringTokenizer(id,"_");
//              this.entityID = tokenizer.nextToken();
//              log.info("id:" + id);
//              log.info("token 2:" + this.entityID);
//              log.info("token 2:" + tokenizer.nextToken());
//              this.slideID = tokenizer.nextToken();
//              log.info("token 3:" + this.slideID);
        }
        /**
         * @return the id
         */
        public String getEntityID() {
                return entityID;
        }
        /**
         * @param label the label to set
         */
        public void setLabel(String label) {
                this.label = label;
        }

        /**
         * @return the label
         */
        public String getLabel() {
                return label;
        }

        public void setTitle(String title) {
                this.title = title;
        }

        public String getTitle() {
                return title;
        }

        public void setVideoType(String videoType) {
                this.videoType = videoType;
        }

        public String getVideoType() {
                return videoType;
        }

        /**
         * @param pic the pic to set
         */
        public void setPic(File pic) {
                this.pic = pic;
        }
        /**
         * @return the pic
         */
        public File getPic() {
                return pic;
        }
        /**
         * @param picContentType the picContentType to set
         */
        public void setPicContentType(String picContentType) {
                this.picContentType = picContentType;
        }
        /**
         * @return the picContentType
         */
        public String getPicContentType() {
                return picContentType;
        }
        /**
         * @param picFileName the picFileName to set
         */
        public void setPicFileName(String picFileName) {
                this.picFileName = picFileName;
        }
        /**
         * @return the picFileName
         */
        public String getPicFileName() {
                return picFileName;
        }
        /**
         * @param fileSystemPath the fileSystemPath to set
         */
        public void setFileSystemPath(String fileSystemPath) {
                this.fileSystemPath = fileSystemPath;
        }
        /**
         * @return the fileSystemPath
         */
        public String getFileSystemPath() {
                return fileSystemPath;
        }

    /**
         * @param youtubeURL the youtubeURL to set
         */
        public void setYoutubeURL(String youtubeURL) {
                this.youtubeURL = youtubeURL;
        }

        /**
         * @return the youtubeURL
         */
        public String getYoutubeURL() {
                return youtubeURL;
        }

        public String getUrl() {
        return this.redirectURL;
    }

        /**
         * @param errorString the exceptionString to set
         */
        public void setErrorString(String errorString) {
                this.errorString = errorString;
        }

        /**
         * @return the exceptionString
         */
        public String getErrorString() {
                return errorString;
        }
        
        /**
         * 
         * @param media
         * @throws Exception
         */
        private void addMedia(Media media) throws Exception {
                Map<String, Media> rawMedia = this.getRawMedia();
                
                if(rawMedia == null) {
                        rawMedia = new HashMap<String, Media>();
                }
                rawMedia.put(media.getLabel(), media);
                
                DBUtils.store(rawMedia, Utils.CONTENT_DB_PATH + "media" + File.separator + this.getEntityID() + 
                                ".ser");
        }

    
    /**
     * @throws Exception 
     * 
     */
    private Map<String, Media> getRawMedia() throws Exception {
        if(this.rawMedia == null) {
                this.rawMedia = CreationUtils.getRawMedia(
                                Long.parseLong(this.getEntityID()));
        }
        
        return this.rawMedia;
    }
    
        /**
         * 
         * @throws Exception
         */
        private String storeFile() throws Exception {
                String mediaDirPath = Utils.CONTENT_DB_PATH + "media" + File.separator + this.getEntityID();
                File mediaDir = new File(mediaDirPath);
                if(!mediaDir.exists()) {
                        mediaDir.mkdir();
                }
                
                String mediaFileName = mediaDirPath + "/" + this.getPicFileName();
                File mediaFile = new File(mediaFileName);
                mediaFile.createNewFile();

                File uploadedPicFile = this.getPic();

                InputStream in = new FileInputStream(uploadedPicFile);
                
                // appending output stream
                // @rajveer : replacing the existing file 
                OutputStream out = new FileOutputStream(mediaFile); 
                
                try {
                        IOUtils.copy(in, out);
                }
                finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                }
                
                return mediaFileName;
        }

        /**
         * @param id the id to set
         */
        public void setId(String id) {
//              StringTokenizer tokenizer = new StringTokenizer(id,"_");
//              log.info("id:" + id);
//              this.id = tokenizer.nextToken();
//              log.info("token 1:" + tokenizer.nextToken());
//              this.slideID = tokenizer.nextToken();
//              log.info("token 2:" + this.slideID);
                log.info("id:" + id);
                this.id = id;
        }

        /**
         * @return the id
         */
        public String getId() {
                return id;
        }
        
        
    /**
     * 
     * @param entity
     * @throws Exception
     */
        private void updateEntity(Entity entity) throws Exception {             
                log.info("#### EntityController.updateEntity ####");
                EntityContainer entContainer = Catalog.getInstance().getEntityContainer();
                
                ContentValidator validator = new ContentValidator();
                if(!validator.validate(entity)) {
                        CreationUtils.addToIncomplete(entity);
                        
                        // Delete from repository if incomplete
                        entContainer.deleteEntity(entity);
                }
                else {
                        CreationUtils.deleteFromIncomplete(entity);
                        
                        entContainer.updateEntity(entity);
                }
                
                CreationUtils.storeEntity(entity);
                
                this.updateRepository();
        }

        /**
         * 
         * @throws Exception
         */
        private void updateRepository() throws Exception {      
                EntityContainer entContainer = Catalog.getInstance().getEntityContainer();
                
                Map<Long, Entity> entities = entContainer.getEntities();
                log.info("entities.size():" + entities.size());
                
                Map<Long, List<Entity>> entitiesByCategory = 
                        entContainer.getEntitiesbyCategory();
                log.info("entitiesByCategory.size():" + entitiesByCategory.size());
                
                CreationUtils.rewriteRepository(entities, entitiesByCategory);
        }

}