Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2006-2013 Oracle and/or its affiliates. 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_1_1.html
  * or packager/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 packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [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 org.glassfish.webservices;
 
 
 import  org.jvnet.hk2.annotations.Service;
 import  javax.inject.Inject;
 
 import java.io.*;
 import java.net.*;
 import java.util.*;
Webservices module deployer. This is loaded from WebservicesContainer

Author(s):
Bhakti Mehta
Rama Pulavarthi
 
 @Service
     public static final WebServiceDeploymentNotifier deploymentNotifier =
             new WebServiceDeploymentNotifierImpl();
        return ;
    }
    private static final Logger logger = LogUtils.getLogger();
    private ResourceBundle rb = .getResourceBundle();
    @Inject
    private RequestDispatcher dispatcher;
    @Inject
    private ArchiveFactory archiveFactory;

    
Constructor
    public WebServicesDeployer() {
    }
    protected void cleanArtifacts(DeploymentContext deploymentContextthrows DeploymentException {
    }

   

    
Prepares the application bits for running in the application server. For certain cases, this is exploding the jar file to a format the ContractProvider instance is expecting, generating non portable artifacts and other application specific tasks. Failure to prepare should throw an exception which will cause the overall deployment to fail.

Parameters:
dc deployment context
Returns:
true if the prepare phase was successful
    @Override
    public boolean prepare(DeploymentContext dc) {
        try {
            Application app = dc.getModuleMetaData(Application.class);
            if (app==null) {
                // hopefully the DOL gave a good message of the failure...
                .log(..);
                return false;
            }
            BundleDescriptor bundle = DOLUtils.getCurrentBundleForContext(dc);
            String moduleCP = getModuleClassPath(dc);
            final List<URLmoduleCPUrls = ASClassLoaderUtil.getURLsFromClasspath(moduleCP.null);
            final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
            URLClassLoader newCl = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
                @Override
                public URLClassLoader run() {
                    return new URLClassLoader(ASClassLoaderUtil.convertURLListToArray(moduleCPUrls), oldCl);
                }
            });
            Thread.currentThread().setContextClassLoader(newCl);
            WebServicesDescriptor wsDesc = bundle.getWebServices();
            for (WebService ws : wsDesc.getWebServices()) {
                if ((new WsUtil()).isJAXWSbasedService(ws)){
                    setupJaxWSServiceForDeployment(dcws);
                } else {
                    JAXRPCCodeGenFacade facade.getService(JAXRPCCodeGenFacade.class);
                    if (facade != null) {
                        facade.run(dcmoduleCPfalse);
                    }  else {
                        throw new DeploymentException(.getString(.)) ;
                    }
                }
            }
            doWebServicesDeployment(app,dc);
            Thread.currentThread().setContextClassLoader(oldCl);
            WebServicesContainer container = .getService(WebServicesContainer.class);
            WebServicesDeploymentMBean bean = container.getDeploymentBean();
            WebServiceDeploymentNotifier notifier = getDeploymentNotifier();
            bean.deploy(wsDesc,notifier);
            return true;
        } catch (Exception ex) {
            RuntimeException re = new RuntimeException(ex.getMessage());
            re.initCause(ex);
            throw re;
        }
    }
        BundleDescriptor bundle = dc.getModuleMetaData(BundleDescriptor.class);
        // for modules this is domains/<domain-name>/j2ee-modules/<module-name>
        // for apps this is domains/<domain-name>/j2ee-apps/<app-name>/<foo_war> (in case of embedded wars)
        //  or domains/<domain-name>/j2ee-apps/<app-name>/<foo_jar> (in case of embedded jars)
        File moduleDir = dc.getSourceDir();
        //For modules this is domains/<domain-name>/generated/xml
        //Check with Hong about j2ee-modules
        File wsdlDir = dc.getScratchDir("xml");
        mkDirs(wsdlDir);
        //For modules this is domains/<domain-name>/generated/xml
        //Check with Hong about j2ee-modules
        File stubsDir = dc.getScratchDir("ejb");
        mkDirs(stubsDir);
        if (!DOLUtils.warType().equals(bundle.getModuleType()) &&
                !DOLUtils.ejbType().equals(bundle.getModuleType())) {
            // unknown module type with @WebService, just ignore...
            return;
        }
        wsdlDir = new File(wsdlDirbundle.getWsdlDir().replaceAll("/""\\"+.));
        // Check if catalog file is present, if so get mapped WSDLs
        String wsdlFileUri;
        File wsdlFile;
        try {
            checkCatalog(bundlewsmoduleDir);
        } catch (DeploymentException e) {
        }
        if (ws.hasWsdlFile()) {
            // If wsdl file is an http URL, download that WSDL and all embedded relative wsdls, schemas
            if (ws.getWsdlFileUri().startsWith("http")) {
                try {
                    wsdlFileUri = downloadWsdlsAndSchemasnew URL(ws.getWsdlFileUri()), wsdlDir);
                } catch(Exception e) {
                    throw new DeploymentException(e.toString(), e);
                }
                wsdlFile = new File(wsdlDirwsdlFileUri);
            } else {
                wsdlFileUri = ws.getWsdlFileUri();
                File wsdlFileAbs = new File(wsdlFileUri);
                wsdlFile = wsdlFileAbs.isAbsolute()? wsdlFileAbs : new File(moduleDirwsdlFileUri);
            }
            if (!wsdlFile.exists()) {
                String errorMessage = format(.getResourceBundle().getString(.),
                        ws.getWsdlFileUri(), bundle.getModuleDescriptor().getArchiveUri());
                .log(.errorMessage);
                throw new DeploymentException(errorMessage);
            }
        }
    }

    
