/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

/*
 * AssociationPhase.java
 *
 * Created on May 20, 2003, 3:14 PM
 * @author  sandhyae
 * <BR> <I>$Source: /cvs/glassfish/appserv-core/src/java/com/sun/enterprise/deployment/phasing/AssociationPhase.java,v $
 *
 */

package com.sun.enterprise.deployment.phasing;

import com.sun.enterprise.deployment.backend.IASDeploymentException;
import com.sun.enterprise.deployment.backend.DeploymentRequest;
import com.sun.enterprise.deployment.backend.DeploymentEventInfo;
import com.sun.enterprise.deployment.backend.DeploymentEvent;
import com.sun.enterprise.deployment.backend.DeploymentEventType;
import com.sun.enterprise.deployment.backend.DeployableObjectType;
import com.sun.enterprise.deployment.backend.DeploymentLogger;
import com.sun.enterprise.deployment.backend.DeploymentStatus;
import com.sun.enterprise.config.serverbeans.ServerTags;
import com.sun.enterprise.config.ConfigException;
import com.sun.enterprise.config.serverbeans.ServerHelper;
import com.sun.enterprise.config.serverbeans.ApplicationHelper;

import com.sun.enterprise.util.i18n.StringManager;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class manages the association of an application or module with a target
 * @author  Sandhya E
 */
public class AssociationPhase extends DeploymentPhase {

    /** Deployment Logger object for this class */
    public static final Logger sLogger = DeploymentLogger.get();
    
    /** string manager */
    private static StringManager localStrings =
        StringManager.getManager( AssociationPhase.class );
   
    /** 
     * Creates a new instance of AssociationPhase 
     * @param deploymentCtx context object for the deployment
     */
    public AssociationPhase(DeploymentContext deploymentCtx) 
    {
        this.deploymentCtx = deploymentCtx;        
        this.name = ASSOCIATE;
    }

    /**
     * 
     */
    public void prePhase(DeploymentPhaseContext phaseCtx)
    {
        DeploymentRequest req = phaseCtx.getDeploymentRequest();
        DeploymentStatus status = phaseCtx.getDeploymentStatus();
        DeploymentTarget target = (DeploymentTarget)req.getTarget();

        try {
            // check context root uniqueness
            String virtualServers = (String)req.getOptionalAttributes().get(ServerTags.VIRTUAL_SERVERS);

            String contextRootInConflict = 
                ApplicationConfigHelper.checkContextRootUniqueness(
                    DeploymentServiceUtils.getConfigContext(), req.getName(), 
                    req.getTarget().getName(), virtualServers);
 
            if (contextRootInConflict != null) {
                throw new IASDeploymentException(localStrings.getString(
                    "duplicate_context_root",
                    contextRootInConflict, req.getName(), 
                    req.getTarget().getName()));
            }

            // only support directory deployment on DAS
            if (DeploymentServiceUtils.isDirectoryDeployed(req.getName(),
                req.getType())) {
                if (target != null && ServerHelper.isAServer(deploymentCtx.getConfigContext(), target.getTarget().getName()) && ServerHelper.isDAS(deploymentCtx.getConfigContext(), target.getTarget().getName())) {
                    return; 
                } else {
                    throw new IASDeploymentException(localStrings.getString(
                        "dir_deploy_not_support"));
                }
            }

            // FIXME: add the context root check here
        } catch(Throwable t){
            status.setStageStatus(DeploymentStatus.FAILURE);
            status.setStageException(t);
            status.setStageStatusMessage(t.getMessage());
        }
    }

    
    /** 
     * Phase specific execution logic will go in this method. Any phase implementing
     * this class will provide its implementation for this method.
     * @param req Deployment request object
     * @param phaseCtx the DeploymentPhaseContext object     
     */
    public void runPhase(DeploymentPhaseContext phaseCtx) 
    {
        try {
            DeploymentRequest req = phaseCtx.getDeploymentRequest();
            DeploymentTarget target = (DeploymentTarget)req.getTarget();
            if(target == null) {
                String msg = localStrings.getString("enterprise.deployment.phasing.association.targetnotspecified" );
                sLogger.log(Level.FINEST, msg);
                phaseCtx.getDeploymentStatus().setStageStatus(DeploymentStatus.WARNING);
                return;
            }
            prePhaseNotify(getPrePhaseEvent(req));
            String virtualServers = (String)req.getOptionalAttributes().get(ServerTags.VIRTUAL_SERVERS);
            target.addAppReference(req.getName(), req.isStartOnDeploy(), virtualServers);
            postPhaseNotify(getPostPhaseEvent(req));
            sendAssociateEvent(req);
            phaseCtx.getDeploymentStatus().setStageStatus(DeploymentStatus.SUCCESS);
        } catch(DeploymentTargetException dte) {
            phaseCtx.getDeploymentStatus().setStageStatus(DeploymentStatus.FAILURE);
            phaseCtx.getDeploymentStatus().setStageException(dte.getCause());
            if (dte.getCause()!=null) {
                phaseCtx.getDeploymentStatus().setStageStatusMessage(dte.getCause().getMessage());
            }
        }
    }
    

    /**
     * Event that will be broadcasted at the start of the phase
     * @param req Deployment request object
     * @return DeploymentEvent
     */
    private DeploymentEvent getPrePhaseEvent(DeploymentRequest req) 
    {
        return new DeploymentEvent(DeploymentEventType.PRE_ASSOCIATE, new DeploymentEventInfo(req));
    }
    
    /**
     * Event that will be broadcasted at the end of the phase
     * @return DeploymentEvent
     */
    private DeploymentEvent getPostPhaseEvent(DeploymentRequest req)
    {
        return new DeploymentEvent(DeploymentEventType.POST_ASSOCIATE, new DeploymentEventInfo(req));
    }


    private void sendAssociateEvent(DeploymentRequest req ) throws 
        DeploymentTargetException {
        try {
            DeploymentTarget target = (DeploymentTarget)req.getTarget();
            
            String moduleType;
            
            if(req.isApplication()) {
                moduleType = null;
            }
            else {
                moduleType = DeploymentServiceUtils.getModuleTypeString(req.getType());
            }
            
            int eventType = com.sun.enterprise.admin.event.BaseDeployEvent.APPLICATION_REFERENCED;
            String appName = req.getName();
            String targetName = target.getTarget().getName();
            
           boolean success = DeploymentServiceUtils.multicastEvent(
                            eventType, 
                            appName, 
                            moduleType, 
                            false, 
                            true, 
                            targetName);
           
           sLogger.log(Level.FINE, "sendAssociateEvent: success=" + success);
        } catch(Throwable t) {
            DeploymentTargetException dte = 
                new DeploymentTargetException(t.getMessage());
            dte.initCause(t);
            throw dte;
        }
    }
}
