/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, 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/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.sun.enterprise.deployment.util;

import com.sun.enterprise.deployment.ServiceReferenceDescriptor;
import com.sun.enterprise.deployment.WebService;
import com.sun.enterprise.deployment.deploy.shared.FileArchive;
import com.sun.enterprise.util.FileUtil;

import javax.xml.ws.WebServiceClient;
import javax.xml.namespace.QName;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;

/**
 *
 * @author Kenneth Saks
 */
public class ModuleContentLinker extends DefaultDOLVisitor {

    // For standalone modules, this is either a directory or a jar file.
    // For .ears, this is the directory used by the j2ee classloader.
    protected FileArchive rootLocation_;
    
    // records whether URL assignments should be calculated even if the URLs
    // already have values. 
    private boolean forceWSDLURLs;

    public ModuleContentLinker(FileArchive rootLocation, boolean forceWSDLURLs) {
        rootLocation_ = rootLocation;
        this.forceWSDLURLs = forceWSDLURLs;
    }
    
    public ModuleContentLinker(FileArchive rootLocation) {
        this(rootLocation, false);
    }
    
    protected ModuleContentLinker() {
    }

    private File getModuleLocation(ModuleDescriptor module) throws IOException {
        File moduleLocation = new File(rootLocation_.getArchiveUri());
        if( !module.isStandalone() ) {
            // If this is an ear, get module jar by adding the module path
            // to the root directory.
            String archiveUri = module.getArchiveUri();
            moduleLocation = new File(rootLocation_.getEmbeddedArchive(archiveUri).getArchiveUri());
        }
        return moduleLocation;
    }

    private URL internalGetUrl(ModuleDescriptor module, String uri) 
        throws Exception {
        File moduleLocation = getModuleLocation(module);
        URL url = FileUtil.getEntryAsUrl(moduleLocation, uri);
        return url;
    }

    public void accept(ServiceReferenceDescriptor serviceRef) {
        try {
            ModuleDescriptor moduleDesc = 
                serviceRef.getBundleDescriptor().getModuleDescriptor();

            if( serviceRef.hasWsdlFile() ) {
                
                String wsdlFileUri = serviceRef.getWsdlFileUri();
                File tmpFile = new File(wsdlFileUri);
                if(tmpFile.isAbsolute()) {
                    // This takes care of the case when we set wsdlFileUri from generated @WebClient
                    // and the uri is an absolute path
                    serviceRef.setWsdlFileUrl(tmpFile.toURI().toURL());
                } else {
                    // If the given WSDL is an http URL, create a URL directly from this
                    if(wsdlFileUri.startsWith("http")) {
                        serviceRef.setWsdlFileUrl(new URL(wsdlFileUri));
                    } else {
                        // Given WSDL location is a relative path - append this to the module dir
                        File wsdlFile = new File(getModuleLocation(moduleDesc), wsdlFileUri);                
                        URL wsdlFileUrl = internalGetUrl(moduleDesc, wsdlFileUri);
                        serviceRef.setWsdlFileUrl(wsdlFile.toURI().toURL());
                    }
                }
            } else {
            //Incase wsdl file is missing we can obtain it from the @WebServiceClient annotation
                  ClassLoader classloader = Thread.currentThread().getContextClassLoader();
                  Class serviceInterfaceClass = classloader.loadClass(serviceRef.getServiceInterface());
                  WebServiceClient wsc = (WebServiceClient)serviceInterfaceClass.getAnnotation(javax.xml.ws.WebServiceClient.class);
                  if (wsc != null) {
                      serviceRef.setWsdlFileUri(wsc.wsdlLocation());
                      //we set the service QName too from the @WebServiceClient annotation
                      serviceRef.setServiceName(new QName(wsc.targetNamespace(),wsc.name()) );
                  }

            }
            if( serviceRef.hasMappingFile() ) {
                String mappingFileUri = serviceRef.getMappingFileUri();
                File mappingFile = new File(getModuleLocation(moduleDesc), mappingFileUri);
                serviceRef.setMappingFile(mappingFile);

            } 
        } catch (java.net.MalformedURLException mex) {
            DOLUtils.getDefaultLogger().log
                (Level.SEVERE, "enterprise.deployment.backend.invalidWsdlURL",
                new Object[] {serviceRef.getWsdlFileUri()});            
        } catch(Exception e) {
            DOLUtils.getDefaultLogger().log
                (Level.SEVERE, "enterprise.deployment.backend.invalidDescriptorMappingFailure",
                new Object[] {serviceRef.getName() , rootLocation_});
        }
    }

    public void accept(WebService webService) {
        try {
            ModuleDescriptor moduleDesc = 
                webService.getBundleDescriptor().getModuleDescriptor();
            // If the web service has a WSDL file, assign its URL if it is not
            // already assigned or if URLs are forced to be assigned.  
            if( webService.hasWsdlFile() && (webService.getWsdlFileUrl()==null || forceWSDLURLs) ) {
                String wsdlFileUri = webService.getWsdlFileUri();
                URL wsdlFileURL=null;
                try {
                    URL url = new URL(wsdlFileUri);
                    if (url.getProtocol()!=null && !url.getProtocol().equalsIgnoreCase("file")) {
                        wsdlFileURL=url;
                    } 
                } catch(java.net.MalformedURLException e) {
                    // ignore, it could just be a relate URI
                }
                if (wsdlFileURL==null) {
                    File wsdlFile = new File(getModuleLocation(moduleDesc), wsdlFileUri);                        
                    wsdlFileURL = wsdlFile.toURI().toURL();
                }
                webService.setWsdlFileUrl(wsdlFileURL);
            }
            if( webService.hasMappingFile() ) {
                String mappingFileUri = webService.getMappingFileUri();
                File mappingFile = new File(getModuleLocation(moduleDesc), mappingFileUri);
                webService.setMappingFile(mappingFile);
            } 
        } catch(Exception e) {
            DOLUtils.getDefaultLogger().log
                (Level.SEVERE, "enterprise.deployment.backend.invalidDescriptorMappingFailure",
                new Object[] {webService.getName() , rootLocation_});
        } 
    }

}