Loads the meta date associated with the application.

Parameters:
type type of metadata that this deployer has declared providing.
    @Override
    public Object loadMetaData(Class typeDeploymentContext dc) {
         //Moved the doWebServicesDeployment back to prepare after discussing with
         //Jerome
         //see this bug  https://glassfish.dev.java.net/issues/show_bug.cgi?id=8080
         return true;
    }

    
Returns the meta data assocated with this Deployer

Returns:
the meta data for this Deployer
    @Override
    public MetaData getMetaData() {
        return new MetaData(falsenullnew Class[] {Application.class});
    }

    
This method downloads the main wsdl/schema and its imports in to the directory specified and returns the name of downloaded root document.

Parameters:
httpUrl
wsdlDir
Returns:
Returns the name of the root file downloaded with the invocation.
Throws:
Exception
    private String downloadWsdlsAndSchemasURL httpUrlFile wsdlDirthrows Exception {
        // First make required directories and download this wsdl file
        mkDirs(wsdlDir);
        String fileName = httpUrl.toString().substring(httpUrl.toString().lastIndexOf("/")+1);
        File toFile = new File(wsdlDir.getAbsolutePath()+.+fileName);
        downloadFile(httpUrltoFile);
        // Get a list of wsdl and schema relative imports in this wsdl
        HashSet<ImportwsdlRelativeImports = new HashSet<Import>();
        HashSet<ImportschemaRelativeImports = new HashSet<Import>();
        HashSet<ImportwsdlIncludes = new HashSet<Import>();
        HashSet<ImportschemaIncludes = new HashSet<Import>();
        parseRelativeImports(httpUrlwsdlRelativeImportswsdlIncludes,
                schemaRelativeImportsschemaIncludes);
        wsdlRelativeImports.addAll(wsdlIncludes);
        schemaRelativeImports.addAll(schemaIncludes);
        // Download all schema relative imports
        String urlWithoutFileName = httpUrl.toString().substring(0, httpUrl.toString().lastIndexOf("/"));
        for(Import next : schemaRelativeImports) {
            String location = next.getLocation();
            location = location.replaceAll("/""\\"+.);
            if(location.lastIndexOf(.) != -1) {
                File newDir = new File(wsdlDir.getAbsolutePath()+.+
                location.substring(0, location.lastIndexOf(.)));
                mkDirs(newDir);
            }
            downloadFile(new URL(urlWithoutFileName+"/"+next.getLocation()),
                        new File(wsdlDir.getAbsolutePath()+.+location));
        }
        // Download all wsdl relative imports
        for(Import next : wsdlRelativeImports) {
            String newWsdlLocation = next.getLocation();
            newWsdlLocation = newWsdlLocation.replaceAll("/",  "\\"+.);
            File newWsdlDir;
            if(newWsdlLocation.lastIndexOf(.) != -1) {
                newWsdlDir = new File(wsdlDir.getAbsolutePath() + . +
                newWsdlLocation.substring(0, newWsdlLocation.lastIndexOf(.)));
            } else {
                newWsdlDir = wsdlDir;
            }
            downloadWsdlsAndSchemasnew URL(urlWithoutFileName+"/"+next.getLocation()), newWsdlDir);
        }
        return fileName;
    }
    // If catalog file is present, get the mapped WSDL for given WSDL and replace the value in
    // the given WebService object
    private void checkCatalog(BundleDescriptor bundleWebService wsFile moduleDir)
                            throws DeploymentException {
        // If no catalog file is present, return
        File catalogFile = new File(moduleDir,
                bundle.getDeploymentDescriptorDir() +
                . + "jax-ws-catalog.xml");
        if(!catalogFile.exists()) {
            return;
        }
        resolveCatalog(catalogFilews.getWsdlFileUri(), ws);
    }
    public URL resolveCatalog(File catalogFileString wsdlFileWebService wsthrows DeploymentException {
        try {
           URL retVal = null;
            // Get an entity resolver
            org.xml.sax.EntityResolver resolver =
                    XmlUtil.createEntityResolver(catalogFile.toURL());
            org.xml.sax.InputSource source = resolver.resolveEntity(nullwsdlFile);
            if(source != null) {
                String mappedEntry = source.getSystemId();
                // For entries with relative paths, Entity resolver always
                // return file://<absolute path
                if(mappedEntry.startsWith("file:")) {
                    File f = new File(mappedEntry.substring(mappedEntry.indexOf(":")+1));
                    if(!f.exists()) {
                        throw new DeploymentException(format(.getString(.), mappedEntry));
                    }
                    retVal = f.toURI().toURL();
                    if(ws != null) {
                        ws.setWsdlFileUri(f.getAbsolutePath());
                        ws.setWsdlFileUrl(retVal);
                    }
                } else if(mappedEntry.startsWith("http")) {
                    retVal = new URL(mappedEntry);
                    if(ws != null) {
                        ws.setWsdlFileUrl(retVal);
                    }
                }
            }
            return retVal;
        } catch (Throwable t) {
            throw new DeploymentException(format(.getString(.),
                     catalogFile.getAbsolutePath(), t.getMessage()));
        }
      
    }

    
Copies file from source to destination

Parameters:
src
dest
Throws:
IOException
    private static void copyFile(File srcFile destthrows IOException {
        if (!dest.exists()) {
            mkDirs(dest.getParentFile());
            mkFile(dest);
        }
        FileChannel srcChannel = null;
        FileChannel destChannel = null;
        try {
            srcChannel = new FileInputStream(src).getChannel();
            destChannel = new FileOutputStream(dest).getChannel();
            destChannel.transferFrom(srcChannel, 0, srcChannel.size());
        }
        finally {
            if (srcChannel != null) {
                srcChannel.close();
            }
            if (destChannel != null) {
                destChannel.close();
            }
        }
    }
    public void downloadFile(URL httpUrlFile toFilethrows Exception {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            if(!toFile.createNewFile()) {
                throw new Exception(format(.getString(.), toFile.getAbsolutePath()));
            }
            is = httpUrl.openStream();
            os = new FileOutputStream(toFiletrue);
            int readCount;
            byte[] buffer = new byte[10240]; // Read 10KB at a time
            while(true) {
                readCount = is.read(buffer, 0, 10240);
                if(readCount != -1) {
                    os.write(buffer, 0, readCount);
                } else {
                    break;
                }
            }
            os.flush();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }
    }

    
Collect all relative imports from a web service's main wsdl document.

Parameters:
wsdlFileUrl
wsdlRelativeImports output param in which wsdl relative imports will be added
schemaRelativeImports output param in which schema relative imports will be added
schemaIncludes output param in which schema includes will be added
    private void parseRelativeImports(URL wsdlFileUrl,
                                      Collection wsdlRelativeImports,
                                      Collection wsdlIncludes,
                                      Collection schemaRelativeImports,
                                       Collection schemaIncludes)
        throws Exception {
        // We will use our little parser rather than using JAXRPC's heavy weight WSDL parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        //Validation is not needed as we want to be too strict in processing wsdls that are generated by buggy tools.
        factory.setExpandEntityReferences(false);
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl"true);
        InputStream is = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            is = wsdlFileUrl.openStream();
            Document document = builder.parse(is);
            procesSchemaImports(documentschemaRelativeImports);
            procesWsdlImports(documentwsdlRelativeImports);
            procesSchemaIncludes(documentschemaIncludes);
            procesWsdlIncludes(documentwsdlIncludes);
        } catch (SAXParseException spe) {
            // Error generated by the parser
            .log(..,
                    new Object[] {spe.getLineNumber() ,spe.getSystemId()});
            // Use the contained exception, if any
            Exception x = spe;
            if (spe.getException() != null) {
                x = spe.getException();
            }
            .log(..x);
        } catch (Exception sxe) {
            .log(..sxe.getMessage());
        } finally {
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException io) {
                if (.isLoggable(.)) {
                    .log(..io.getMessage());
                }
            }
        }
    }
    private void procesSchemaImports(Document documentCollection schemaImportCollectionthrows SAXException,
            ParserConfigurationExceptionIOException {
        NodeList schemaImports =
                document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema""import");
        addImportsAndIncludes(schemaImportsschemaImportCollection"namespace""schemaLocation");
    }
    private void procesWsdlImports(Document documentCollection wsdlImportCollectionthrows SAXException,
            ParserConfigurationExceptionIOException {
        NodeList wsdlImports =
                document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/""import");
        addImportsAndIncludes(wsdlImportswsdlImportCollection"namespace""location");
    }
    private void procesSchemaIncludes(Document documentCollection schemaIncludeCollectionthrows SAXException,
            ParserConfigurationExceptionIOException {
        NodeList schemaIncludes =
                document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema""include");
        addImportsAndIncludes(schemaIncludesschemaIncludeCollectionnull"schemaLocation");
    }
    private void procesWsdlIncludes(Document documentCollection wsdlIncludesCollectionthrows SAXException,
            ParserConfigurationExceptionIOException {
        NodeList wsdlIncludes =
                document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/""include");
        addImportsAndIncludes(wsdlIncludeswsdlIncludesCollectionnull"location");
    }
    private void addImportsAndIncludes(NodeList listCollection result,
                        String namespaceString locationthrows SAXException,
                        ParserConfigurationExceptionIOException {
        for(int i=0; i<list.getLength(); i++) {
            String givenLocation = null;
            Node element = list.item(i);
            NamedNodeMap attrs = element.getAttributes();
            Node nattrs.getNamedItem(location);
            if(n != null) {
                givenLocation = n.getNodeValue();
            }
            if(givenLocation == null || givenLocation.startsWith("http")) {
                continue;
            }
            Import imp = new Import();
            imp.setLocation(givenLocation);
            if(namespace != null) {
                n = attrs.getNamedItem(namespace);
                if(n != null) {
                    imp.setNamespace(n.getNodeValue());
                }
            }
            result.add(imp);
        }
    }

    
Processes all the web services in the module and prepares for deployment. The tasks include composing the endpoint publish url and generating WSDL in to the application repository directory. In JAX-WS, WSDL files are generated dynamically, hence skips the wsdl generation step unless explicitly requested for WSDL file publishing via DD.

Parameters:
app
dc
Throws:
Exception
    private void doWebServicesDeployment(Application appDeploymentContext dc)
        throws Exception{
        Collection<WebServicewebServices = new HashSet<WebService>();
        // when there are multiple sub modules in ear, we only want to handle the ones local to this deployment context
        //First get the web services associated with module bundle descriptor.
        if (wsDesc != null && wsDesc.getWebServices().size() > 0) {
            if (.isLoggable(.)) {
                .log(..,
                        new Object[] {wsDesc.getWebServices().size(), getWebServiceDescriptors(app).size()});
            }
            webServices.addAll(wsDesc.getWebServices());
        }
        //Now get the web services associated with extension descriptors,ex: EJB WS in war.
        WebBundleDescriptor webBundleDesc = dc.getModuleMetaData(WebBundleDescriptor.class);
        if (webBundleDesc != null) {
            Collection<EjbBundleDescriptorejbBundleDescriptors = webBundleDesc.getExtensionsDescriptors(EjbBundleDescriptor.class);
            for (EjbBundleDescriptor ejbBundleDescriptor : ejbBundleDescriptors) {
                Collection wsInExtnDesc = ejbBundleDescriptor.getWebServices().getWebServices();
                webServices.addAll(wsInExtnDesc);
                if (.isLoggable(.)) {
                    .log(..wsInExtnDesc);
                }
            }
        }
        // swap the deployment descriptors context-root with the one
        // provided in the deployment request.
        //do not do for ejb in war case
        if (webBundleDesc!= null && webBundleDesc.getExtensionsDescriptors(EjbBundleDescriptor.class).size()==0) {
            if (dc.getAppProps().get("context-root") != null &&
                    app.isVirtual() ) {
                String contextRoot = ((String)dc.getAppProps().get("context-root"));
                webBundleDesc.setContextRoot(contextRoot);
            }
        }
        // Generate final wsdls for all web services and store them in
        // the application repository directory.
        for(WebService next : webServices) {
            WsUtil wsUtil = new WsUtil();
            // For JAXWS services, we rely on JAXWS RI to do WSL gen and publishing
            // For JAXRPC we do it here in 109
            //however it is needed for file publishing for jaxws
            if(wsUtil.isJAXWSbasedService(next) && (!next.hasFilePublishing())) {
                for(WebServiceEndpoint wsep : next.getEndpoints()) {
                    wsep.composeFinalWsdlUrl(wsUtil.getWebServerInfoForDAS().getWebServerRootURL(wsep.isSecure()));
                }
            } else {
                // Even if deployer specified a wsdl file
                // publish location, server can't assume it can access that
                // file system.  Plus, it's cleaner to depend on a file stored
                // within the application repository rather than one directly
                // exposed to the deployer. Name of final wsdl is derived based
                // on the location of its associated module.  This prevents us
                // from having write the module to disk in order to store the
                // modified runtime info.
                URL url = next.getWsdlFileUrl();
                if (url == null ) {
                    File f = new File(dc.getSourceDir(),next.getWsdlFileUri()) ;
                    url = f.toURL();
                }
                // Create the generated WSDL in the generated directory; for that create the directories first
                File genXmlDir =  dc.getScratchDir("xml");
                String wsdlFileDir = next.getWsdlFileUri().substring(0, next.getWsdlFileUri().lastIndexOf('/'));
                mkDirs(new File(genXmlDirwsdlFileDir));
                File genWsdlFile = new File(genXmlDirnext.getWsdlFileUri());
                wsUtil.generateFinalWsdl(urlnextwsUtil.getWebServerInfoForDAS(), genWsdlFile);
            }
        }
        //Swap the servlet class name with a real servlet processing the SOAP requests.
        if (webBundleDesc != null) {
            doWebServiceDeployment(webBundleDesc);
        }
    }

    
Prepares the servlet based web services specified in web.xml for deployment. Swap the application written servlet implementation class for one provided by the container. The original class is stored as runtime information since it will be used as the servant at dispatch time.
    private void doWebServiceDeployment(WebBundleDescriptor webBunDesc)
        throws DeploymentExceptionMalformedURLException {

        
Combining code from com.sun.enterprise.deployment.backend.WebServiceDeployer in v2
        Collection<WebServiceEndpointendpoints =
            webBunDesc.getWebServices().getEndpoints();
        ClassLoader cl = webBunDesc.getClassLoader();
        WsUtil wsutil = new WsUtil();
        for(WebServiceEndpoint nextEndpoint : endpoints) {
            WebComponentDescriptor webComp = nextEndpoint.getWebComponentImpl();
            if( !nextEndpoint.hasServletImplClass() ) {
                throw new DeploymentExceptionformat(.getString(
                        .),
                        nextEndpoint.getEndpointName()));
            }
            if (nextEndpoint.hasEndpointAddressUri()) {
                webComp.getUrlPatternsSet().clear();
                webComp.addUrlPattern(nextEndpoint.getEndpointAddressUri());
            }
            if( !nextEndpoint.getWebService().hasFilePublishing() ) {
                String publishingUri = nextEndpoint.getPublishingUri();
                String publishingUrlPattern =
                        (publishingUri.charAt(0) == '/') ?publishingUri : "/" + publishingUri + "/*";
                webComp.addUrlPattern(publishingUrlPattern);
            }
            String servletImplClass = nextEndpoint.getServletImplClass();
            try {
                Class servletImplClazz  = cl.loadClass(servletImplClass);
                String containerServlet;
                if(wsutil.isJAXWSbasedService(nextEndpoint.getWebService())) {
                    containerServlet = "org.glassfish.webservices.JAXWSServlet";
                    addWSServletContextListener(webBunDesc);
                } else {
                    containerServlet =
                    SingleThreadModel.class.isAssignableFrom(servletImplClazz) ?
                    "org.glassfish.webservices.SingleThreadJAXRPCServlet" :
                        "org.glassfish.webservices.JAXRPCServlet";
                }
                webComp.setWebComponentImplementation(containerServlet);
            } catch(ClassNotFoundException cex) {
                throw new DeploymentExceptionformat(.getString(
                        .),
                        nextEndpoint.getEndpointName()));
            }

            
Now trying to figure the address from com.sun.enterprise.webservice.WsUtil.java
            // Get a URL for the root of the webserver, where the host portion
            // is a canonical host name.  Since this will be used to compose the
            // endpoint address that is written into WSDL, it's better to use
            // hostname as opposed to IP address.
            // The protocol and port will be based on whether the endpoint
            // has a transport guarantee of INTEGRAL or CONFIDENTIAL.
            // If yes, https will be used.  Otherwise, http will be used.
            WebServerInfo wsi = new WsUtil().getWebServerInfoForDAS();
            URL rootURL = wsi.getWebServerRootURL(nextEndpoint.isSecure());
            String contextRoot = webBunDesc.getContextRoot();
            URL actualAddress = nextEndpoint.composeEndpointAddress(rootURLcontextRoot);
            if (wsi.getHttpVS() != null && wsi.getHttpVS().getPort()!=0) {
               .log(..,
                       new Object[] {nextEndpoint.getEndpointName(), actualAddress});
            }
        }
    }
    private void addWSServletContextListener(WebBundleDescriptor webBunDesc) {
        for(AppListenerDescriptor appListnerwebBunDesc.getAppListenerDescriptors()) {
            if(appListner.getListener().equals(WSServletContextListener.class.getName())) {
                //already registered
                return;
            }
        }
    }
    
    private String format(String keyString ... values){
        return MessageFormat.format(key, (Object [])values);
    }
    public static void moveFile(String sourceFileString destFile)
    throws IOException {
        FileUtils.copy(sourceFiledestFile);
        FileUtils.deleteFile(new File(sourceFile));
    }
    @Override
    public void unload(WebServicesApplication containerDeploymentContext context) {
        final WebServiceDeploymentNotifier notifier = getDeploymentNotifier();
        deletePublishedFiles(container.getPublishedFiles());
        Application app = container.getApplication();
        if ( app == null ) {
            // load uses context.getModuleMetaData(Application.class) to get the Application.  If there's a deployment
            // failure then "container" may not have initialized the application and container.getApplication() returns
            // null and we get NPE.  So use context.getModuleMetaData(Application.class) always.
            app = context.getModuleMetaData(Application.class);
        }
        if ( app != null ) {
            for(WebService svc : getWebServiceDescriptors(app)) {
                for(WebServiceEndpoint endpoint : svc.getEndpoints()) {
                    if (notifier != null) {
                        notifier.notifyUndeployed(endpoint);
                    }
                }
            }
        }
    }
    @Override
    public void clean(DeploymentContext dc) {
        super.clean(dc);
        WebServicesContainer container = .getService(WebServicesContainer.class);
        WebServicesDeploymentMBean bean = container.getDeploymentBean();
        if (params != null)  {
            bean.undeploy(params.name);
        }
    }
    @Override
    public WebServicesApplication load(WebServicesContainer containerDeploymentContext context) {
        Set<StringpublishedFiles = null;
        Application app = context.getModuleMetaData(Application.class);
        try {
            publishedFiles = populateWsdlFilesForPublish(contextgetWebServiceDescriptors(app));
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
        return new WebServicesApplication(context,  publishedFiles);
    }

    
Populate the wsdl files entries to download (if any) (Only for webservices which use file publishing). TODO File publishing currently works only for wsdls packaged in the application for jax-ws. Need to publish the dynamically generated wsdls as well. Lazy creation of WSEndpoint objects prohibits it now.
            DeploymentContext dcSet<WebServicewebservicesthrows IOException {
        Set<StringpublishedFiles = new HashSet<String>();
        for (WebService webService : webservices) {
            if (!webService.hasFilePublishing()) {
                continue;
            }
            copyExtraFilesToGeneratedFolder(dc);
            BundleDescriptor bundle = webService.getBundleDescriptor();
            ArchiveType moduleType = bundle.getModuleType();
            //only EAR, WAR and EJB archives could contain wsdl files for publish
            if (moduleType==null || !(moduleType.equals(DOLUtils.earType()) ||
                    moduleType.equals(DOLUtils.warType()) ||
                    moduleType.equals(DOLUtils.ejbType()))) {
                return publishedFiles;
            }
            File sourceDir = dc.getScratchDir("xml");
            File parent;
            try {
                URI clientPublishURI = webService.getClientPublishUrl().toURI();
                if(!clientPublishURI.isOpaque()) {
                    parent = new File(clientPublishURI);
                } else {
                    parent =  new File(webService.getClientPublishUrl().getPath());
                }
            } catch (URISyntaxException e) {
                .log(..e);
                parent = new File(webService.getClientPublishUrl().getPath());
            }
            // Collect the names of all entries in or below the
            // dedicated wsdl directory.
            FileArchive archive = new FileArchive();
            archive.open(sourceDir.toURI());
            Enumeration entries = archive.entries(bundle.getWsdlDir());
            while (entries.hasMoreElements()) {
                String name = (Stringentries.nextElement();
                String wsdlName = stripWsdlDir(namebundle);
                File clientwsdl = new File(parentwsdlName);
                File fulluriFile = new File(sourceDirname);
                if (!fulluriFile.isDirectory()) {
                    publishFile(fulluriFileclientwsdl);
                    publishedFiles.add(clientwsdl.getAbsolutePath());
                }
            }
        }
        return publishedFiles;
    }
    private void publishFile(File fileFile publishLocationthrows IOException {
        copyFile(filepublishLocation);
    }
    private void deletePublishedFiles(Set<StringpublishedFiles) {
        if (publishedFiles != null) {
            for (String pathpublishedFiles) {
                File f = new File(path);
                if (f.exists()) {
                    FileUtils.deleteFile(f);
                }
            }
        }
    }
    
This is to be used for file publishing only. In case of wsdlImports and wsdlIncludes we need to copy the nested wsdls from applications folder to the generated/xml folder
    private void copyExtraFilesToGeneratedFolderDeploymentContext contextthrows IOException{
        Archivist archivist = .getService(Archivist.class);
        ReadableArchive archive = .openArchive(
                context.getSourceDir());
        WritableArchive archive2 = .createArchive(
                context.getScratchDir("xml"));
        // copy the additional webservice elements etc
        archivist.copyExtraElements(archivearchive2);
 
    }

    
Return the entry name without "WEB-INF/wsdl" or "META-INF/wsdl".
    private String stripWsdlDir(String entryBundleDescriptor bundle) {
        String wsdlDir = bundle.getWsdlDir();
        return entry.substring(wsdlDir.length()+1);
    }

    
Return a set of all com.sun.enterprise.deployment.WebService descriptors in the application.
        Set<WebServicewebServiceDescriptors = new HashSet<WebService>();
        for (BundleDescriptor next : app.getBundleDescriptors()) {
            WebServicesDescriptor webServicesDesc =
                    next.getWebServices();
            webServiceDescriptors.addAll(webServicesDesc.getWebServices());
        }
        return webServiceDescriptors;
    }
    private static void mkDirs(File f) {
        if (!f.mkdirs() && .isLoggable(.)) {
            .log(..f);
        }
    }
    private static void mkFile(File fthrows IOException {
        if (!f.createNewFile() && .isLoggable(.)) {
            .log(..f);
        }
    }
New to GrepCode? Check out our FAQ X