Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.creation.controllers;

import in.shop2020.content.security.UserManager;
import in.shop2020.creation.util.ContentValidator;
import in.shop2020.metamodel.core.Bullet;
import in.shop2020.metamodel.core.Entity;
import in.shop2020.metamodel.core.EntityState;
import in.shop2020.metamodel.core.EntityStatus;
import in.shop2020.metamodel.core.EnumDataObject;
import in.shop2020.metamodel.core.Feature;
import in.shop2020.metamodel.core.FreeformContent;
import in.shop2020.metamodel.core.Media;
import in.shop2020.metamodel.core.Media.Type;
import in.shop2020.metamodel.core.Slide;
import in.shop2020.metamodel.definitions.Catalog;
import in.shop2020.metamodel.util.CreationUtils;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.util.Utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

@InterceptorRefs({
    @InterceptorRef("myDefault"),
    @InterceptorRef("login")
})

@Results({
    @Result(name="success", type="redirectAction", 
                params = {"actionName" , "entity"})
})
public class ItemUpdateController extends BaseController {
        
        private static final long serialVersionUID = 7180013499003793197L;
        
        private String id;
        
        private static Log log = LogFactory.getLog(ItemUpdateController.class);
        
        public String show(){
                if(this.reqparams.get("action") !=null){
                        long entityId = Long.parseLong(getId());
                        String action = this.reqparams.get("action")[0];
                        
                        if(action.equalsIgnoreCase("complete")){
                                if(!UserManager.getUserManager().canComplete(getUsername(), entityId)){
                                        addActionError("Can not complete because this entity is not assigned to you.");
                                        return "success";       
                                }
                                try {
                                        Entity entity = CreationUtils.getEntity(entityId);
                                        ContentValidator validator = new ContentValidator();
                                        if(!validator.validate(entity)){
                                                addActionError("Entity is not yet complete because some mandatory fields are not filled.");
                                                return "success";
                                        }
                                        EntityState state = CreationUtils.getEntityState(entityId);
                                        state.completeEntity(this.getUsername());
                                        CreationUtils.updateEntityState(state);
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                                addActionMessage("Entity completed successfully");
                                return "success";
                        }
                        
                        if(action.equalsIgnoreCase("assign")){
                                if(this.reqparams.get("username") !=null){
                                    if(!UserManager.getUserManager().canAssign(getUsername(), entityId)){
                                                addActionError("You do not have rights to assign an entity");
                                                return "success";       
                                        }
                                        String assignTo = this.reqparams.get("username")[0];
                                        System.out.println("User name is " + assignTo);
                                        try {
                                                EntityState state = CreationUtils.getEntityState(entityId);
                                                if(state.getStatus() == EntityStatus.READY){
                                                    Calendar cl = Calendar.getInstance();
                                                    int hourOfDay = cl.get(Calendar.HOUR_OF_DAY);
                                                    int minuteOfHour = cl.get(Calendar.MINUTE);
                                                    int totalMinutes = 60*hourOfDay + minuteOfHour;  
                                    if(totalMinutes > 14*60 + 45 && totalMinutes < 15*60 + 30){
                                        addActionError("Sorry.... This is not right time to assign this entity. Please visit after 3.30 PM.");
                                        return "success";   
                                    }
                                                    List<Long> inconsistentEntities = CreationUtils.getInconsistentEntities();
                                                    if(inconsistentEntities == null){
                                                        inconsistentEntities = new ArrayList<Long>();
                                                    }
                                                    inconsistentEntities.add(state.getID());
                                                    CreationUtils.storeInconsistentEntities(inconsistentEntities);
                                                }
                                                state.assignEntity(this.getUsername(), assignTo);
                                                CreationUtils.updateEntityState(state);
                                        } catch (Exception e) {
                                                e.printStackTrace();
                                        }
                                        addActionMessage("Entity assigned to " + assignTo + " successfully");
                                        return "success";
                                }
                        }
                        
                        if (action.equalsIgnoreCase("dup-entity")) {
                                if (!UserManager.getUserManager().canAssign(getUsername(),
                                                entityId)) {
                                        addActionError("You do not have rights to clone entites.");
                                        return "success";
                                }
                                String dupEntityId = this.reqparams.get("entity-old")[0];
                                log.info("Duplicate Entity is " + dupEntityId);
                                try {
                                        Entity newEntity = CreationUtils.getEntity(entityId);
                                        Entity dupEntity = CreationUtils.getEntity(Long
                                                        .parseLong(dupEntityId));
                                        
                                        List<Slide> slides = dupEntity.getSlides();
                                        List<Slide> newSlides = new ArrayList<Slide>();
                                        for (Slide slide : slides) {
                                                // Serializing and deserializing to clone the slide
                                                // serialize
                                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                                ObjectOutputStream out = new ObjectOutputStream(bos);
                                                out.writeObject(slide);

                                                // De-serialization
                                                ByteArrayInputStream bis = new ByteArrayInputStream(
                                                                bos.toByteArray());
                                                ObjectInputStream in = new ObjectInputStream(bis);
                                                Slide newSlide = (Slide) in.readObject();
                                                newSlides.add(newSlide);
                                        }
                                        //for all new slides update the mediatypes and create new mediastore for this entity
                                        List<Slide> allSlides = new ArrayList<Slide>();
                                        allSlides.addAll(newSlides);
                                        for(Slide sl: newSlides){
                                                if(sl.hasChildrenSlides()){
                                                        allSlides.addAll(sl.getChildrenSlides());
                                                        for(Slide sl1 : sl.getChildrenSlides()){
                                                                if(sl1.hasChildrenSlides()){
                                                                        allSlides.addAll(sl.getChildrenSlides());
                                                                }
                                                        }
                                                }
                                        }
                                        for(Slide sl : allSlides){
                                                FreeformContent ffc = sl.getFreeformContent();
                                                if(ffc==null){
                                                        continue;
                                                }
                                                Map<String, Media> mediaMap = ffc.getMedias();
                                                if(mediaMap==null){
                                                        continue;
                                                }
                                                for(Media media : mediaMap.values()){
                                                        if(media.getType().equals(Type.IMAGE) || media.getType().equals(Type.DOCUMENT)){
                                                                copyMedia(String.valueOf(entityId), dupEntityId, media);
                                                        }
                                                }
                                        }
                                        List<Long> slideSequence = dupEntity.getSlideSequence();
                                        List<Long> newSlideSequence = new ArrayList<Long>(slideSequence);
                                        newEntity.setSlides(newSlides);
                                        newEntity.setSlideSequence(newSlideSequence);
                                        CreationUtils.updateEntity(newEntity);
                                } catch (Exception e) {
                                        addActionError(dupEntityId + " is not a valid Entity.");
                                        e.printStackTrace();
                                        return "success";
                                }
                                addActionMessage("Entity " + entityId + " has been cloned successfully");
                                return "success";
                        }
                        

                        if(action.equalsIgnoreCase("ready")){
                                if(!UserManager.getUserManager().canMarkReady(getUsername(), entityId)){
                                        addActionError("You do not have rights to mark entity as ready");
                                        return "success";       
                                }
                                try {
                                    EntityState state = CreationUtils.getEntityState(entityId);
                                    
                                    //For all android phones in mobile category, we should enable data pack. 
                                    boolean isAndroid = false;
                                    if(state.getCategoryID() == 10006){
                                        Entity e = CreationUtils.getEntity(entityId);
                                        Slide slide = e.getSlide(130020);
                                        if(slide != null)  {
                                                List<Feature> fs = slide.getFeatures();
                                                if (fs!=null){
                                                        for (Feature f1 : fs){
                                                                if(f1.getFeatureDefinitionID()==120043l){
                                                                        List <Bullet> bullets = f1.getBullets();
                                                                        if(bullets != null) {
                                                                                for(Bullet b : bullets){
                                                                                        String bulletString = Catalog.getInstance().getDefinitionsContainer().getEnumValue(((EnumDataObject)b.getDataObject()).getEnumValueID()).getValue();
                                                                                        if (bulletString.contains("Android")){
                                                                                                isAndroid = true;
                                                                                                log.info("Is android marked true for " + entityId);
                                                                                                break;
                                                                                        }
                                                                                }
                                                                        }
                                                                }
                                                        }
                                                }
                                        }
                                    }
                                    
                                        CatalogClient csc = new CatalogClient();
                                        in.shop2020.model.v1.catalog.CatalogService.Client iclient = csc.getClient();
                                        iclient.markItemAsContentComplete(entityId, state.getCategoryID(), state.getBrand(), state.getModelName(), state.getModelNumber(), isAndroid);  
                                        
                    List<Long> inconsistentEntities = CreationUtils.getInconsistentEntities();
                    if(inconsistentEntities != null){
                        inconsistentEntities.remove(state.getID());
                        CreationUtils.storeInconsistentEntities(inconsistentEntities);
                    }
                                        
                                        state.readyEntity(getUsername());
                                        CreationUtils.updateEntityState(state);
                                        addActionMessage("Entity marked as ready successfully");
                                } catch (Exception e) {
                                        addActionError("Unable to mark entity as ready.");
                                        e.printStackTrace();
                                }
                                return "success";
                        }
                        
                        
                        if(action.equalsIgnoreCase("iteminfo")){
                                return "iteminfo";
                        }

                        
                }
                addActionError("There is some problem, please contact admin.");
                return "success";
        }

        
        public String getId(){
                return this.id;
        }
        
        public void setId(String id){
                this.id = id;
        }
        
        /**
         * 
         * @throws Exception
         */
        private void copyMedia(String newEntityId, String oldEntityId, Media media) throws Exception {
                String mediaDirPath = Utils.CONTENT_DB_PATH + "media" + File.separator + newEntityId;
                File mediaDir = new File(mediaDirPath);
                if(!mediaDir.exists()) {
                        mediaDir.mkdir();
                } 

                String mediaFilePath = mediaDirPath + File.separator + media.getFileName();
                String oldMediaFilePath = media.getLocation();

                File mediaFile = new File(mediaFilePath);
                log.info("Media File ---------" + mediaFile);
                mediaFile.createNewFile();

                File oldMediaFile = new File(oldMediaFilePath);

                InputStream in = new FileInputStream(oldMediaFile);
                
                // 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);
                }
                media.setLocation(mediaFilePath);
        }
        
}