|
Glassfish example source code file (WsUtil.java)
The Glassfish WsUtil.java source code
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 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 com.sun.enterprise.v3.admin.AdminAdapter;
import com.sun.enterprise.v3.admin.adapter.AdminConsoleAdapter;
import com.sun.grizzly.config.dom.NetworkListener;
import com.sun.xml.ws.api.server.SDDocumentSource;
import com.sun.xml.ws.api.WSBinding;
import com.sun.xml.ws.api.BindingID;
import com.sun.logging.LogDomains;
import com.sun.enterprise.deployment.*;
import com.sun.enterprise.deployment.util.ModuleDescriptor;
import com.sun.enterprise.deployment.util.WebServerInfo;
import com.sun.enterprise.deployment.util.VirtualServerInfo;
import com.sun.enterprise.deployment.web.UserDataConstraint;
import com.sun.enterprise.deployment.web.SecurityConstraint;
import com.sun.enterprise.container.common.spi.util.InjectionException;
import com.sun.enterprise.container.common.spi.util.InjectionManager;
import com.sun.enterprise.config.serverbeans.Config;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.xml.rpc.spi.model.*;
import javax.servlet.http.*;
import javax.xml.namespace.QName;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.Stub;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.rpc.soap.SOAPFaultException;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.HandlerRegistry;
import com.sun.xml.rpc.spi.JaxRpcObjectFactory;
import com.sun.xml.rpc.spi.model.Model;
import com.sun.xml.rpc.spi.model.ModelProperties;
import com.sun.xml.rpc.spi.model.Port;
import com.sun.xml.rpc.spi.model.Service;
import com.sun.xml.rpc.spi.runtime.ClientTransportFactory;
import com.sun.xml.rpc.spi.runtime.ClientTransportFactoryTypes;
import com.sun.xml.rpc.spi.runtime.SOAPConstants;
import com.sun.xml.rpc.spi.runtime.StreamingHandler;
import com.sun.xml.rpc.spi.runtime.StubBase;
import com.sun.xml.rpc.spi.runtime.Tie;
import com.sun.xml.rpc.spi.tools.WSDLUtil;
import java.util.*;
import java.net.*;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.xml.parsers.*;
import javax.xml.ws.soap.SOAPBinding;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.servlet.http.HttpServletResponse;
import org.glassfish.web.util.HtmlEntityEncoder;
import org.jvnet.hk2.component.Habitat;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import java.io.*;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.glassfish.api.admin.ServerEnvironment;
import org.glassfish.deployment.common.DeploymentException;
/**
* Web service related utilities.
*
* @author Kenneth Saks
*/
public class WsUtil {
// proprietary property for enabling logging of stub requests/responses
public static final String CLIENT_TRANSPORT_LOG_PROPERTY =
"com.sun.enterprise.webservice.client.transport.log";
// xslt processing parameters for final wsdl transformation
public static final String ENDPOINT_ADDRESS_PARAM_NAME =
"endpointAddressParam";
public final String WSDL_IMPORT_NAMESPACE_PARAM_NAME =
"wsdlImportNamespaceParam";
public static final String WSDL_IMPORT_LOCATION_PARAM_NAME =
"wsdlImportLocationParam";
public static final String WSDL_INCLUDE_LOCATION_PARAM_NAME =
"wsdlIncludeLocationParam";
public final String SCHEMA_IMPORT_NAMESPACE_PARAM_NAME =
"schemaImportNamespaceParam";
public static final String SCHEMA_IMPORT_LOCATION_PARAM_NAME =
"schemaImportLocationParam";
public static final String SCHEMA_INCLUDE_LOCATION_PARAM_NAME =
"schemaIncludeLocationParam";
private Config config = null;
private Habitat habitat = null;
private HtmlEntityEncoder htmlEntityEncoder = new HtmlEntityEncoder();
private List<NetworkListener> networkListeners = null;
public WsUtil() {
config = WebServiceContractImpl.getInstance().getConfig();
habitat = WebServiceContractImpl.getInstance().getHabitat();
}
// @@@ These are jaxrpc-implementation specific MessageContextProperties
// that should be added to jaxrpc spi
private static final String ONE_WAY_OPERATION =
"com.sun.xml.rpc.server.OneWayOperation";
private static final String CLIENT_BAD_REQUEST =
"com.sun.xml.rpc.server.http.ClientBadRequest";
private static final String SECURITY_POLICY_NAMESPACE_URI =
"http://schemas.xmlsoap.org/ws/2005/07/securitypolicy";
private static Logger logger = LogDomains.getLogger(WsUtil.class,LogDomains.WEBSERVICES_LOGGER);
private ResourceBundle rb = logger.getResourceBundle();
private JaxRpcObjectFactory rpcFactory;
/**
* Serve up the FINAL wsdl associated with this web service.
* @return true for success, false for failure
*/
public boolean handleGet(HttpServletRequest request,
HttpServletResponse response,
WebServiceEndpoint endpoint) throws IOException {
MimeHeaders headers = getHeaders(request);
if( hasSomeTextXmlContent(headers) ) {
String message = "Received HTTP GET containing text/xml " +
" content for endpoint " + endpoint.getEndpointName() +
" at " + endpoint.getEndpointAddressUri() +
" . HTTP POST should be used instead.";
writeInvalidMethodType(response, message);
logger.info(message);
return false;
}
URL wsdlUrl = null;
String requestUriRaw = request.getRequestURI();
String requestUri = (requestUriRaw.charAt(0) == '/') ?
requestUriRaw.substring(1) : requestUriRaw;
String queryString = request.getQueryString();
WebService webService = endpoint.getWebService();
if( queryString == null ) {
// Get portion of request uri representing location within a module
String wsdlPath = endpoint.getWsdlContentPath(requestUri);
if( wsdlPath != null) {
ModuleDescriptor module =
webService.getBundleDescriptor().getModuleDescriptor();
if( wsdlPath.equals(webService.getWsdlFileUri())){
// If the request is for the main wsdl document, return
// the final wsdl instead of the wsdl from the module.
wsdlUrl = webService.getWsdlFileUrl();
} else if( isWsdlContent(wsdlPath,
webService.getBundleDescriptor()) ) {
// For relative document imports. These documents do not
// require modification during deployment, so serve them
// up directly from the packaged module. isWsdlContent()
// check ensures we don't serve up arbitrary content from
// the module.
URL finalWsdlUrl = webService.getWsdlFileUrl();
String finalWsdlPath = finalWsdlUrl.getPath();
// remove the final wsdl uri from the above path
String wsdlDirPath = finalWsdlPath.substring(0, finalWsdlPath.length()-webService.getWsdlFileUri().length());
File wsdlDir = new File(wsdlDirPath);
File wsdlFile = new File(wsdlDir, wsdlPath.replace('/', File.separatorChar));
try {
wsdlUrl = wsdlFile.toURL();
} catch(MalformedURLException mue) {
logger.log(Level.INFO, "Failure serving WSDL for " +
webService.getName(), mue);
}
}
}
} else if( queryString.equalsIgnoreCase("WSDL") ) {
wsdlUrl = webService.getWsdlFileUrl();
}
boolean success = false;
if( wsdlUrl != null ) {
InputStream is = null;
try {
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
// if the requested file is the main wsdl document, we are going
// to reprocess it through the XML transformer to change the final
// endpoint URL correct for this particular web server instance.
// This is necessary in the case of SE/EE installations where
// the application can be running on different machines and ports
// than the one they were deployed on (DAS).
if (wsdlUrl.toURI().equals(webService.getWsdlFileUrl().toURI())) {
// get the application module ID
try {
String moduleID = endpoint.getBundleDescriptor().getApplication().getRegistrationName();
WebServerInfo wsi = getWebServerInfoForDAS();
URL url = webService.getWsdlFileUrl();
File originalWsdlFile = new File(url.getPath()+"__orig");
if(!originalWsdlFile.exists()) {
originalWsdlFile = new File(url.getPath());
}
generateFinalWsdl(originalWsdlFile.toURL(), webService, wsi, response.getOutputStream());
} catch(Exception e) {
// if this fail, we revert to service the untouched
// repository item.
URLConnection urlCon = wsdlUrl.openConnection();
urlCon.setUseCaches(false);
is = urlCon.getInputStream();
copyIsToOs(is, response.getOutputStream());
}
} else {
// Copy bytes into output. Disable caches to avoid jar URL
// caching problem.
URLConnection urlCon = wsdlUrl.openConnection();
urlCon.setUseCaches(false);
is = urlCon.getInputStream();
copyIsToOs(is, response.getOutputStream());
}
success = true;
if( logger.isLoggable(Level.FINE) ) {
logger.fine("Serving up final wsdl " + wsdlUrl + " for " +
request.getRequestURL() +
(queryString != null ? ("?"+queryString) : ""));
}
} catch(Exception e) {
logger.log(Level.INFO, "Failure serving WSDL for web service " +
webService.getName(), e);
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ex) {}
}
}
}
if( !success ) {
String message =
"Invalid wsdl request " + request.getRequestURL() +
(queryString != null ? ("?"+queryString) : "") +
" for web service "+ webService.getName();
logger.info(message);
writeInvalidMethodType(response, message);
}
return success;
}
private void copyIsToOs(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[4096];
int len = 0;
while (len != -1) {
try {
len = is.read(buf, 0, buf.length);
} catch (EOFException eof){
break;
}
if(len != -1) {
os.write(buf, 0, len);
}
}
os.flush();
is.close();
os.close();
}
/**
* All wsdl files and wsdl imported files live under a well-known
* wsdl directory.
* @param uri module uri
*/
public boolean isWsdlContent(String uri, BundleDescriptor bundle) {
String wsdlDir = getWsdlDir(bundle);
return (uri != null) && uri.startsWith(wsdlDir);
}
/**
* @return module-specific dedicated wsdl directory
*/
public String getWsdlDir(BundleDescriptor bundle) {
boolean isWar = (bundle instanceof WebBundleDescriptor);
return isWar ? "WEB-INF/wsdl" : "META-INF/wsdl";
}
/**
* Set up a stub for request/response SOAP message logging.
*/
public void setClientTransportLog(ServiceReferenceDescriptor serviceRef,
Stub stub, String transportLogUrlStr) {
try {
final String logUrlString = transportLogUrlStr;
OutputStream os = (OutputStream)
java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction() {
public java.lang.Object run() throws Exception {
URL transportLogUrl = new URL(logUrlString);
File transportFile =new File(transportLogUrl.getFile());
return new FileOutputStream(transportFile, true);
}
});
/* ClientTransportFactory transportFactory =
rpcFactory.createClientTransportFactory(
ClientTransportFactoryTypes.HTTP, os);
if( stub instanceof StubBase ) {
((StubBase)stub)._setTransportFactory(transportFactory);
logger.info("Logging client transport for service-ref " +
serviceRef.getName() + " to file " +
transportLogUrlStr);
}*/
} catch(PrivilegedActionException pae) {
logger.log(Level.INFO, "", pae.getCause());
} catch(Throwable t) {
logger.log(Level.INFO, "", t);
}
}
/**
* Collect all relative imports from a web service's main wsdl document.
*
*@param wsdlRelativeImports outupt param in which wsdl relative imports
* will be added
*
*@param schemaRelativeImports outupt param in which schema relative
* imports 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 don't want to be too strict in processing wsdls that could be 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(document, schemaRelativeImports);
procesWsdlImports(document, wsdlRelativeImports);
procesSchemaIncludes(document, schemaIncludes);
procesWsdlIncludes(document, wsdlIncludes);
} catch (SAXParseException spe) {
// Error generated by the parser
logger.log(Level.SEVERE,"\n** Parsing error" + ", line " +
spe.getLineNumber() + ", uri " + spe.getSystemId());
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null) {
x = spe.getException();
}
logger.log(Level.SEVERE,"Error occured", x);
} catch (Exception sxe) {
logger.log(Level.SEVERE, "Error parsing WSDL" + sxe.getMessage());
} finally {
try {
if(is != null) {
is.close();
}
} catch (IOException io) {}
}
}
private void addImportsAndIncludes(NodeList list, Collection result,
String namespace, String location) throws SAXException,
ParserConfigurationException, IOException, SAXParseException {
for(int i=0; i<list.getLength(); i++) {
String givenLocation = null;
Node element = list.item(i);
NamedNodeMap attrs = element.getAttributes();
Node n= attrs.getNamedItem(location);
if(n != null) {
givenLocation = n.getNodeValue();
}
if((givenLocation == null) ||
((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);
}
return;
}
private void procesSchemaImports(Document document, Collection schemaImportCollection) throws SAXException,
ParserConfigurationException, IOException {
NodeList schemaImports =
document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "import");
addImportsAndIncludes(schemaImports, schemaImportCollection, "namespace", "schemaLocation");
}
private void procesWsdlImports(Document document, Collection wsdlImportCollection) throws SAXException,
ParserConfigurationException, IOException {
NodeList wsdlImports =
document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "import");
addImportsAndIncludes(wsdlImports, wsdlImportCollection, "namespace", "location");
}
private void procesSchemaIncludes(Document document, Collection schemaIncludeCollection) throws SAXException,
ParserConfigurationException, IOException{
NodeList schemaIncludes =
document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "include");
addImportsAndIncludes(schemaIncludes, schemaIncludeCollection, null, "schemaLocation");
}
private void procesWsdlIncludes(Document document, Collection wsdlIncludesCollection) throws SAXException,
ParserConfigurationException, IOException{
NodeList wsdlIncludes =
document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "include");
addImportsAndIncludes(wsdlIncludes, wsdlIncludesCollection, null, "location");
}
/**
* Transform the deployed WSDL document for a given webservice by
* replacing the ENDPOINT ADDRESS for each port with the actual
* endpoint address on which it will be listening.
*
*/
public void generateFinalWsdl(URL wsdlFileUrl, WebService webService, WebServerInfo wsi,
File finalWsdlFile) throws Exception {
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(finalWsdlFile));
generateFinalWsdl(wsdlFileUrl, webService, wsi, outputStream);
}
public void generateFinalWsdl(URL wsdlFileUrl, WebService webService, WebServerInfo wsi,
OutputStream outputStream) throws Exception {
Collection wsdlRelativeImports = new HashSet();
Collection wsdlIncludes = new HashSet();
Collection schemaRelativeImports = new HashSet();
Collection schemaIncludes = new HashSet();
if( webService.hasUrlPublishing() ) {
parseRelativeImports(wsdlFileUrl, wsdlRelativeImports,
wsdlIncludes, schemaRelativeImports, schemaIncludes);
}
Collection endpoints = webService.getEndpoints();
// a WSDL file can contain several ports associated to a service.
// however Deployment descriptors can be expressed in two ways
// to describe such a scenario in webservices.xml :
// - One webservice-description with 2 port-components
// - Two webservice-description with 1 port-component
// The issue with #1, is that we need to configure the XSL with
// the two ports so that the resulting unique WSDL has the correct
// endpoint information and the JAXRPC stubs generated correctly.
// So we need to check if this bundle is declaring more webservice
// descriptor pointing to the same WSDL file...
Collection endpointsCopy = new ArrayList();
endpointsCopy.addAll(endpoints);
BundleDescriptor bundle = webService.getBundleDescriptor();
WebServicesDescriptor wsd = bundle.getWebServices();
Collection webServices = wsd.getWebServices();
if (webServices.size()>1) {
for (Iterator wsIter = webServices.iterator();wsIter.hasNext();) {
WebService aWS = (WebService) wsIter.next();
if (webService.getName().equals(aWS.getName())) {
continue;
}
// this is another web service defined in the same bundle.
// let's check if it points to the same WSDL file
if ((webService.getWsdlFileUri() != null) &&
(aWS.getWsdlFileUri() != null) &&
(webService.getWsdlFileUri().equals(aWS.getWsdlFileUri()))) {
endpointsCopy.addAll(aWS.getEndpoints());
} else if ((webService.getWsdlFileUrl() != null) &&
(aWS.getWsdlFileUrl() != null) &&
((webService.getWsdlFileUrl().toString())
.equals(aWS.getWsdlFileUrl().toString()))) {
endpointsCopy.addAll(aWS.getEndpoints());
}
}
}
// Load the wsdl file bytes with caching turned off. This is
// to avoid a jar url consistency problem that can arise if we
// overwrite the module file later on in deployment.
InputStream wsdlInputStream = new BufferedInputStream(wsdlFileUrl.openStream());
Source XsltWsdlDocument = new StreamSource(wsdlInputStream);
Templates templates = createTemplatesFor
(endpointsCopy, wsdlRelativeImports, wsdlIncludes,
schemaRelativeImports, schemaIncludes);
Transformer transformer = templates.newTransformer();
// WSDL is associated with webservice, but url is endpoint-specific,
// so let WebService choose which endpoint to use.
WebServiceEndpoint endpointForImport =
webService.pickEndpointForRelativeImports();
URL root= wsi.getWebServerRootURL(endpointForImport.isSecure());
URL finalWsdlUrl = endpointForImport.composeFinalWsdlUrl(root);
int wsdlImportNum = 0;
for(Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext();){
Import next = (Import) iter.next();
transformer.setParameter
(WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum,
next.getNamespace());
// Convert each relative import into an absolute import, using
// the final wsdl's Url as the context
URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
transformer.setParameter
(WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum, relativeUrl);
wsdlImportNum++;
}
int schemaImportNum = 0;
for(Iterator iter = schemaRelativeImports.iterator(); iter.hasNext();){
Import next = (Import) iter.next();
transformer.setParameter
(SCHEMA_IMPORT_NAMESPACE_PARAM_NAME + schemaImportNum,
next.getNamespace());
// Convert each relative import into an absolute import, using
// the final wsdl's Url as the context
URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
transformer.setParameter
(SCHEMA_IMPORT_LOCATION_PARAM_NAME + schemaImportNum,
relativeUrl);
schemaImportNum++;
}
int wsdlIncludeNum = 0;
for(Iterator iter = wsdlIncludes.iterator(); iter.hasNext();){
Import next = (Import) iter.next();
URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
transformer.setParameter
(WSDL_INCLUDE_LOCATION_PARAM_NAME + wsdlIncludeNum, relativeUrl);
wsdlIncludeNum++;
}
int schemaIncludeNum = 0;
for(Iterator iter = schemaIncludes.iterator(); iter.hasNext();){
Import next = (Import) iter.next();
URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
transformer.setParameter
(SCHEMA_INCLUDE_LOCATION_PARAM_NAME + schemaIncludeNum,
relativeUrl);
schemaIncludeNum++;
}
int endpointNum = 0;
for(Iterator iter = endpointsCopy.iterator(); iter.hasNext();) {
WebServiceEndpoint next = (WebServiceEndpoint) iter.next();
// 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.
URL rootURL = wsi.getWebServerRootURL(next.isSecure());
URL actualAddress = next.composeEndpointAddress(rootURL);
transformer.setParameter(ENDPOINT_ADDRESS_PARAM_NAME + endpointNum,
actualAddress.toExternalForm());
String endpointType = next.implementedByEjbComponent() ?
"EJB" : "Servlet";
logger.log(Level.INFO,
"enterprise.deployment.endpoint.registration",
new Object[] { endpointType,
next.getEndpointName(), actualAddress });
endpointNum++;
}
transformer.transform(XsltWsdlDocument, new StreamResult(outputStream));
wsdlInputStream.close();
outputStream.close();
return;
}
public HandlerInfo createHandlerInfo(WebServiceHandler handler,
ClassLoader loader)
throws Exception {
QName[] headers = new QName[handler.getSoapHeaders().size()];
int i = 0;
for(Iterator iter = handler.getSoapHeaders().iterator();
iter.hasNext();) {
headers[i] = (QName) iter.next();
i++;
}
Map properties = new HashMap();
for(Iterator iter = handler.getInitParams().iterator();
iter.hasNext();) {
NameValuePairDescriptor next = (NameValuePairDescriptor)
iter.next();
properties.put(next.getName(), next.getValue());
}
Class handlerClass = loader.loadClass(handler.getHandlerClass());
return new HandlerInfo(handlerClass, properties, headers);
}
/**
* Accessing wsdl URL might involve file system access, so wrap
* operation in a doPrivileged block.
*/
public URL privilegedGetServiceRefWsdl
(ServiceReferenceDescriptor desc) throws Exception {
URL wsdlFileURL;
try {
final ServiceReferenceDescriptor serviceRef = desc;
wsdlFileURL = (URL) java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction() {
public java.lang.Object run() throws Exception {
URL retVal;
if(serviceRef.hasWsdlOverride()) {
retVal = serviceRef.getWsdlOverride();
} else {
// Upon server restart, wsdlfileURL can be null
// check that and return value from wsdlFileURI
if(serviceRef.getWsdlFileUrl() != null) {
retVal = serviceRef.getWsdlFileUrl();
} else {
if(serviceRef.getWsdlFileUri().startsWith("http")) {
retVal = new URL(serviceRef.getWsdlFileUri());
} else {
if ((serviceRef.getWsdlFileUri().startsWith("WEB-INF")|| serviceRef.getWsdlFileUri().startsWith("META-INF"))) {
//This can be the case when the toURL fails
//because in its implementation it looks for user.dir
// which sometimes can vary based on where vm is launched
// so in this case
//resolve from application path
WebServiceContractImpl wscImpl = WebServiceContractImpl.getInstance();
ServerEnvironment se = wscImpl.getHabitat().getByContract(ServerEnvironment.class);
File appFile = new File(se.getApplicationRepositoryPath(),serviceRef.getBundleDescriptor().getApplication().getAppName());
if (appFile.exists()) {
retVal = new File(appFile,serviceRef.getWsdlFileUri()).toURL();
} else {
//Fix for 6853656 and 6868695
//In case of appclients the wsdl will be in the classpath
//This will work for launches using the appclient command and
// for Java Web Start launches
retVal = Thread.currentThread().getContextClassLoader().getResource(serviceRef.getWsdlFileUri()) ;
}
}else {
retVal = new File(serviceRef.getWsdlFileUri()).toURL();
}
}
}
}
return retVal;
}
});
} catch(PrivilegedActionException pae) {
logger.log(Level.WARNING, "", pae);
Exception e = new Exception();
e.initCause(pae.getCause());
throw e;
}
return wsdlFileURL;
}
public boolean isJAXWSbasedService(WebService ws) {
if(ws.isJaxWSBased() != null) {
//already verified
return ws.isJaxWSBased();
}
boolean jaxwsEndPtFound = false;
boolean jaxrpcEndPtFound = false;
String declaredType = ws.getType();
if(declaredType != null) {
if(declaredType.equals("JAX-WS")) {
jaxwsEndPtFound = true;
} else if(declaredType.equals("JAX-RPC")) {
jaxrpcEndPtFound = false;
} else {
logger.log(Level.SEVERE, rb.getString("webservice.type.error"),new Object[] {ws.getDescription(), declaredType});
}
}
//Verify that all the endpoints are of the same type
for (WebServiceEndpoint endpoint : ws.getEndpoints()) {
String implClassName;
if (endpoint.implementedByEjbComponent()) {
implClassName = endpoint.getEjbComponentImpl().getEjbClassName();
} else {
implClassName = endpoint.getWebComponentImpl().getWebComponentImplementation();
}
Class implClass;
try {
implClass = Thread.currentThread().getContextClassLoader().loadClass(implClassName);
} catch(Exception e) {
logger.log(Level.SEVERE, "Unable to load impl class ", e);
continue;
}
if (implClass!=null) {
if(implClass.getAnnotation(javax.xml.ws.WebServiceProvider.class) != null) {
// if we already found a jaxrpcendpoint, flag error since we do not support jaxws+jaxrpc endpoint
// in the same service
if(jaxrpcEndPtFound) {
logger.log(Level.SEVERE, rb.getString("jaxws-jaxrpc.error"));
continue;
}
//This is a JAXWS endpoint with @WebServiceProvider
//Do not run wsgen for this endpoint
jaxwsEndPtFound = true;
continue;
}
if(implClass.getAnnotation(javax.jws.WebService.class) != null) {
// if we already found a jaxrpcendpoint, flag error since we do not support jaxws+jaxrpc endpoint
// in the same service
if(jaxrpcEndPtFound) {
logger.log(Level.SEVERE, rb.getString("jaxws-jaxrpc.error"));
continue;
}
// This is a JAXWS endpoint with @WebService;
jaxwsEndPtFound = true;
continue;
}
if (JAXWSServlet.class.isAssignableFrom(implClass)) {
// if we already found a jaxrpcendpoint, flag error since we do not support jaxws+jaxrpc endpoint
// in the same service
if(jaxrpcEndPtFound) {
logger.log(Level.SEVERE, rb.getString("jaxws-jaxrpc.error"));
continue;
}
// This is a JAXWS endpoint with @WebService;
jaxwsEndPtFound = true;
continue;
} else {
// this is a jaxrpc endpoint
// if we already found a jaxws endpoint, flag error since we do not support jaxws+jaxrpc endpoint
// in the same service
if(jaxwsEndPtFound) {
logger.log(Level.SEVERE, rb.getString("jaxws-jaxrpc.error"));
continue;
}
// Set spec version to 1.1 to indicate later the wscompile should be run
// We do this here so that jaxrpc endpoint having J2EE1.4 or JavaEE5
// descriptors will work properly
jaxrpcEndPtFound = true;
ws.getWebServicesDescriptor().setSpecVersion("1.1");
}
}
}
if(jaxwsEndPtFound) {
ws.setJaxWSBased(true);
ws.setType("JAX-WS");
} else {
ws.setJaxWSBased(false);
ws.setType("JAX-RPC");
}
return jaxwsEndPtFound;
}
public javax.xml.rpc.Service createConfiguredService
(ServiceReferenceDescriptor desc) throws Exception {
final ServiceReferenceDescriptor serviceRef = desc;
javax.xml.rpc.Service service = null;
try {
// Configured service can be created with any kind of URL.
// Since resolving it might require file system access,
// do operation in a doPrivivileged block. JAXRPC RI should
// probably have the doPrivileged as well.
final URL wsdlFileURL = privilegedGetServiceRefWsdl(serviceRef);
final QName serviceName = serviceRef.getServiceName();
final ServiceFactory serviceFactory = ServiceFactory.newInstance();
service = (javax.xml.rpc.Service)
java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction() {
public java.lang.Object run() throws Exception {
return serviceFactory.createService
(wsdlFileURL, serviceName);
}
});
} catch(PrivilegedActionException pae) {
logger.log(Level.WARNING, "", pae);
Exception e = new Exception();
e.initCause(pae.getCause());
throw e;
}
return service;
}
public void configureHandlerChain(ServiceReferenceDescriptor serviceRef,
javax.xml.rpc.Service service,
Iterator ports, ClassLoader loader)
throws Exception {
if( !serviceRef.hasHandlers() ) {
return;
}
HandlerRegistry registry = service.getHandlerRegistry();
while(ports.hasNext()) {
QName nextPort = (QName) ports.next();
List handlerChain = registry.getHandlerChain(nextPort);
Collection soapRoles = new HashSet();
for(Iterator iter = serviceRef.getHandlers().iterator();
iter.hasNext();) {
WebServiceHandler nextHandler = (WebServiceHandler) iter.next();
Collection portNames = nextHandler.getPortNames();
if( portNames.isEmpty() ||
portNames.contains(nextPort.getLocalPart()) ) {
soapRoles.addAll(nextHandler.getSoapRoles());
HandlerInfo handlerInfo =
createHandlerInfo(nextHandler, loader);
handlerChain.add(handlerInfo);
}
}
}
}
/**
* Create an xslt template for transforming the packaged webservice
* WSDL to a final WSDL.
*/
private Templates createTemplatesFor(Collection endpoints,
Collection wsdlRelativeImports,
Collection wsdlIncludes,
Collection schemaRelativeImports,
Collection schemaIncludes) throws Exception {
// create the stylesheet
ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(bos, "UTF-8");
writer.write("<xsl:transform version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:soap12=\"http://schemas.xmlsoap.org/wsdl/soap12/\">\n");
int wsdlImportNum = 0;
for(Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext();) {
Import next = (Import) iter.next();
String importNamespaceParam =
WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum;
String importLocationParam =
WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum;
writer.write("<xsl:param name=\"" + importNamespaceParam + "\"/>\n");
writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n");
writer.write("<xsl:template match=\"/\">
Other Glassfish examples (source code examples)Here is a short list of links related to this Glassfish WsUtil.java source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.