index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDNonFatalException.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A non-fatal WSDD exception (bad type mapping, for instance) * * @author Glen Daniels (gdaniels@apache.org) */ package org.apache.axis.deployment.wsdd; public class WSDDNonFatalException extends WSDDException { public WSDDNonFatalException(String msg) { super(msg); } public WSDDNonFatalException(Exception e) { super(e); } }
7,700
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDParameter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; public class WSDDParameter extends WSDDElement { OperationDesc parent; ParameterDesc parameter = new ParameterDesc(); public WSDDParameter(Element e, OperationDesc parent) throws WSDDException { super(e); this.parent = parent; // Get the parameter's name. If a qname is specified, use that, // otherwise also look for a "name" attribute. (name specifies // an unqualified name) String nameStr = e.getAttribute(ATTR_QNAME); if (nameStr != null && !nameStr.equals("")) { parameter.setQName(XMLUtils.getQNameFromString(nameStr, e)); } else { nameStr = e.getAttribute(ATTR_NAME); if (nameStr != null && !nameStr.equals("")) { parameter.setQName(new QName(null, nameStr)); } } String modeStr = e.getAttribute(ATTR_MODE); if (modeStr != null && !modeStr.equals("")) { parameter.setMode(ParameterDesc.modeFromString(modeStr)); } String inHStr = e.getAttribute(ATTR_INHEADER); if (inHStr != null) { parameter.setInHeader(JavaUtils.isTrueExplicitly(inHStr)); } String outHStr = e.getAttribute(ATTR_OUTHEADER); if (outHStr != null) { parameter.setOutHeader(JavaUtils.isTrueExplicitly(outHStr)); } String typeStr = e.getAttribute(ATTR_TYPE); if (typeStr != null && !typeStr.equals("")) { parameter.setTypeQName(XMLUtils.getQNameFromString(typeStr, e)); } String itemQNameStr = e.getAttribute(ATTR_ITEMQNAME); if (itemQNameStr != null && !itemQNameStr.equals("")) { parameter.setItemQName(XMLUtils.getQNameFromString(itemQNameStr, e)); } String itemTypeStr = e.getAttribute(ATTR_ITEMTYPE); if (itemTypeStr != null && !itemTypeStr.equals("")) { parameter.setItemType(XMLUtils.getQNameFromString(itemTypeStr, e)); } Element docElem = getChildElement(e, ELEM_WSDD_DOC); if (docElem != null) { WSDDDocumentation documentation = new WSDDDocumentation(docElem); parameter.setDocumentation(documentation.getValue()); } } public WSDDParameter() { } public WSDDParameter(ParameterDesc parameter) { this.parameter = parameter; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); QName qname = parameter.getQName(); if (qname != null) { if (qname.getNamespaceURI() != null && !qname.getNamespaceURI().equals("")) { attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", context.qName2String(parameter.getQName())); } else { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", parameter.getQName().getLocalPart()); } } // Write the mode attribute, but only if it's not the default (IN) byte mode = parameter.getMode(); if (mode != ParameterDesc.IN) { String modeStr = ParameterDesc.getModeAsString(mode); attrs.addAttribute("", ATTR_MODE, ATTR_MODE, "CDATA", modeStr); } if (parameter.isInHeader()) { attrs.addAttribute("", ATTR_INHEADER, ATTR_INHEADER, "CDATA", "true"); } if (parameter.isOutHeader()) { attrs.addAttribute("", ATTR_OUTHEADER, ATTR_OUTHEADER, "CDATA", "true"); } QName typeQName = parameter.getTypeQName(); if (typeQName != null) { attrs.addAttribute("", ATTR_TYPE, ATTR_TYPE, "CDATA", context.qName2String(typeQName)); } QName itemQName = parameter.getItemQName(); if (itemQName != null) { attrs.addAttribute("", ATTR_ITEMQNAME, ATTR_ITEMQNAME, "CDATA", context.qName2String(itemQName)); } QName itemType = parameter.getItemType(); if (itemType != null) { attrs.addAttribute("", ATTR_ITEMTYPE, ATTR_ITEMTYPE, "CDATA", context.qName2String(itemType)); } context.startElement(getElementName(), attrs); if (parameter.getDocumentation() != null) { WSDDDocumentation documentation = new WSDDDocumentation(parameter.getDocumentation()); documentation.writeToContext(context); } context.endElement(); } public ParameterDesc getParameter() { return parameter; } public void setParameter(ParameterDesc parameter) { this.parameter = parameter; } /** * Return the element name of a particular subclass. */ protected QName getElementName() { return WSDDConstants.QNAME_PARAM; } }
7,701
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDTargetedChain.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.io.IOException; /** * */ public abstract class WSDDTargetedChain extends WSDDDeployableItem { private WSDDRequestFlow requestFlow; private WSDDResponseFlow responseFlow; private QName pivotQName; protected WSDDTargetedChain() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ protected WSDDTargetedChain(Element e) throws WSDDException { super(e); Element reqEl = getChildElement(e, ELEM_WSDD_REQFLOW); if (reqEl != null && reqEl.getElementsByTagName("*").getLength()>0) { requestFlow = new WSDDRequestFlow(reqEl); } Element respEl = getChildElement(e, ELEM_WSDD_RESPFLOW); if (respEl != null && respEl.getElementsByTagName("*").getLength()>0) { responseFlow = new WSDDResponseFlow(respEl); } // !!! pivot? use polymorphic method? String pivotStr = e.getAttribute(ATTR_PIVOT); if (pivotStr != null && !pivotStr.equals("")) pivotQName = XMLUtils.getQNameFromString(pivotStr, e); } public WSDDRequestFlow getRequestFlow() { return requestFlow; } public void setRequestFlow(WSDDRequestFlow flow) { requestFlow = flow; } public WSDDResponseFlow getResponseFlow() { return responseFlow; } public void setResponseFlow(WSDDResponseFlow flow) { responseFlow = flow; } /** * * @return XXX */ public WSDDFaultFlow[] getFaultFlows() { return null; } /** * * @param name XXX * @return XXX */ public WSDDFaultFlow getFaultFlow(QName name) { WSDDFaultFlow[] t = getFaultFlows(); for (int n = 0; n < t.length; n++) { if (t[n].getQName().equals(name)) { return t[n]; } } return null; } /** * * @param type XXX */ public void setType(String type) throws WSDDException { throw new WSDDException(Messages.getMessage( "noTypeSetting", getElementName().getLocalPart())); } public QName getPivotQName() { return pivotQName; } public void setPivotQName(QName pivotQName) { this.pivotQName = pivotQName; } /** * * @param registry XXX * @return XXX * @throws ConfigurationException XXX */ public Handler makeNewInstance(EngineConfiguration registry) throws ConfigurationException { Handler reqHandler = null; WSDDChain req = getRequestFlow(); if (req != null) reqHandler = req.getInstance(registry); Handler pivot = null; if (pivotQName != null) { if (URI_WSDD_JAVA.equals(pivotQName.getNamespaceURI())) { try { pivot = (Handler)ClassUtils.forName(pivotQName.getLocalPart()).newInstance(); } catch (InstantiationException e) { throw new ConfigurationException(e); } catch (IllegalAccessException e) { throw new ConfigurationException(e); } catch (ClassNotFoundException e) { throw new ConfigurationException(e); } } else { pivot = registry.getHandler(pivotQName); } } Handler respHandler = null; WSDDChain resp = getResponseFlow(); if (resp != null) respHandler = resp.getInstance(registry); Handler retVal = new org.apache.axis.SimpleTargetedChain(reqHandler, pivot, respHandler); retVal.setOptions(getParametersTable()); return retVal; } /** * Write this element out to a SerializationContext */ public final void writeFlowsToContext(SerializationContext context) throws IOException { if (requestFlow != null) { requestFlow.writeToContext(context); } if (responseFlow != null) { responseFlow.writeToContext(context); } } public void deployToRegistry(WSDDDeployment registry) { // deploy any named subparts if (requestFlow != null) { requestFlow.deployToRegistry(registry); } if (responseFlow != null) { responseFlow.deployToRegistry(registry); } } }
7,702
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDOperation.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.description.FaultDesc; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; /** * * Parse the WSDD operation elements. * * Example: * &lt;operation name="name" qname="element QName" returnQName="QName"&gt; * &lt;parameter ... /&gt; * &lt;/operation&gt; * */ public class WSDDOperation extends WSDDElement { /** Holds all our actual data */ OperationDesc desc = new OperationDesc(); /** * Constructor */ public WSDDOperation(OperationDesc desc) { this.desc = desc; } /** * Constructor from XML * * @param e (Element) the &lt;operation&gt; element * @param parent our ServiceDesc. * @throws WSDDException XXX */ public WSDDOperation(Element e, ServiceDesc parent) throws WSDDException { super(e); desc.setParent(parent); desc.setName(e.getAttribute(ATTR_NAME)); String qNameStr = e.getAttribute(ATTR_QNAME); if (qNameStr != null && !qNameStr.equals("")) desc.setElementQName(XMLUtils.getQNameFromString(qNameStr, e)); String retQNameStr = e.getAttribute(ATTR_RETQNAME); if (retQNameStr != null && !retQNameStr.equals("")) desc.setReturnQName(XMLUtils.getQNameFromString(retQNameStr, e)); String retTypeStr = e.getAttribute(ATTR_RETTYPE); if (retTypeStr != null && !retTypeStr.equals("")) desc.setReturnType(XMLUtils.getQNameFromString(retTypeStr, e)); String retHStr = e.getAttribute(ATTR_RETHEADER); if (retHStr != null) { desc.setReturnHeader(JavaUtils.isTrueExplicitly(retHStr)); } String retItemQName = e.getAttribute(ATTR_RETITEMQNAME); if (retItemQName != null && !retItemQName.equals("")) { ParameterDesc param = desc.getReturnParamDesc(); param.setItemQName(XMLUtils.getQNameFromString(retItemQName, e)); } String retItemType = e.getAttribute(ATTR_RETITEMTYPE); if (retItemType != null && !retItemType.equals("")) { ParameterDesc param = desc.getReturnParamDesc(); param.setItemType(XMLUtils.getQNameFromString(retItemType, e)); } String soapAction = e.getAttribute(ATTR_SOAPACTION); if (soapAction != null) { desc.setSoapAction(soapAction); } String mepString = e.getAttribute(ATTR_MEP); if (mepString != null) { desc.setMep(mepString); } Element [] parameters = getChildElements(e, ELEM_WSDD_PARAM); for (int i = 0; i < parameters.length; i++) { Element paramEl = parameters[i]; WSDDParameter parameter = new WSDDParameter(paramEl, desc); desc.addParameter(parameter.getParameter()); } Element [] faultElems = getChildElements(e, ELEM_WSDD_FAULT); for (int i = 0; i < faultElems.length; i++) { Element faultElem = faultElems[i]; WSDDFault fault = new WSDDFault(faultElem); desc.addFault(fault.getFaultDesc()); } Element docElem = getChildElement(e, ELEM_WSDD_DOC); if (docElem != null) { WSDDDocumentation documentation = new WSDDDocumentation(docElem); desc.setDocumentation(documentation.getValue()); } } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); if (desc.getReturnQName() != null) { attrs.addAttribute("", ATTR_RETQNAME, ATTR_RETQNAME, "CDATA", context.qName2String(desc.getReturnQName())); } if (desc.getReturnType() != null) { attrs.addAttribute("", ATTR_RETTYPE, ATTR_RETTYPE, "CDATA", context.qName2String(desc.getReturnType())); } if (desc.isReturnHeader()) { attrs.addAttribute("", ATTR_RETHEADER, ATTR_RETHEADER, "CDATA", "true"); } if (desc.getName() != null) { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", desc.getName()); } if (desc.getElementQName() != null) { attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", context.qName2String(desc.getElementQName())); } QName retItemQName = desc.getReturnParamDesc().getItemQName(); if (retItemQName != null) { attrs.addAttribute("", ATTR_RETITEMQNAME, ATTR_RETITEMQNAME, "CDATA", context.qName2String(retItemQName)); } if (desc.getSoapAction() != null) { attrs.addAttribute("", ATTR_SOAPACTION, ATTR_SOAPACTION, "CDATA", desc.getSoapAction()); } if (desc.getMep() != null) { attrs.addAttribute("", ATTR_MEP, ATTR_MEP, "CDATA", desc.getMepString()); } context.startElement(getElementName(), attrs); if (desc.getDocumentation() != null) { WSDDDocumentation documentation = new WSDDDocumentation(desc.getDocumentation()); documentation.writeToContext(context); } ArrayList params = desc.getParameters(); for (Iterator i = params.iterator(); i.hasNext();) { ParameterDesc parameterDesc = (ParameterDesc) i.next(); WSDDParameter p = new WSDDParameter(parameterDesc); p.writeToContext(context); } ArrayList faults = desc.getFaults(); if (faults != null) { for (Iterator i = faults.iterator(); i.hasNext();) { FaultDesc faultDesc = (FaultDesc) i.next(); WSDDFault f = new WSDDFault(faultDesc); f.writeToContext(context); } } context.endElement(); } protected QName getElementName() { return QNAME_OPERATION; } public OperationDesc getOperationDesc() { return desc; } }
7,703
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDTypeMapping.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializerFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SerializerFactory; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.ser.BaseDeserializerFactory; import org.apache.axis.encoding.ser.BaseSerializerFactory; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; /** * */ public class WSDDTypeMapping extends WSDDElement { private static final Log log = LogFactory.getLog(WSDDTypeMapping.class.getName()); protected QName qname = null; protected String serializer = null; protected String deserializer = null; protected QName typeQName = null; protected String encodingStyle = null; /** * Default constructor * */ public WSDDTypeMapping() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDTypeMapping(Element e) throws WSDDException { serializer = e.getAttribute(ATTR_SERIALIZER); deserializer = e.getAttribute(ATTR_DESERIALIZER); Attr attrNode = e.getAttributeNode(ATTR_ENCSTYLE); if (attrNode == null) { encodingStyle = Constants.URI_DEFAULT_SOAP_ENC; } else { encodingStyle = attrNode.getValue(); } String qnameStr = e.getAttribute(ATTR_QNAME); qname = XMLUtils.getQNameFromString(qnameStr, e); // JSR 109 v0.093 indicates that this attribute is named "type" String typeStr = e.getAttribute(ATTR_TYPE); typeQName = XMLUtils.getQNameFromString(typeStr, e); if (typeStr == null || typeStr.equals("")) { typeStr = e.getAttribute(ATTR_LANG_SPEC_TYPE); typeQName = XMLUtils.getQNameFromString(typeStr, e); } } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", ATTR_ENCSTYLE, ATTR_ENCSTYLE, "CDATA", encodingStyle); attrs.addAttribute("", ATTR_SERIALIZER, ATTR_SERIALIZER, "CDATA", serializer); attrs.addAttribute("", ATTR_DESERIALIZER, ATTR_DESERIALIZER, "CDATA", deserializer); String typeStr = context.qName2String(typeQName); // JSR 109 indicates that the name of this field is type attrs.addAttribute("", ATTR_TYPE, ATTR_TYPE, "CDATA", typeStr); String qnameStr = context.attributeQName2String(qname); attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", qnameStr); context.startElement(QNAME_TYPEMAPPING, attrs); context.endElement(); } protected QName getElementName() { return QNAME_TYPEMAPPING; } /** * * @return XXX */ public String getEncodingStyle() { return encodingStyle; } /** * * @param es XXX */ public void setEncodingStyle(String es) { encodingStyle = es; } /** * * @return XXX */ public QName getQName() { return qname; } /** * * @param name XXX */ public void setQName(QName name) { qname = name; } /** * * @return XXX * @throws ClassNotFoundException XXX */ public Class getLanguageSpecificType() throws ClassNotFoundException { if (typeQName != null) { if (!URI_WSDD_JAVA.equals(typeQName.getNamespaceURI())) { throw new ClassNotFoundException(Messages.getMessage("badTypeNamespace00", typeQName.getNamespaceURI(), URI_WSDD_JAVA)); } String loadName = JavaUtils.getLoadableClassName(typeQName.getLocalPart()); if (JavaUtils.getWrapper(loadName) != null) { Class cls = JavaUtils.getPrimitiveClassFromName(loadName); return cls; } return ClassUtils.forName(loadName); } throw new ClassNotFoundException(Messages.getMessage("noTypeQName00")); } /** * Set javaType (type= attribute or languageSpecificType= attribute) * @param javaType the class of the javaType */ public void setLanguageSpecificType(Class javaType) { String type = javaType.getName(); typeQName = new QName(URI_WSDD_JAVA, type); } /** * Set javaType (type= attribute or languageSpecificType= attribute) * @param javaType is the name of the class. (For arrays this * could be the form my.Foo[] or could be in the form [Lmy.Foo; */ public void setLanguageSpecificType(String javaType) { typeQName = new QName(URI_WSDD_JAVA, javaType); } /** * * @return XXX * @throws ClassNotFoundException XXX */ public Class getSerializer() throws ClassNotFoundException { return ClassUtils.forName(serializer); } /** * * @return serializer factory name */ public String getSerializerName() { return serializer; } /** * * @param ser XXX */ public void setSerializer(Class ser) { serializer = ser.getName(); } /** * Set the serializer factory name * @param ser name of the serializer factory class */ public void setSerializer(String ser) { serializer = ser; } /** * * @return XXX * @throws ClassNotFoundException XXX */ public Class getDeserializer() throws ClassNotFoundException { return ClassUtils.forName(deserializer); } /** * * @return deserializer factory name */ public String getDeserializerName() { return deserializer; } /** * * @param deser XXX */ public void setDeserializer(Class deser) { deserializer = deser.getName(); } /** * Set the deserializer factory name * @param deser name of the deserializer factory class */ public void setDeserializer(String deser) { deserializer = deser; } void registerTo(TypeMapping tm) throws WSDDException { try { SerializerFactory ser = null; DeserializerFactory deser = null; // Try to construct a serializerFactory by introspecting for the // following: // public static create(Class javaType, QName xmlType) // public <constructor>(Class javaType, QName xmlType) // public <constructor>() // // The BaseSerializerFactory createFactory() method is a utility // that does this for us. if (getSerializerName() != null && !getSerializerName().equals("")) { ser = BaseSerializerFactory.createFactory(getSerializer(), getLanguageSpecificType(), getQName()); } setupSerializer(ser); if (getDeserializerName() != null && !getDeserializerName().equals("")) { deser = BaseDeserializerFactory.createFactory(getDeserializer(), getLanguageSpecificType(), getQName()); } tm.register(getLanguageSpecificType(), getQName(), ser, deser); } catch (ClassNotFoundException e) { log.error(Messages.getMessage("unabletoDeployTypemapping00", getQName().toString()), e); throw new WSDDNonFatalException(e); } catch (Exception e) { throw new WSDDException(e); } } void setupSerializer(SerializerFactory ser) { } }
7,704
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDArrayMapping.java
/* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import java.io.IOException; import javax.xml.namespace.QName; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SerializerFactory; import org.apache.axis.encoding.ser.ArraySerializerFactory; import org.apache.axis.utils.XMLUtils; /** * A <code>WSDDArrayMapping</code> is simply a <code>WSDDTypeMapping</code> * which has preset values for the serializer and deserializer attributes. * * This enables the following slightly simplified syntax when expressing * an array mapping: * * &lt;arrayMapping qname="prefix:local" languageSpecificType="java:class" innerType="prefix:local"/&gt; * */ public class WSDDArrayMapping extends WSDDTypeMapping { /** array item type */ private QName innerType = null; /** * Default constructor */ public WSDDArrayMapping() { } public WSDDArrayMapping(Element e) throws WSDDException { super(e); Attr innerTypeAttr = e.getAttributeNode(ATTR_INNER_TYPE); if (innerTypeAttr != null) { String qnameStr = innerTypeAttr.getValue(); innerType = XMLUtils.getQNameFromString(qnameStr, e); } serializer = ARRAY_SERIALIZER_FACTORY; deserializer = ARRAY_DESERIALIZER_FACTORY; } protected QName getElementName() { return QNAME_ARRAYMAPPING; } /** * @return Returns the innerType. */ public QName getInnerType() { return innerType; } public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); String typeStr = context.qName2String(typeQName); attrs.addAttribute("", ATTR_LANG_SPEC_TYPE, ATTR_LANG_SPEC_TYPE, "CDATA", typeStr); String qnameStr = context.qName2String(qname); attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", qnameStr); String innerTypeStr = context.qName2String(innerType); attrs.addAttribute("", ATTR_INNER_TYPE, ATTR_INNER_TYPE, "CDATA", innerTypeStr); context.startElement(QNAME_ARRAYMAPPING, attrs); context.endElement(); } void setupSerializer(SerializerFactory ser) { if (ser instanceof ArraySerializerFactory) { ((ArraySerializerFactory)ser).setComponentType(getInnerType()); } } }
7,705
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.namespace.QName; import java.io.IOException; import java.io.Serializable; import java.util.Vector; /** * abstract class extended by all WSDD Element classes */ public abstract class WSDDElement extends WSDDConstants implements Serializable { private String name; /** * Default constructor */ public WSDDElement() { } /** * Create an element in WSDD that wraps an extant DOM element * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDElement(Element e) throws WSDDException { validateCandidateElement(e); } /** * Return the element name of a particular subclass. */ protected abstract QName getElementName(); /** * Make sure everything looks kosher with the element name. */ private void validateCandidateElement(Element e) throws WSDDException { QName name = getElementName(); if ((null == e) || (null == e.getNamespaceURI()) || (null == e.getLocalName()) ||!e.getNamespaceURI().equals(name.getNamespaceURI()) ||!e.getLocalName().equals(name.getLocalPart())) { throw new WSDDException(Messages.getMessage("invalidWSDD00", e.getLocalName(), name.getLocalPart())); } } public Element getChildElement(Element e, String name) { Element [] elements = getChildElements(e, name); if (elements.length == 0) return null; return elements[0]; } public Element [] getChildElements(Element e, String name) { NodeList nl = e.getChildNodes(); Vector els = new Vector(); for (int i = 0; i < nl.getLength(); i++) { Node thisNode = nl.item(i); if (!(thisNode instanceof Element)) continue; Element el = (Element)thisNode; if (el.getLocalName().equals(name)) { els.add(el); } } Element [] elements = new Element [els.size()]; els.toArray(elements); return elements; } /** * Write this element out to a SerializationContext */ public abstract void writeToContext(SerializationContext context) throws IOException; }
7,706
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDDocument.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /** * represents a WSDD Document (this is the top level object in this object model) * Only one of {@link #deployment} and {@link #undeployment} should be valid. */ public class WSDDDocument extends WSDDConstants { protected static Log log = LogFactory.getLog(WSDDDocument.class.getName()); /** owner doc */ private Document doc; /** * deployment tree. may be null */ private WSDDDeployment deployment; /** undeployment tree. may be null */ private WSDDUndeployment undeployment; /** * empty constructor */ public WSDDDocument() { } /** * create and bind to a document * @param document (Document) XXX */ public WSDDDocument(Document document) throws WSDDException { setDocument(document); } /** * bind to a sub-element in a document. * @param e (Element) XXX */ public WSDDDocument(Element e) throws WSDDException { doc = e.getOwnerDocument(); if (ELEM_WSDD_UNDEPLOY.equals(e.getLocalName())) { undeployment = new WSDDUndeployment(e); } else { deployment = new WSDDDeployment(e); } } /** * Get the deployment. If there is no deployment, create an empty one * @return the deployment document */ public WSDDDeployment getDeployment() { if (deployment == null) { deployment = new WSDDDeployment(); } return deployment; } /** * get the deployment as a DOM. * Requires that the deployment member variable is not null. * @return * @throws ConfigurationException */ public Document getDOMDocument() throws ConfigurationException { StringWriter writer = new StringWriter(); SerializationContext context = new SerializationContext(writer); context.setPretty(true); try { deployment.writeToContext(context); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } try { writer.close(); return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString()))); } catch (Exception e) { return null; } } /** * write the deployment to the supplied serialization context. * @param context * @throws IOException */ public void writeToContext(SerializationContext context) throws IOException { getDeployment().writeToContext(context); } /** * Bind to a new document, setting the undeployment nodes if it is an undeployment, * the deployment tree if it is anything else. * @param document XXX */ public void setDocument(Document document) throws WSDDException { this.doc = document; Element docEl = doc.getDocumentElement(); if (ELEM_WSDD_UNDEPLOY.equals(docEl.getLocalName())) { undeployment = new WSDDUndeployment(docEl); } else { deployment = new WSDDDeployment(docEl); } } /** * do a deploy and/or undeploy, depending on what is in the document. * If both trees are set, then undeploy follows deploy. * @param registry * @throws ConfigurationException */ public void deploy(WSDDDeployment registry) throws ConfigurationException { if (deployment != null) { deployment.deployToRegistry(registry); } if (undeployment != null) { undeployment.undeployFromRegistry(registry); } } }
7,707
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDFault.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Glen Daniels (gdaniels@apache.org) */ package org.apache.axis.deployment.wsdd; import org.apache.axis.description.FaultDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; public class WSDDFault extends WSDDElement { FaultDesc desc; public WSDDFault(FaultDesc desc) { this.desc = desc; } /** * Construct a WSDDFault from a DOM Element * @param e the &lt;fault&gt; Element * @throws WSDDException */ public WSDDFault(Element e) throws WSDDException { super(e); desc = new FaultDesc(); String nameStr = e.getAttribute(ATTR_NAME); if (nameStr != null && !nameStr.equals("")) desc.setName(nameStr); String qNameStr = e.getAttribute(ATTR_QNAME); if (qNameStr != null && !qNameStr.equals("")) desc.setQName(XMLUtils.getQNameFromString(qNameStr, e)); String classNameStr = e.getAttribute(ATTR_CLASS); if (classNameStr != null && !classNameStr.equals("")) desc.setClassName(classNameStr); String xmlTypeStr = e.getAttribute(ATTR_TYPE); if (xmlTypeStr != null && !xmlTypeStr.equals("")) desc.setXmlType(XMLUtils.getQNameFromString(xmlTypeStr, e)); } /** * Return the element name of a particular subclass. */ protected QName getElementName() { return QNAME_FAULT; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", context.qName2String(desc.getQName())); attrs.addAttribute("", ATTR_CLASS, ATTR_CLASS, "CDATA", desc.getClassName()); attrs.addAttribute("", ATTR_TYPE, ATTR_TYPE, "CDATA", context.qName2String(desc.getXmlType())); context.startElement(getElementName(), attrs); context.endElement(); } public FaultDesc getFaultDesc() { return desc; } public void setFaultDesc(FaultDesc desc) { this.desc = desc; } }
7,708
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDTransport.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; /** * */ public class WSDDTransport extends WSDDTargetedChain { /** * Default constructor */ public WSDDTransport() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDTransport(Element e) throws WSDDException { super(e); } protected QName getElementName() { return WSDDConstants.QNAME_TRANSPORT; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); QName name = getQName(); if (name != null) { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", context.qName2String(name)); } name = getPivotQName(); if (name != null) { attrs.addAttribute("", ATTR_PIVOT, ATTR_PIVOT, "CDATA", context.qName2String(name)); } context.startElement(WSDDConstants.QNAME_TRANSPORT, attrs); writeFlowsToContext(context); writeParamsToContext(context); context.endElement(); } public void deployToRegistry(WSDDDeployment registry) { registry.addTransport(this); super.deployToRegistry(registry); } }
7,709
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; /** * */ public class WSDDHandler extends WSDDDeployableItem { /** * Default constructor */ public WSDDHandler() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDHandler(Element e) throws WSDDException { super(e); if (type == null && (this.getClass() == WSDDHandler.class)) { throw new WSDDException(Messages.getMessage("noTypeAttr00")); } } protected QName getElementName() { return QNAME_HANDLER; } public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); QName name = getQName(); if (name != null) { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", context.qName2String(name)); } attrs.addAttribute("", ATTR_TYPE, ATTR_TYPE, "CDATA", context.qName2String(getType())); context.startElement(WSDDConstants.QNAME_HANDLER, attrs); writeParamsToContext(context); context.endElement(); } public void deployToRegistry(WSDDDeployment deployment) { deployment.addHandler(this); } }
7,710
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDJavaRMIProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; /** * A WSDD RMI provider * * @author Davanum Srinivas (dims@yahoo.com) */ public class WSDDJavaRMIProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_RMI; } /** * */ public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { return new org.apache.axis.providers.java.RMIProvider(); } }
7,711
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDComProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; import org.apache.axis.providers.BasicProvider; import org.apache.axis.utils.ClassUtils; /** * */ public class WSDDComProvider extends WSDDProvider { public static final String OPTION_PROGID = "ProgID"; public static final String OPTION_THREADING_MODEL = "threadingModel"; public String getName() { return WSDDConstants.PROVIDER_COM; } public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { Class _class = ClassUtils.forName("org.apache.axis.providers.ComProvider"); BasicProvider provider = (BasicProvider) _class.newInstance(); String option = service.getParameter("ProgID"); if (!option.equals("")) { provider.setOption(OPTION_PROGID, option); } option = service.getParameter("threadingModel"); if (option!= null && !option.equals("")) { provider.setOption(OPTION_THREADING_MODEL, option); } return provider; } }
7,712
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDHandlerProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; /** * This is a simple provider for using Handler-based services which don't * need further configuration (such as Java classes, etc). * * @author Glen Daniels (gdaniels@apache.org) */ public class WSDDHandlerProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_HANDLER; } public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { String providerClass = service.getParameter("handlerClass"); if (providerClass == null) { throw new ConfigurationException(Messages.getMessage("noHandlerClass00")); } Class _class = ClassUtils.forName(providerClass); if (!(Handler.class.isAssignableFrom(_class))) { throw new ConfigurationException(Messages.getMessage("badHandlerClass00", _class.getName())); } return (Handler)_class.newInstance(); } }
7,713
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDJavaCORBAProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; /** * A WSDD CORBA provider * * @author Davanum Srinivas (dims@yahoo.com) */ public class WSDDJavaCORBAProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_CORBA; } /** * */ public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { return new org.apache.axis.providers.java.CORBAProvider(); } }
7,714
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDJavaMsgProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; /** * */ public class WSDDJavaMsgProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_MSG; } /** * */ public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { return new org.apache.axis.providers.java.MsgProvider(); } }
7,715
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDJavaEJBProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; /** * A WSDD EJB provider * * @author Glen Daniels (gdaniels@apache.org) */ public class WSDDJavaEJBProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_EJB; } /** * */ public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { return new org.apache.axis.providers.java.EJBProvider(); } }
7,716
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDJavaRPCProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.deployment.wsdd.providers; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDProvider; import org.apache.axis.deployment.wsdd.WSDDService; /** * */ public class WSDDJavaRPCProvider extends WSDDProvider { public String getName() { return WSDDConstants.PROVIDER_RPC; } /** * */ public Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception { return new org.apache.axis.providers.java.RPCProvider(); } }
7,717
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/Skeleton.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl; import java.io.Serializable; /** * Interface for WSDL2Java generated skeletons */ public interface Skeleton extends Serializable { }
7,718
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/SkeletonImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; import java.util.HashMap; /** * Provides Base function implementation for the Skeleton interface */ public class SkeletonImpl implements Skeleton { /** Field table */ private static HashMap table = null; /** * Constructor */ public SkeletonImpl() { if (table == null) { table = new HashMap(); } } /** * Class MetaInfo * * @version %I%, %G% */ class MetaInfo { /** Field names */ QName[] names; /** Field modes */ ParameterMode[] modes; /** Field inputNamespace */ String inputNamespace; /** Field outputNamespace */ String outputNamespace; /** Field soapAction */ String soapAction; /** * Constructor MetaInfo * * @param names * @param modes * @param inputNamespace * @param outputNamespace * @param soapAction */ MetaInfo(QName[] names, ParameterMode[] modes, String inputNamespace, String outputNamespace, String soapAction) { this.names = names; this.modes = modes; this.inputNamespace = inputNamespace; this.outputNamespace = outputNamespace; this.soapAction = soapAction; } } /** * Add operation name and vector containing return and parameter names. * The first name in the array is either the return name (which * should be set to null if there is no return name) * * @param operation * @param names * @param modes * @param inputNamespace * @param outputNamespace * @param soapAction */ public void add(String operation, QName[] names, ParameterMode[] modes, String inputNamespace, String outputNamespace, String soapAction) { table.put(operation, new MetaInfo(names, modes, inputNamespace, outputNamespace, soapAction)); } /** * Convenience method which allows passing an array of Strings which * will be converted into QNames with no namespace. * * @param operation * @param names * @param modes * @param inputNamespace * @param outputNamespace * @param soapAction */ public void add(String operation, String[] names, ParameterMode[] modes, String inputNamespace, String outputNamespace, String soapAction) { QName[] qnames = new QName[names.length]; for (int i = 0; i < names.length; i++) { QName qname = new QName(null, names[i]); qnames[i] = qname; } add(operation, qnames, modes, inputNamespace, outputNamespace, soapAction); } /** * Used to return the name of the n-th parameter of the specified * operation. Use -1 to get the return type name * Returns null if problems occur or the parameter is not known. * * @param operationName * @param n * @return */ public QName getParameterName(String operationName, int n) { MetaInfo value = (MetaInfo) table.get(operationName); if ((value == null) || (value.names == null) || (value.names.length <= n + 1)) { return null; } return value.names[n + 1]; } /** * Used to return the mode of the n-th parameter of the specified * operation. Use -1 to get the return mode. * Returns null if problems occur or the parameter is not known. * * @param operationName * @param n * @return */ public ParameterMode getParameterMode(String operationName, int n) { MetaInfo value = (MetaInfo) table.get(operationName); if ((value == null) || (value.modes == null) || (value.modes.length <= n + 1)) { return null; } return value.modes[n + 1]; } /** * Used to return the namespace of the input clause of the given * operation. Returns null if problems occur. * * @param operationName * @return */ public String getInputNamespace(String operationName) { MetaInfo value = (MetaInfo) table.get(operationName); if (value == null) { return null; } return value.inputNamespace; } /** * Used to return the namespace of the output clause of the given * operation. Returns null if problems occur. * * @param operationName * @return */ public String getOutputNamespace(String operationName) { MetaInfo value = (MetaInfo) table.get(operationName); if (value == null) { return null; } return value.outputNamespace; } /** * Used to return the SOAPAction of the given operation. * Returns null if problems occur. * * @param operationName * @return */ public String getSOAPAction(String operationName) { MetaInfo value = (MetaInfo) table.get(operationName); if (value == null) { return null; } return value.soapAction; } }
7,719
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/MessageEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.wsdl.Message; /** * This class represents a WSDL message. It simply encompasses the WSDL4J Message object so it can * reside in the SymbolTable. */ public class MessageEntry extends SymTabEntry { /** Field message */ private Message message; /** * Construct a MessageEntry from a WSDL4J Message object. * * @param message */ public MessageEntry(Message message) { super(message.getQName()); this.message = message; } // ctor /** * Get this entry's Message object. * * @return */ public Message getMessage() { return message; } // getMessage } // class MessageEntry
7,720
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Element.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This class represents a TypeEntry that is a type (complexType, simpleType, etc. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public abstract class Element extends TypeEntry { /** * Create an Element object for an xml construct that references a type that has * not been defined yet. Defer processing until refType is known. * * @param pqName * @param refType * @param pNode * @param dims */ protected Element(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName, refType, pNode, dims); } /** * Create a Element object for an xml construct that is not a base java type * * @param pqName * @param pNode */ protected Element(QName pqName, Node pNode) { super(pqName, pNode); } }
7,721
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/CollectionTE.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; /* * Common marker interface for CollectionType and CollectionElement */ /** * Interface CollectionTE * * @version %I%, %G% */ public interface CollectionTE { }
7,722
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Type.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This class represents a TypeEntry that is a type (complexType, simpleType, etc. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public abstract class Type extends TypeEntry { private boolean generated; // true if java class is generated during WSDL->Java processing /** * Create a Type object for an xml construct name that represents a base type * * @param pqName */ protected Type(QName pqName) { super(pqName); } /** * Create a TypeEntry object for an xml construct that references a type that has * not been defined yet. Defer processing until refType is known. * * @param pqName * @param refType * @param pNode * @param dims */ protected Type(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName, refType, pNode, dims); } /** * Create a Type object for an xml construct that is not a base type * * @param pqName * @param pNode */ protected Type(QName pqName, Node pNode) { super(pqName, pNode); } public void setGenerated(boolean b) { generated = b; } public boolean isGenerated() { return generated; } }
7,723
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/SymbolTable.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.utils.Messages; import org.apache.axis.utils.URLHashSet; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.wsdl.Binding; import javax.wsdl.BindingFault; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.BindingOutput; import javax.wsdl.Definition; import javax.wsdl.Fault; import javax.wsdl.Import; import javax.wsdl.Input; import javax.wsdl.Message; import javax.wsdl.Operation; import javax.wsdl.Output; import javax.wsdl.Part; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.wsdl.WSDLException; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.UnknownExtensibilityElement; import javax.wsdl.extensions.http.HTTPBinding; import javax.wsdl.extensions.mime.MIMEContent; import javax.wsdl.extensions.mime.MIMEMultipartRelated; import javax.wsdl.extensions.mime.MIMEPart; import javax.wsdl.extensions.soap.SOAPBinding; import javax.wsdl.extensions.soap.SOAPBody; import javax.wsdl.extensions.soap.SOAPFault; import javax.wsdl.extensions.soap.SOAPHeader; import javax.wsdl.extensions.soap.SOAPHeaderFault; import javax.wsdl.extensions.soap12.SOAP12Binding; import javax.wsdl.extensions.soap12.SOAP12Body; import javax.wsdl.extensions.soap12.SOAP12Fault; import javax.wsdl.extensions.soap12.SOAP12Header; import javax.wsdl.extensions.soap12.SOAP12HeaderFault; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; import javax.xml.rpc.holders.BooleanHolder; import javax.xml.rpc.holders.IntHolder; import javax.xml.rpc.holders.QNameHolder; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; /** * This class represents a table of all of the top-level symbols from a set of WSDL Definitions and * DOM Documents: XML types; WSDL messages, portTypes, bindings, and services. * <p> * This symbolTable contains entries of the form &lt;key, value&gt; where key is of type QName and value is * of type Vector. The Vector's elements are all of the objects that have the given QName. This is * necessary since names aren't unique among the WSDL types. message, portType, binding, service, * could all have the same QName and are differentiated merely by type. SymbolTable contains * type-specific getters to bypass the Vector layer: * public PortTypeEntry getPortTypeEntry(QName name), etc. */ public class SymbolTable { private static final Log log = LogFactory.getLog(SymbolTable.class.getName()); // used to cache dervied types protected HashMap derivedTypes = new HashMap(); // Should the contents of imported files be added to the symbol table? /** Field addImports */ private boolean addImports; // The actual symbol table. This symbolTable contains entries of the form // <key, value> where key is of type QName and value is of type Vector. The // Vector's elements are all of the objects that have the given QName. This // is necessary since names aren't unique among the WSDL types. message, // portType, binding, service, could all have the same QName and are // differentiated merely by type. SymbolTable contains type-specific // getters to bypass the Vector layer: // public PortTypeEntry getPortTypeEntry(QName name), etc. /** Field symbolTable */ private HashMap symbolTable = new HashMap(); // a map of qnames -> Elements in the symbol table /** Field elementTypeEntries */ private final Map elementTypeEntries = new HashMap(); // an unmodifiable wrapper so that we can share the index with others, safely /** Field elementIndex */ private final Map elementIndex = Collections.unmodifiableMap(elementTypeEntries); // a map of qnames -> Types in the symbol table /** Field typeTypeEntries */ private final Map typeTypeEntries = new HashMap(); // an unmodifiable wrapper so that we can share the index with others, safely /** Field typeIndex */ private final Map typeIndex = Collections.unmodifiableMap(typeTypeEntries); /** * cache of nodes -&gt; base types for complexTypes. The cache is * built on nodes because multiple TypeEntry objects may use the * same node. */ protected final Map node2ExtensionBase = new HashMap(); // allow friendly access /** Field verbose */ private boolean verbose; /** Field quiet */ protected boolean quiet; /** Field btm */ private BaseTypeMapping btm = null; // should we attempt to treat document/literal WSDL as "rpc-style" /** Field nowrap */ private boolean nowrap; // Did we encounter wraped mode WSDL /** Field wrapped */ private boolean wrapped = false; /** Field ANON_TOKEN */ public static final String ANON_TOKEN = ">"; /** Field def */ private Definition def = null; /** Field wsdlURI */ private String wsdlURI = null; private EntityResolver entityResolver; /** If this is false, we will "unwrap" literal arrays, generating a plan "String[]" instead * of "ArrayOfString" when encountering an element containing a single maxOccurs="unbounded" * inner element. */ private boolean wrapArrays; Set arrayTypeQNames = new HashSet(); /** Field elementFormDefaults */ private final Map elementFormDefaults = new HashMap(); /** * Construct a symbol table with the given Namespaces. * * @param btm * @param addImports * @param verbose * @param nowrap */ public SymbolTable(BaseTypeMapping btm, boolean addImports, boolean verbose, boolean nowrap) { this.btm = btm; this.addImports = addImports; this.verbose = verbose; this.nowrap = nowrap; } // ctor /** * Method isQuiet * * @return */ public boolean isQuiet() { return quiet; } /** * Method setQuiet * * @param quiet */ public void setQuiet(boolean quiet) { this.quiet = quiet; } /** * Get the raw symbol table HashMap. * * @return */ public HashMap getHashMap() { return symbolTable; } // getHashMap /** * Get the list of entries with the given QName. Since symbols can share QNames, this list is * necessary. This list will not contain any more than one element of any given SymTabEntry. * * @param qname * @return */ public Vector getSymbols(QName qname) { return (Vector) symbolTable.get(qname); } // get /** * Get the entry with the given QName of the given class. If it does not exist, return null. * * @param qname * @param cls * @return */ public SymTabEntry get(QName qname, Class cls) { Vector v = (Vector) symbolTable.get(qname); if (v == null) { return null; } else { for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (cls.isInstance(entry)) { return entry; } } return null; } } // get /** * Get the type entry for the given qname. * * @param qname * @param wantElementType boolean that indicates type or element (for type= or ref=) * @return */ public TypeEntry getTypeEntry(QName qname, boolean wantElementType) { if (wantElementType) { return getElement(qname); } else { return getType(qname); } } // getTypeEntry /** * Get the Type TypeEntry with the given QName. If it doesn't * exist, return null. * * @param qname * @return */ public Type getType(QName qname) { return (Type) typeTypeEntries.get(qname); } // getType /** * Get the Element TypeEntry with the given QName. If it doesn't * exist, return null. * * @param qname * @return */ public Element getElement(QName qname) { return (Element) elementTypeEntries.get(qname); } // getElement /** * Get the MessageEntry with the given QName. If it doesn't exist, return null. * * @param qname * @return */ public MessageEntry getMessageEntry(QName qname) { return (MessageEntry) get(qname, MessageEntry.class); } // getMessageEntry /** * Get the PortTypeEntry with the given QName. If it doesn't exist, return null. * * @param qname * @return */ public PortTypeEntry getPortTypeEntry(QName qname) { return (PortTypeEntry) get(qname, PortTypeEntry.class); } // getPortTypeEntry /** * Get the BindingEntry with the given QName. If it doesn't exist, return null. * * @param qname * @return */ public BindingEntry getBindingEntry(QName qname) { return (BindingEntry) get(qname, BindingEntry.class); } // getBindingEntry /** * Get the ServiceEntry with the given QName. If it doesn't exist, return null. * * @param qname * @return */ public ServiceEntry getServiceEntry(QName qname) { return (ServiceEntry) get(qname, ServiceEntry.class); } // getServiceEntry /** * Get the list of all the XML schema types in the symbol table. In other words, all entries * that are instances of TypeEntry. * * @return * @deprecated use specialized get{Element,Type}Index() methods instead */ public Vector getTypes() { Vector v = new Vector(); v.addAll(elementTypeEntries.values()); v.addAll(typeTypeEntries.values()); return v; } // getTypes /** * Return an unmodifiable map of qnames -&gt; Elements in the symbol * table. * * @return an unmodifiable <code>Map</code> value */ public Map getElementIndex() { return elementIndex; } /** * Return an unmodifiable map of qnames -&gt; Elements in the symbol * table. * * @return an unmodifiable <code>Map</code> value */ public Map getTypeIndex() { return typeIndex; } /** * Return the count of TypeEntries in the symbol table. * * @return an <code>int</code> value */ public int getTypeEntryCount() { return elementTypeEntries.size() + typeTypeEntries.size(); } /** * Get the Definition. The definition is null until * populate is called. * * @return */ public Definition getDefinition() { return def; } // getDefinition /** * Get the WSDL URI. The WSDL URI is null until populate * is called, and ONLY if a WSDL URI is provided. * * @return */ public String getWSDLURI() { return wsdlURI; } // getWSDLURI /** * Are we wrapping literal soap body elements. * * @return */ public boolean isWrapped() { return wrapped; } /** * Turn on/off element wrapping for literal soap body's. * * @param wrapped */ public void setWrapped(boolean wrapped) { this.wrapped = wrapped; } /** * Get the entity resolver. * * @return the entity resolver, or <code>null</code> if no entity resolver is configured */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Set the entity resolver. This is used to load the WSDL file (unless it is supplied as a * {@link Document}) and all imported WSDL and schema documents. * * @param entityResolver * the entity resolver, or <code>null</code> to use a default entity resolver */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * Dump the contents of the symbol table. For debugging purposes only. * * @param out */ public void dump(java.io.PrintStream out) { out.println(); out.println(Messages.getMessage("symbolTable00")); out.println("-----------------------"); Iterator it = symbolTable.values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { out.println(v.elementAt(i).getClass().getName()); out.println(v.elementAt(i)); } } out.println("-----------------------"); } // dump /** * Call this method if you have a uri for the WSDL document * * @param uri wsdlURI the location of the WSDL file. * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void populate(String uri) throws IOException, WSDLException, SAXException, ParserConfigurationException { populate(uri, null, null); } // populate /** * Method populate * * @param uri * @param username * @param password * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void populate(String uri, String username, String password) throws IOException, WSDLException, SAXException, ParserConfigurationException { if (verbose) { System.out.println(Messages.getMessage("parsing00", uri)); } Document doc = XMLUtils.newDocument(uri, username, password); this.wsdlURI = uri; try { File f = new File(uri); if (f.exists()) { uri = f.toURL().toString(); } } catch (Exception e) { } populate(uri, doc); } // populate /** * Call this method if your WSDL document has already been parsed as an XML DOM document. * * @param context context This is directory context for the Document. If the Document were from file "/x/y/z.wsdl" then the context could be "/x/y" (even "/x/y/z.wsdl" would work). If context is null, then the context becomes the current directory. * @param doc doc This is the XML Document containing the WSDL. * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException */ public void populate(String context, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); reader.setFeature("javax.wsdl.verbose", verbose); this.def = reader.readWSDL(new WSDLLocatorAdapter(context, entityResolver != null ? entityResolver : NullEntityResolver.INSTANCE), doc.getDocumentElement()); add(context, def, doc); } // populate /** * Add the given Definition and Document information to the symbol table (including imported * symbols), populating it with SymTabEntries for each of the top-level symbols. When the * symbol table has been populated, iterate through it, setting the isReferenced flag * appropriately for each entry. * * @param context * @param def * @param doc * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException */ protected void add(String context, Definition def, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { URL contextURL = (context == null) ? null : getURL(null, context); populate(contextURL, def, doc, null); processTypes(); checkForUndefined(); populateParameters(); setReferences(def, doc); // uses wrapped flag set in populateParameters } // add /** * Scan the Definition for undefined objects and throw an error. * * @param def * @param filename * @throws IOException */ private void checkForUndefined(Definition def, String filename) throws IOException { if (def != null) { // Bindings Iterator ib = def.getBindings().values().iterator(); while (ib.hasNext()) { Binding binding = (Binding) ib.next(); if (binding.isUndefined()) { if (filename == null) { throw new IOException( Messages.getMessage( "emitFailtUndefinedBinding01", binding.getQName().getLocalPart())); } else { throw new IOException( Messages.getMessage( "emitFailtUndefinedBinding02", binding.getQName().getLocalPart(), filename)); } } } // portTypes Iterator ip = def.getPortTypes().values().iterator(); while (ip.hasNext()) { PortType portType = (PortType) ip.next(); if (portType.isUndefined()) { if (filename == null) { throw new IOException( Messages.getMessage( "emitFailtUndefinedPort01", portType.getQName().getLocalPart())); } else { throw new IOException( Messages.getMessage( "emitFailtUndefinedPort02", portType.getQName().getLocalPart(), filename)); } } } /* * tomj: This is a bad idea, faults seem to be undefined * / RJB reply: this MUST be done for those systems that do something with * / messages. Perhaps we have to do an extra step for faults? I'll leave * / this commented for now, until someone uses this generator for something * / other than WSDL2Java. * // Messages * Iterator i = def.getMessages().values().iterator(); * while (i.hasNext()) { * Message message = (Message) i.next(); * if (message.isUndefined()) { * throw new IOException( * Messages.getMessage("emitFailtUndefinedMessage01", * message.getQName().getLocalPart())); * } * } */ } } /** * Scan the symbol table for undefined types and throw an exception. * * @throws IOException */ private void checkForUndefined() throws IOException { Iterator it = symbolTable.values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.get(i); // Report undefined types if (entry instanceof UndefinedType) { QName qn = entry.getQName(); // Special case dateTime/timeInstant that changed // from version to version. if ((qn.getLocalPart().equals( "dateTime") && !qn.getNamespaceURI().equals( Constants.URI_2001_SCHEMA_XSD)) || (qn.getLocalPart().equals( "timeInstant") && qn.getNamespaceURI().equals( Constants.URI_2001_SCHEMA_XSD))) { throw new IOException( Messages.getMessage( "wrongNamespace00", qn.getLocalPart(), qn.getNamespaceURI())); } // Check for a undefined XSD Schema Type and throw // an unsupported message instead of undefined if (SchemaUtils.isSimpleSchemaType(qn)) { throw new IOException( Messages.getMessage( "unsupportedSchemaType00", qn.getLocalPart())); } // last case, its some other undefined thing throw new IOException( Messages.getMessage( "undefined00", qn.toString())); } // if undefined else if (entry instanceof UndefinedElement) { throw new IOException( Messages.getMessage( "undefinedElem00", entry.getQName().toString())); } } } } // checkForUndefined private Document newDocument(String systemId) throws SAXException, IOException, ParserConfigurationException { InputSource is = null; if (entityResolver != null) { is = entityResolver.resolveEntity(null, systemId); } if (is == null) { is = new InputSource(systemId); } return XMLUtils.newDocument(is); } /** * Add the given Definition and Document information to the symbol table (including imported * symbols), populating it with SymTabEntries for each of the top-level symbols. * NOTE: filename is used only by checkForUndefined so that it can report which WSDL file * has the problem. If we're on the primary WSDL file, then we don't know the name and * filename will be null. But we know the names of all imported files. */ private URLHashSet importedFiles = new URLHashSet(); /** * Method populate * * @param context * @param def * @param doc * @param filename * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws WSDLException */ private void populate( URL context, Definition def, Document doc, String filename) throws IOException, ParserConfigurationException, SAXException, WSDLException { if (doc != null) { populateTypes(context, doc); if (addImports) { // Add the symbols from any xsd:import'ed documents. lookForImports(context, doc); } } if (def != null) { checkForUndefined(def, filename); if (addImports) { // Add the symbols from the wsdl:import'ed WSDL documents Map imports = def.getImports(); Object[] importKeys = imports.keySet().toArray(); for (int i = 0; i < importKeys.length; ++i) { Vector v = (Vector) imports.get(importKeys[i]); for (int j = 0; j < v.size(); ++j) { Import imp = (Import) v.get(j); if (!importedFiles.contains(imp.getLocationURI())) { importedFiles.add(imp.getLocationURI()); URL url = getURL(context, imp.getLocationURI()); populate(url, imp.getDefinition(), newDocument(url.toString()), url.toString()); } } } } populateMessages(def); populatePortTypes(def); populateBindings(def); populateServices(def); } } // populate /** * This is essentially a call to "new URL(contextURL, spec)" with extra handling in case spec is * a file. * * @param contextURL * @param spec * @return * @throws IOException */ private static URL getURL(URL contextURL, String spec) throws IOException { // First, fix the slashes as windows filenames may have backslashes // in them, but the URL class wont do the right thing when we later // process this URL as the contextURL. String path = spec.replace('\\', '/'); // See if we have a good URL. URL url = null; try { // first, try to treat spec as a full URL url = new URL(contextURL, path); // if we are deail with files in both cases, create a url // by using the directory of the context URL. if ((contextURL != null) && url.getProtocol().equals("file") && contextURL.getProtocol().equals("file")) { url = getFileURL(contextURL, path); } } catch (MalformedURLException me) { // try treating is as a file pathname url = getFileURL(contextURL, path); } // Everything is OK with this URL, although a file url constructed // above may not exist. This will be caught later when the URL is // accessed. return url; } // getURL /** * Method getFileURL * * @param contextURL * @param path * @return * @throws IOException */ private static URL getFileURL(URL contextURL, String path) throws IOException { if (contextURL != null) { // get the parent directory of the contextURL, and append // the spec string to the end. String contextFileName = contextURL.getFile(); URL parent = null; File parentFile = new File(contextFileName).getParentFile(); if ( parentFile != null ) { parent = parentFile.toURL(); } if (parent != null) { return new URL(parent, path); } } return new URL("file", "", path); } // getFileURL /** * Recursively find all xsd:import'ed objects and call populate for each one. * * @param context * @param node * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws WSDLException */ private void lookForImports(URL context, Node node) throws IOException, ParserConfigurationException, SAXException, WSDLException { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("import".equals(child.getLocalName())) { NamedNodeMap attributes = child.getAttributes(); Node namespace = attributes.getNamedItem("namespace"); // skip XSD import of soap encoding if ((namespace != null) && isKnownNamespace(namespace.getNodeValue())) { continue; } Node importFile = attributes.getNamedItem("schemaLocation"); if (importFile != null) { URL url = getURL(context, importFile.getNodeValue()); if (!importedFiles.contains(url)) { importedFiles.add(url); String filename = url.toString(); populate(url, null, newDocument(filename), filename); } } } lookForImports(context, child); } } // lookForImports /** * Check if this is a known namespace (soap-enc or schema xsd or schema xsi or xml) * * @param namespace * @return true if this is a know namespace. */ public boolean isKnownNamespace(String namespace) { if (Constants.isSOAP_ENC(namespace)) { return true; } if (Constants.isSchemaXSD(namespace)) { return true; } if (Constants.isSchemaXSI(namespace)) { return true; } if (namespace.equals(Constants.NS_URI_XML)) { return true; } return false; } /** * Populate the symbol table with all of the Types from the Document. * * @param context * @param doc * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException */ public void populateTypes(URL context, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { addTypes(context, doc, ABOVE_SCHEMA_LEVEL); } // populateTypes /** * Utility method which walks the Document and creates Type objects for * each complexType, simpleType, attributeGroup or element referenced or defined. * <p/> * What goes into the symbol table? In general, only the top-level types * (ie., those just below * the schema tag). But base types and references can * appear below the top level. So anything * at the top level is added to the symbol table, * plus non-Element types (ie, base and refd) * that appear deep within other types. */ private static final int ABOVE_SCHEMA_LEVEL = -1; /** Field SCHEMA_LEVEL */ private static final int SCHEMA_LEVEL = 0; /** * Method addTypes * * @param context * @param node * @param level * @throws IOException * @throws ParserConfigurationException * @throws WSDLException * @throws SAXException */ private void addTypes(URL context, Node node, int level) throws IOException, ParserConfigurationException, WSDLException, SAXException { if (node == null) { return; } // Get the kind of node (complexType, wsdl:part, etc.) String localPart = node.getLocalName(); if (localPart != null) { boolean isXSD = Constants.isSchemaXSD(node.getNamespaceURI()); if (((isXSD && localPart.equals("complexType")) || localPart.equals("simpleType"))) { // If an extension or restriction is present, // create a type for the reference Node re = SchemaUtils.getRestrictionOrExtensionNode(node); if ((re != null) && (Utils.getAttribute(re, "base") != null)) { createTypeFromRef(re); } Node list = SchemaUtils.getListNode(node); if (list != null && Utils.getAttribute(list,"itemType") != null) { createTypeFromRef(list); } Node union = SchemaUtils.getUnionNode(node); if (union != null) { QName [] memberTypes = Utils.getMemberTypeQNames(union); if (memberTypes != null) { for (int i=0;i<memberTypes.length;i++) { if (SchemaUtils.isSimpleSchemaType(memberTypes[i]) && getType(memberTypes[i]) == null) { symbolTablePut(new BaseType(memberTypes[i])); } } } } // This is a definition of a complex type. // Create a Type. createTypeFromDef(node, false, false); } else if (isXSD && localPart.equals("element")) { // Create a type entry for the referenced type createTypeFromRef(node); // If an extension or restriction is present, // create a type for the reference Node re = SchemaUtils.getRestrictionOrExtensionNode(node); if ((re != null) && (Utils.getAttribute(re, "base") != null)) { createTypeFromRef(re); } // Create a type representing an element. (This may // seem like overkill, but is necessary to support ref= // and element=. createTypeFromDef(node, true, level > SCHEMA_LEVEL); } else if (isXSD && localPart.equals("attributeGroup")) { // bug 23145: support attributeGroup (Brook Richan) // Create a type entry for the referenced type createTypeFromRef(node); // Create a type representing an attributeGroup. createTypeFromDef(node, false, level > SCHEMA_LEVEL); } else if (isXSD && localPart.equals("group")) { // Create a type entry for the referenced type createTypeFromRef(node); // Create a type representing an group createTypeFromDef(node, false, level > SCHEMA_LEVEL); } else if (isXSD && localPart.equals("attribute")) { // Create a type entry for the referenced type BooleanHolder forElement = new BooleanHolder(); QName refQName = Utils.getTypeQName(node, forElement, false); if ((refQName != null) && !forElement.value) { createTypeFromRef(node); // Get the symbol table entry and make sure it is a simple // type if (refQName != null) { TypeEntry refType = getTypeEntry(refQName, false); if ((refType != null) && (refType instanceof Undefined)) { // Don't know what the type is. // It better be simple so set it as simple refType.setSimpleType(true); } else if ((refType == null) || (!(refType instanceof BaseType) && !refType.isSimpleType())) { // Problem if not simple throw new IOException( Messages.getMessage( "AttrNotSimpleType01", refQName.toString())); } } } createTypeFromDef(node, true, level > SCHEMA_LEVEL); } else if (isXSD && localPart.equals("any")) { // Map xsd:any element to special xsd:any "type" if (getType(Constants.XSD_ANY) == null) { Type type = new BaseType(Constants.XSD_ANY); symbolTablePut(type); } } else if (localPart.equals("part") && Constants.isWSDL(node.getNamespaceURI())) { // This is a wsdl part. Create an TypeEntry representing the reference createTypeFromRef(node); } else if (isXSD && localPart.equals("include")) { String includeName = Utils.getAttribute(node, "schemaLocation"); if (includeName != null) { URL url = getURL(context, includeName); Document includeDoc = newDocument(url.toString()); // Vidyanand : Fix for Bug #15124 org.w3c.dom.Element schemaEl = includeDoc.getDocumentElement(); if (!schemaEl.hasAttribute("targetNamespace")) { org.w3c.dom.Element parentSchemaEl = (org.w3c.dom.Element) node.getParentNode(); if (parentSchemaEl.hasAttribute("targetNamespace")) { // we need to set two things in here // 1. targetNamespace // 2. setup the xmlns=<targetNamespace> attribute String tns = parentSchemaEl.getAttribute("targetNamespace"); schemaEl.setAttribute("targetNamespace", tns); schemaEl.setAttribute("xmlns", tns); } } populate(url, null, includeDoc, url.toString()); } } } if (level == ABOVE_SCHEMA_LEVEL) { if ((localPart != null) && localPart.equals("schema")) { level = SCHEMA_LEVEL; String targetNamespace = ((org.w3c.dom.Element) node).getAttribute("targetNamespace"); String elementFormDefault = ((org.w3c.dom.Element) node).getAttribute("elementFormDefault"); if (targetNamespace != null && targetNamespace.length() > 0) { elementFormDefault = (elementFormDefault == null || elementFormDefault.length() == 0) ? "unqualified" : elementFormDefault; if(elementFormDefaults.get(targetNamespace)==null) { elementFormDefaults.put(targetNamespace, elementFormDefault); } } } } else { ++level; } // Recurse through children nodes NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { addTypes(context, children.item(i), level); } } // addTypes /** * Create a TypeEntry from the indicated node, which defines a type * that represents a complexType, simpleType or element (for ref=). * * @param node * @param isElement * @param belowSchemaLevel * @throws IOException */ private void createTypeFromDef( Node node, boolean isElement, boolean belowSchemaLevel) throws IOException { // Get the QName of the node's name attribute value QName qName = Utils.getNodeNameQName(node); if (qName != null) { // If the qname is already registered as a base type, // don't create a defining type/element. if (!isElement && (btm.getBaseName(qName) != null)) { return; } // If the node has a type or ref attribute, get the // qname representing the type BooleanHolder forElement = new BooleanHolder(); QName refQName = Utils.getTypeQName(node, forElement, false); if (refQName != null) { // Error check - bug 12362 if (qName.getLocalPart().length() == 0) { String name = Utils.getAttribute(node, "name"); if (name == null) { name = "unknown"; } throw new IOException(Messages.getMessage("emptyref00", name)); } // Now get the TypeEntry TypeEntry refType = getTypeEntry(refQName, forElement.value); if (!belowSchemaLevel) { if (refType == null) { throw new IOException( Messages.getMessage( "absentRef00", refQName.toString(), qName.toString())); } symbolTablePut(new DefinedElement(qName, refType, node, "")); } } else { // Flow to here indicates no type= or ref= attribute. // See if this is an array or simple type definition. IntHolder numDims = new IntHolder(); BooleanHolder underlTypeNillable = new BooleanHolder(); // If we're supposed to unwrap arrays, supply someplace to put the "inner" QName // so we can propagate it into the appropriate metadata container. QNameHolder itemQName = wrapArrays ? null : new QNameHolder(); BooleanHolder forElement2 = new BooleanHolder(); numDims.value = 0; QName arrayEQName = SchemaUtils.getArrayComponentQName(node, numDims, underlTypeNillable, itemQName, forElement2, this); if (arrayEQName != null) { // Get the TypeEntry for the array element type refQName = arrayEQName; TypeEntry refType = getTypeEntry(refQName, forElement2.value); if (refType == null) { // arrayTypeQNames.add(refQName); // Not defined yet, add one String baseName = btm.getBaseName(refQName); if (baseName != null) { refType = new BaseType(refQName); } else if(forElement2.value) { refType = new UndefinedElement(refQName); } else { refType = new UndefinedType(refQName); } symbolTablePut(refType); } // Create a defined type or element that references refType String dims = ""; while (numDims.value > 0) { dims += "[]"; numDims.value--; } TypeEntry defType = null; if (isElement) { if (!belowSchemaLevel) { defType = new DefinedElement(qName, refType, node, dims); // Save component type for ArraySerializer defType.setComponentType(arrayEQName); if (itemQName != null) defType.setItemQName(itemQName.value); } } else { defType = new DefinedType(qName, refType, node, dims); // Save component type for ArraySerializer defType.setComponentType(arrayEQName); defType.setUnderlTypeNillable(underlTypeNillable.value); if (itemQName != null) defType.setItemQName(itemQName.value); } if (defType != null) { symbolTablePut(defType); } } else { // Create a TypeEntry representing this type/element String baseName = btm.getBaseName(qName); if (baseName != null) { symbolTablePut(new BaseType(qName)); } else { // Create a type entry, set whether it should // be mapped as a simple type, and put it in the // symbol table. TypeEntry te = null; TypeEntry parentType = null; if (!isElement) { te = new DefinedType(qName, node); // check if we are an anonymous type underneath // an element. If so, we point the refType of the // element to us (the real type). if (qName.getLocalPart().indexOf(ANON_TOKEN) >= 0) { Node parent = node.getParentNode(); QName parentQName = Utils.getNodeNameQName(parent); parentType = getElement(parentQName); } } else { if (!belowSchemaLevel) { te = new DefinedElement(qName, node); } } if (te != null) { if (SchemaUtils.isSimpleTypeOrSimpleContent(node)) { te.setSimpleType(true); } te = (TypeEntry)symbolTablePut(te); if (parentType != null) { parentType.setRefType(te); } } } } } } } // createTypeFromDef /** * Node may contain a reference (via type=, ref=, or element= attributes) to * another type. Create a Type object representing this referenced type. * * @param node * @throws IOException */ protected void createTypeFromRef(Node node) throws IOException { // Get the QName of the node's type attribute value BooleanHolder forElement = new BooleanHolder(); QName qName = Utils.getTypeQName(node, forElement, false); if (qName == null || (Constants.isSchemaXSD(qName.getNamespaceURI()) && qName.getLocalPart().equals("simpleRestrictionModel"))) { return; } // Error check - bug 12362 if (qName.getLocalPart().length() == 0) { String name = Utils.getAttribute(node, "name"); if (name == null) { name = "unknown"; } throw new IOException(Messages.getMessage("emptyref00", name)); } // Get Type or Element depending on whether type attr was used. TypeEntry type = getTypeEntry(qName, forElement.value); // A symbol table entry is created if the TypeEntry is not found if (type == null) { // See if this is a special QName for collections if (qName.getLocalPart().indexOf("[") > 0) { QName containedQName = Utils.getTypeQName(node, forElement, true); TypeEntry containedTE = getTypeEntry(containedQName, forElement.value); if (!forElement.value) { // Case of type and maxOccurs if (containedTE == null) { // Collection Element Type not defined yet, add one. String baseName = btm.getBaseName(containedQName); if (baseName != null) { containedTE = new BaseType(containedQName); } else { containedTE = new UndefinedType(containedQName); } symbolTablePut(containedTE); } boolean wrapped = qName.getLocalPart().endsWith("wrapped"); symbolTablePut(new CollectionType(qName, containedTE, node, "[]", wrapped)); } else { // Case of ref and maxOccurs if (containedTE == null) { containedTE = new UndefinedElement(containedQName); symbolTablePut(containedTE); } symbolTablePut(new CollectionElement(qName, containedTE, node, "[]")); } } else { // Add a BaseType or Undefined Type/Element String baseName = btm.getBaseName(qName); if (baseName != null) { symbolTablePut(new BaseType(qName)); // bugzilla 23145: handle attribute groups // soap/encoding is treated as a "known" schema // so now let's act like we know it } else if (qName.equals(Constants.SOAP_COMMON_ATTRS11)) { symbolTablePut(new BaseType(qName)); // the 1.1 commonAttributes type contains two attributes // make sure those attributes' types are in the symbol table // attribute name = "id" type = "xsd:ID" if (getTypeEntry(Constants.XSD_ID, false) == null) { symbolTablePut(new BaseType(Constants.XSD_ID)); } // attribute name = "href" type = "xsd:anyURI" if (getTypeEntry(Constants.XSD_ANYURI, false) == null) { symbolTablePut(new BaseType(Constants.XSD_ANYURI)); } } else if (qName.equals(Constants.SOAP_COMMON_ATTRS12)) { symbolTablePut(new BaseType(qName)); // the 1.2 commonAttributes type contains one attribute // make sure the attribute's type is in the symbol table // attribute name = "id" type = "xsd:ID" if (getTypeEntry(Constants.XSD_ID, false) == null) { symbolTablePut(new BaseType(Constants.XSD_ID)); } } else if (qName.equals(Constants.SOAP_ARRAY_ATTRS11)) { symbolTablePut(new BaseType(qName)); // the 1.1 arrayAttributes type contains two attributes // make sure the attributes' types are in the symbol table // attribute name = "arrayType" type = "xsd:string" if (getTypeEntry(Constants.XSD_STRING, false) == null) { symbolTablePut(new BaseType(Constants.XSD_STRING)); } // attribute name = "offset" type = "soapenc:arrayCoordinate" // which is really an xsd:string } else if (qName.equals(Constants.SOAP_ARRAY_ATTRS12)) { symbolTablePut(new BaseType(qName)); // the 1.2 arrayAttributes type contains two attributes // make sure the attributes' types are in the symbol table // attribute name = "arraySize" type = "2003soapenc:arraySize" // which is really a hairy beast that is not // supported, yet; so let's just use string if (getTypeEntry(Constants.XSD_STRING, false) == null) { symbolTablePut(new BaseType(Constants.XSD_STRING)); } // attribute name = "itemType" type = "xsd:QName" if (getTypeEntry(Constants.XSD_QNAME, false) == null) { symbolTablePut(new BaseType(Constants.XSD_QNAME)); } } else if (forElement.value == false) { symbolTablePut(new UndefinedType(qName)); } else { symbolTablePut(new UndefinedElement(qName)); } } } } // createTypeFromRef /** * Populate the symbol table with all of the MessageEntry's from the Definition. * * @param def * @throws IOException */ private void populateMessages(Definition def) throws IOException { Iterator i = def.getMessages().values().iterator(); while (i.hasNext()) { Message message = (Message) i.next(); MessageEntry mEntry = new MessageEntry(message); symbolTablePut(mEntry); } } // populateMessages /** * ensures that a message in a <code>&lt;input&gt;</code>, <code>&lt;output&gt;</code>, * or <code>&lt;fault&gt;</code> element in an <code>&lt;operation&gt;</code> * element is valid. In particular, ensures that * <ol> * <li>an attribute <code>message</code> is present (according to the * XML Schema for WSDL 1.1 <code>message</code> is <strong>required</strong> * <p> * <li>the value of attribute <code>message</code> (a QName) refers to * an already defined message * </ol> * <p> * <strong>Note</strong>: this method should throw a <code>javax.wsdl.WSDLException</code> rather than * a <code>java.io.IOException</code> * * @param message the message object * @throws IOException thrown, if the message is not valid */ protected void ensureOperationMessageValid(Message message) throws IOException { // make sure the message is not null (i.e. there is an // attribute 'message ') // if (message == null) { throw new IOException( "<input>,<output>, or <fault> in <operation ..> without attribute 'message' found. Attribute 'message' is required."); } // make sure the value of the attribute refers to an // already defined message // if (message.isUndefined()) { throw new IOException( "<input ..>, <output ..> or <fault ..> in <portType> with undefined message found. message name is '" + message.getQName().toString() + "'"); } } /** * ensures that an an element <code>&lt;operation&gt;</code> within * an element <code>&lt;portType&gt;</code> is valid. Throws an exception * if the operation is not valid. * <p> * <strong>Note</strong>: this method should throw a <code>javax.wsdl.WSDLException</code> * rather than a <code>java.io.IOException</code> * * @param operation the operation element * @throws IOException thrown, if the element is not valid. * @throws IllegalArgumentException thrown, if operation is null */ protected void ensureOperationValid(Operation operation) throws IOException { if (operation == null) { throw new IllegalArgumentException( "parameter 'operation' must not be null"); } Input input = operation.getInput(); Message message; if (input != null) { message = input.getMessage(); if (message == null) { throw new IOException( "No 'message' attribute in <input> for operation '" + operation.getName() + "'"); } ensureOperationMessageValid(message); } Output output = operation.getOutput(); if (output != null) { message = output.getMessage(); if (message == null) { throw new IOException( "No 'message' attribute in <output> for operation '" + operation.getName() + "'"); } ensureOperationMessageValid(output.getMessage()); } Map faults = operation.getFaults(); if (faults != null) { Iterator it = faults.values().iterator(); while (it.hasNext()) { Fault fault = (Fault)it.next(); message = fault.getMessage(); if (message == null) { throw new IOException( "No 'message' attribute in <fault> named '" + fault.getName() + "' for operation '" + operation.getName() + "'"); } ensureOperationMessageValid(message); } } } /** * ensures that an an element <code>&lt;portType&gt;</code> * is valid. Throws an exception if the portType is not valid. * <p> * <strong>Note</strong>: this method should throw a <code>javax.wsdl.WSDLException</code> * rather than a <code>java.io.IOException</code> * * @param portType the portType element * @throws IOException thrown, if the element is not valid. * @throws IllegalArgumentException thrown, if operation is null */ protected void ensureOperationsOfPortTypeValid(PortType portType) throws IOException { if (portType == null) { throw new IllegalArgumentException( "parameter 'portType' must not be null"); } List operations = portType.getOperations(); // no operations defined ? -> valid according to the WSDL 1.1 schema // if ((operations == null) || (operations.size() == 0)) { return; } // check operations defined in this portType // Iterator it = operations.iterator(); while (it.hasNext()) { Operation operation = (Operation) it.next(); ensureOperationValid(operation); } } /** * Populate the symbol table with all of the PortTypeEntry's from the Definition. * * @param def * @throws IOException */ private void populatePortTypes(Definition def) throws IOException { Iterator i = def.getPortTypes().values().iterator(); while (i.hasNext()) { PortType portType = (PortType) i.next(); if (log.isDebugEnabled()) { log.debug("Processing port type " + portType.getQName()); } // If the portType is undefined, then we're parsing a Definition // that didn't contain a portType, merely a binding that referred // to a non-existent port type. Don't bother with it. if (!portType.isUndefined()) { ensureOperationsOfPortTypeValid(portType); PortTypeEntry ptEntry = new PortTypeEntry(portType); symbolTablePut(ptEntry); } } } // populatePortTypes /** * Create the parameters and store them in the bindingEntry. * * @throws IOException */ private void populateParameters() throws IOException { Iterator it = symbolTable.values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { if (v.get(i) instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) v.get(i); // Skip non-soap bindings if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } Binding binding = bEntry.getBinding(); Collection bindOperations = bEntry.getOperations(); PortType portType = binding.getPortType(); HashMap parameters = new HashMap(); Iterator operations = portType.getOperations().iterator(); // get parameters while (operations.hasNext()) { Operation operation = (Operation) operations.next(); // See if the PortType operation has a corresponding // Binding operation and report an error if it doesn't. if (!bindOperations.contains(operation)) { throw new IOException( Messages.getMessage( "emitFailNoMatchingBindOperation01", operation.getName(), portType.getQName().getLocalPart())); } if (log.isDebugEnabled()) { log.debug("Processing operation " + operation.getName()); } String namespace = portType.getQName().getNamespaceURI(); Parameters parms = getOperationParameters(operation, namespace, bEntry); parameters.put(operation, parms); } bEntry.setParameters(parameters); } } } } // populateParameters /** * For the given operation, this method returns the parameter info conveniently collated. * There is a bit of processing that is needed to write the interface, stub, and skeleton. * Rather than do that processing 3 times, it is done once, here, and stored in the * Parameters object. * * @param operation * @param namespace * @param bindingEntry * @return * @throws IOException */ public Parameters getOperationParameters( Operation operation, String namespace, BindingEntry bindingEntry) throws IOException { Parameters parameters = new Parameters(); // The input and output Vectors of Parameters Vector inputs = new Vector(); Vector outputs = new Vector(); List parameterOrder = operation.getParameterOrdering(); // Handle parameterOrder="", which is techinically illegal if ((parameterOrder != null) && parameterOrder.isEmpty()) { parameterOrder = null; } Input input = operation.getInput(); Output output = operation.getOutput(); parameters.mep = operation.getStyle(); // All input parts MUST be in the parameterOrder list. It is an error otherwise. if (parameterOrder != null && !wrapped) { if (input != null) { Message inputMsg = input.getMessage(); Map allInputs = inputMsg.getParts(); Collection orderedInputs = inputMsg.getOrderedParts(parameterOrder); if (allInputs.size() != orderedInputs.size()) { throw new IOException( Messages.getMessage("emitFail00", operation.getName())); } } } boolean literalInput = false; boolean literalOutput = false; if (bindingEntry != null) { literalInput = (bindingEntry.getInputBodyType(operation) == Use.LITERAL); literalOutput = (bindingEntry.getOutputBodyType(operation) == Use.LITERAL); } // Collect all the input parameters if ((input != null) && (input.getMessage() != null)) { getParametersFromParts(inputs, input.getMessage().getOrderedParts(null), literalInput, operation.getName(), bindingEntry); } // Collect all the output parameters if ((output != null) && (output.getMessage() != null)) { getParametersFromParts(outputs, output.getMessage().getOrderedParts(null), literalOutput, operation.getName(), bindingEntry); } if (parameterOrder != null && !wrapped) { // Construct a list of the parameters in the parameterOrder list, determining the // mode of each parameter and preserving the parameterOrder list. for (int i = 0; i < parameterOrder.size(); ++i) { String name = (String) parameterOrder.get(i); // index in the inputs Vector of the given name, -1 if it doesn't exist. int index = getPartIndex(name, inputs); // index in the outputs Vector of the given name, -1 if it doesn't exist. int outdex = getPartIndex(name, outputs); if (index >= 0) { // The mode of this parameter is either in or inout addInishParm(inputs, outputs, index, outdex, parameters, true); } else if (outdex >= 0) { addOutParm(outputs, outdex, parameters, true); } else { System.err.println(Messages.getMessage("noPart00", name)); } } } // Some special case logic for JAX-RPC, but also to make things // nicer for the user. // If we have a single input and output with the same name // instead of: void echo(StringHolder inout) // Do this: string echo(string in) if (wrapped && (inputs.size() == 1) && (outputs.size() == 1) && Utils.getLastLocalPart(((Parameter) inputs.get(0)).getName()).equals( Utils.getLastLocalPart(((Parameter) outputs.get(0)).getName())) ) { // add the input and make sure its a IN not an INOUT addInishParm(inputs, null, 0, -1, parameters, false); } else { // Get the mode info about those parts that aren't in the // parameterOrder list. Since they're not in the parameterOrder list, // the order is, first all in (and inout) parameters, then all out // parameters, in the order they appear in the messages. for (int i = 0; i < inputs.size(); i++) { Parameter p = (Parameter) inputs.get(i); int outdex = getPartIndex(p.getName(), outputs); addInishParm(inputs, outputs, i, outdex, parameters, false); } } // Now that the remaining in and inout parameters are collected, // determine the status of outputs. If there is only 1, then it // is the return value. If there are more than 1, then they are // out parameters. if (outputs.size() == 1) { parameters.returnParam = (Parameter) outputs.get(0); parameters.returnParam.setMode(Parameter.OUT); if (parameters.returnParam.getType() instanceof DefinedElement) { parameters.returnParam.setQName( parameters.returnParam.getType().getQName()); } ++parameters.outputs; } else { for (int i = 0; i < outputs.size(); i++) { addOutParm(outputs, i, parameters, false); } } parameters.faults = operation.getFaults(); // before we return the paramters, // make sure we dont have a duplicate name Vector used = new Vector(parameters.list.size()); Iterator i = parameters.list.iterator(); while (i.hasNext()) { Parameter parameter = (Parameter) i.next(); int count = 2; while (used.contains(parameter.getName())) { // duplicate, add a suffix and try again parameter.setName(parameter.getName() + Integer.toString(count++)); } used.add(parameter.getName()); } return parameters; } // parameters /** * Return the index of the given name in the given Vector, -1 if it doesn't exist. * * @param name * @param v * @return */ private int getPartIndex(String name, Vector v) { name = Utils.getLastLocalPart(name); for (int i = 0; i < v.size(); i++) { String paramName = ((Parameter) v.get(i)).getName(); paramName = Utils.getLastLocalPart(paramName); if (name.equals(paramName)) { return i; } } return -1; } // getPartIndex /** * Add an in or inout parameter to the parameters object. * * @param inputs * @param outputs * @param index * @param outdex * @param parameters * @param trimInput */ private void addInishParm(Vector inputs, Vector outputs, int index, int outdex, Parameters parameters, boolean trimInput) { Parameter p = (Parameter) inputs.get(index); // If this is an element, we want the XML to reflect the element name // not the part name. Same check is made in addOutParam below. if (p.getType() instanceof DefinedElement) { DefinedElement de = (DefinedElement) p.getType(); p.setQName(de.getQName()); } // If this is a collection we want the XML to reflect the type in // the collection, not foo[unbounded]. // Same check is made in addOutParam below. if (p.getType() instanceof CollectionElement) { p.setQName(p.getType().getRefType().getQName()); } // Should we remove the given parameter type/name entries from the Vector? if (trimInput) { inputs.remove(index); } // At this point we know the name and type of the parameter, and that it's at least an // in parameter. Now check to see whether it's also in the outputs Vector. If it is, // then it's an inout parameter. if (outdex >= 0) { Parameter outParam = (Parameter) outputs.get(outdex); TypeEntry paramEntry = p.getType(); TypeEntry outParamEntry = outParam.getType(); // String paramLastLocalPart = Utils.getLastLocalPart(paramEntry.getQName().getLocalPart()); // String outParamLastLocalPart = Utils.getLastLocalPart(outParamEntry.getQName().getLocalPart()); if (paramEntry.equals(outParamEntry)) { outputs.remove(outdex); p.setMode(Parameter.INOUT); ++parameters.inouts; } /* else if (paramLastLocalPart.equals(outParamLastLocalPart)) { outputs.remove(outdex); p.setMode(Parameter.INOUT); ++parameters.inouts; if (paramEntry.isBaseType()) { if (paramEntry.getBaseType().equals(outParamEntry.getBaseType())) { outputs.remove(outdex); p.setMode(Parameter.INOUT); ++parameters.inouts; } } else if (paramEntry.getRefType() != null) { if (paramEntry.getRefType().equals(outParamEntry.getRefType())) { outputs.remove(outdex); p.setMode(Parameter.INOUT); ++parameters.inouts; } } else { ++parameters.inputs; } } */ else { // If we're here, we have both an input and an output // part with the same name but different types.... guess // it's not really an inout.... // // throw new IOException(Messages.getMessage("differentTypes00", // new String[] { p.getName(), // p.getType().getQName().toString(), // outParam.getType().getQName().toString() // } // )); // There is some controversy about this, and the specs are // a bit vague about what should happen if the types don't // agree. Throwing an error is not correct with document/lit // operations, as part names get resused (i.e. "body"). // See WSDL 1.1 section 2.4.6, // WSDL 1.2 working draft 9 July 2002 section 2.3.1 ++parameters.inputs; } } else { ++parameters.inputs; } parameters.list.add(p); } // addInishParm /** * Add an output parameter to the parameters object. * * @param outputs * @param outdex * @param parameters * @param trim */ private void addOutParm(Vector outputs, int outdex, Parameters parameters, boolean trim) { Parameter p = (Parameter) outputs.get(outdex); // If this is an element, we want the XML to reflect the element name // not the part name. Same check is made in addInishParam above. if (p.getType() instanceof DefinedElement) { DefinedElement de = (DefinedElement) p.getType(); p.setQName(de.getQName()); } // If this is a collection we want the XML to reflect the type in // the collection, not foo[unbounded]. // Same check is made in addInishParam above. if (p.getType() instanceof CollectionElement) { p.setQName(p.getType().getRefType().getQName()); } if (trim) { outputs.remove(outdex); } p.setMode(Parameter.OUT); ++parameters.outputs; parameters.list.add(p); } // addOutParm /** * This method returns a vector containing Parameters which represent * each Part (shouldn't we call these "Parts" or something?) * * This routine does the wrapped doc/lit processing. * It is also used for generating Faults, and this really confuses things * but we need to do the same processing for the fault messages. * * This whole method is waaaay too complex. * It needs rewriting (for instance, we sometimes new up * a Parameter, then ignore it in favor of another we new up.) * * @param v The output vector of parameters * @param parts The parts of the message * @param literal Are we in a literal operation (or fault)? * @param opName The operation (or fault) name * @param bindingEntry The binding for this operation - can be NULL if we are looking at a fault * @throws IOException when encountering an error in the WSDL */ public void getParametersFromParts(Vector v, Collection parts, boolean literal, String opName, BindingEntry bindingEntry) throws IOException { // Determine if there's only one element. For wrapped // style, we normally only have 1 part which is an // element. But with MIME we could have any number of // types along with that single element. As long as // there's only ONE element, and it's the same name as // the operation, we can unwrap it. int numberOfElements = 0; boolean possiblyWrapped = false; Iterator i = parts.iterator(); while (i.hasNext()) { Part part = (Part) i.next(); if (part.getElementName() != null) { ++numberOfElements; if (part.getElementName().getLocalPart().equals(opName)) { possiblyWrapped = true; } } } // Try to sense "wrapped" document literal mode // if we haven't been told not to. // Criteria: // - If there is a single element part, // - That part is an element // - That element has the same name as the operation // - That element has no attributes (check done below) if (!nowrap && literal && (numberOfElements == 1) && possiblyWrapped) { wrapped = true; } i = parts.iterator(); while (i.hasNext()) { Parameter param = new Parameter(); Part part = (Part) i.next(); QName elementName = part.getElementName(); QName typeName = part.getTypeName(); String partName = part.getName(); // if we are either: // 1. encoded // 2. literal & not wrapped. if (!literal || !wrapped || (elementName == null)) { param.setName(partName); // Add this type or element name if (typeName != null) { param.setType(getType(typeName)); } else if (elementName != null) { // Just an FYI: The WSDL spec says that for use=encoded // that parts reference an abstract type using the type attr // but we kinda do the right thing here, so let it go. // if (!literal) // error... param.setType(getElement(elementName)); } else { // no type or element throw new IOException( Messages.getMessage( "noTypeOrElement00", new String[]{partName, opName})); } fillParamInfo(param, bindingEntry, opName, partName); v.add(param); continue; // next part } // flow to here means wrapped literal ! // See if we can map all the XML types to java(?) types // if we can, we use these as the types Node node = null; TypeEntry typeEntry = null; if ((typeName != null) && (bindingEntry == null || bindingEntry.getMIMETypes().size() == 0)) { // Since we can't (yet?) make the Axis engine generate the right // XML for literal parts that specify the type attribute, // (unless they're MIME types) abort processing with an // error if we encounter this case // // node = getTypeEntry(typeName, false).getNode(); String bindingName = (bindingEntry == null) ? "unknown" : bindingEntry.getBinding().getQName().toString(); throw new IOException(Messages.getMessage("literalTypePart00", new String[]{ partName, opName, bindingName})); } // Get the node which corresponds to the type entry for this // element. i.e.: // <part name="part" element="foo:bar"/> // ... // <schema targetNamespace="foo"> // <element name="bar"...> <--- This one typeEntry = getTypeEntry(elementName, true); node = typeEntry.getNode(); // Check if this element is of the form: // <element name="foo" type="tns:foo_type"/> BooleanHolder forElement = new BooleanHolder(); QName type = Utils.getTypeQName(node, forElement, false); if ((type != null) && !forElement.value) { // If in fact we have such a type, go get the node that // corresponds to THAT definition. typeEntry = getTypeEntry(type, false); node = typeEntry.getNode(); } Vector vTypes = null; // If we have nothing at this point, we're in trouble. if (node == null) { // If node is null, that means the element in question has no type declaration, // therefore is not a wrapper element. wrapped = false; if (verbose) { System.out.println(Messages.getMessage("cannotDoWrappedMode00", elementName.toString())); } } else { // check for attributes if (typeEntry.getContainedAttributes() != null) { // can't do wrapped mode wrapped = false; } if (!SchemaUtils.isWrappedType(node)) { // mark the type entry as not just literal referenced // This doesn't work, but it may help in the future. // The problem is "wrapped" is a symbol table wide flag, // which means if one operation breaks the rules // implemented in isWrappedType(), then everything goes bad // For example, see bug Axis-1900. typeEntry.setOnlyLiteralReference(false); wrapped = false; } // Get the nested type entries. // TODO - If we are unable to represent any of the types in the // element, we need to use SOAPElement/SOAPBodyElement. // I don't believe getContainedElementDecl does the right thing yet. vTypes = typeEntry.getContainedElements(); } // IF we got the type entries and we didn't find attributes // THEN use the things in this element as the parameters if ((vTypes != null) && wrapped) { // add the elements in this list for (int j = 0; j < vTypes.size(); j++) { ElementDecl elem = (ElementDecl) vTypes.elementAt(j); Parameter p = new Parameter(); p.setQName(elem.getQName()); // If the parameter is a anonymous complex type, the parameter // name should just be the name of the element, not >foo>element String paramName = p.getName(); final int gt = paramName.lastIndexOf(ANON_TOKEN); if (gt != 1) { paramName = paramName.substring(gt+1); } p.setName(paramName); p.setType(elem.getType()); p.setOmittable(elem.getMinOccursIs0()); p.setNillable(elem.getNillable()); fillParamInfo(p, bindingEntry, opName, partName); v.add(p); } } else { // - we were unable to get the types OR // - we found attributes // so we can't use wrapped mode. param.setName(partName); if (typeName != null) { param.setType(getType(typeName)); } else if (elementName != null) { param.setType(getElement(elementName)); } fillParamInfo(param, bindingEntry, opName, partName); v.add(param); } } // while } // getParametersFromParts /** * Set the header information for this paramter * * @param param Parameter to modify * @param bindingEntry Binding info for this operation/parameter * @param opName the operation we are processing * @param partName the part we are processing */ private void fillParamInfo(Parameter param, BindingEntry bindingEntry, String opName, String partName) { // If we don't have a binding, can't do anything if (bindingEntry == null) return; setMIMEInfo(param, bindingEntry.getMIMEInfo(opName, partName)); boolean isHeader = false; // Is this parameter in an Input header? if (bindingEntry.isInHeaderPart(opName, partName)) { isHeader = true; param.setInHeader(true); } // Is this parameter in an Output header? if (bindingEntry.isOutHeaderPart(opName, partName)) { isHeader = true; param.setOutHeader(true); } // If this parameter is part of a header, find the binding operation // that we are processing and get the QName of the parameter. if (isHeader && (bindingEntry.getBinding() != null)) { List list = bindingEntry.getBinding().getBindingOperations(); for (int i = 0; (list != null) && (i < list.size()); i++) { BindingOperation operation = (BindingOperation) list.get(i); if (operation.getName().equals(opName)) { if (param.isInHeader()) { QName qName = getBindedParameterName( operation.getBindingInput().getExtensibilityElements(), param); if(qName!= null) { param.setQName(qName); } } else if (param.isOutHeader()) { QName qName = getBindedParameterName( operation.getBindingOutput().getExtensibilityElements(), param); if(qName!= null) { param.setQName(qName); } } } } } } /** * Method getBindedParameterName * * @param elements * @param p * @return */ private QName getBindedParameterName(List elements, Parameter p) { // If the parameter can either be in the message header or in the // message body. // When it is in the header, there may be a SOAPHeader (soap:header) // with its part name. The namespace used is the one of the soap:header. // When it is in the body, if there is a SOAPBody with its part name, // the namespace used is the one of this soap:body. // // If the parameter is in the body and there is a soap:body with no parts, // its namespace is used for the parameter. QName paramName = null; String defaultNamespace = null; String parameterPartName = p.getName(); for (Iterator k = elements.iterator(); k.hasNext();) { ExtensibilityElement element = (ExtensibilityElement) k.next(); if (element instanceof SOAPBody) { SOAPBody bodyElement = (SOAPBody) element; List parts = bodyElement.getParts(); if ((parts == null) || (parts.size() == 0)) { defaultNamespace = bodyElement.getNamespaceURI(); } else { boolean found = false; for (Iterator l = parts.iterator(); l.hasNext();) { Object o = l.next(); if(o instanceof String) { if (parameterPartName.equals((String)o)) { paramName = new QName(bodyElement.getNamespaceURI(), parameterPartName); found = true; break; } } } if (found) { break; } } } else if (element instanceof SOAPHeader) { SOAPHeader headerElement = (SOAPHeader) element; String part = headerElement.getPart(); if (parameterPartName.equals(part)) { paramName = new QName(headerElement.getNamespaceURI(), parameterPartName); break; } } } if ((paramName == null) && (!p.isInHeader()) && (!p.isOutHeader())) { if (defaultNamespace != null) { paramName = new QName(defaultNamespace, parameterPartName); } else { paramName = p.getQName(); } } return paramName; } /** * Set the MIME type. This can be determine in one of two ways: * 1. From WSDL 1.1 MIME constructs on the binding (passed in); * 2. From AXIS-specific xml MIME types. * * @param p * @param mimeInfo */ private void setMIMEInfo(Parameter p, MimeInfo mimeInfo) { // If there is no binding MIME construct (ie., the mimeType parameter is // null), then get the MIME type from the AXIS-specific xml MIME type. if (mimeInfo == null && p.getType() != null) { QName mimeQName = p.getType().getQName(); if (mimeQName.getNamespaceURI().equals(Constants.NS_URI_XMLSOAP)) { if (Constants.MIME_IMAGE.equals(mimeQName)) { mimeInfo = new MimeInfo("image/jpeg", ""); } else if (Constants.MIME_PLAINTEXT.equals(mimeQName)) { mimeInfo = new MimeInfo("text/plain", ""); } else if (Constants.MIME_MULTIPART.equals(mimeQName)) { mimeInfo = new MimeInfo("multipart/related", ""); } else if (Constants.MIME_SOURCE.equals(mimeQName)) { mimeInfo = new MimeInfo("text/xml", ""); } else if (Constants.MIME_OCTETSTREAM.equals(mimeQName)) { mimeInfo = new MimeInfo("application/octet-stream", ""); } } } p.setMIMEInfo(mimeInfo); } // setMIMEType /** * Populate the symbol table with all of the BindingEntry's from the Definition. * * @param def * @throws IOException */ private void populateBindings(Definition def) throws IOException { Iterator i = def.getBindings().values().iterator(); while (i.hasNext()) { Binding binding = (Binding) i.next(); BindingEntry bEntry = new BindingEntry(binding); symbolTablePut(bEntry); Iterator extensibilityElementsIterator = binding.getExtensibilityElements().iterator(); while (extensibilityElementsIterator.hasNext()) { Object obj = extensibilityElementsIterator.next(); if (obj instanceof SOAPBinding) { bEntry.setBindingType(BindingEntry.TYPE_SOAP); SOAPBinding sb = (SOAPBinding) obj; String style = sb.getStyle(); if ("rpc".equalsIgnoreCase(style)) { bEntry.setBindingStyle(Style.RPC); } } else if (obj instanceof HTTPBinding) { HTTPBinding hb = (HTTPBinding) obj; if (hb.getVerb().equalsIgnoreCase("post")) { bEntry.setBindingType(BindingEntry.TYPE_HTTP_POST); } else { bEntry.setBindingType(BindingEntry.TYPE_HTTP_GET); } } else if (obj instanceof SOAP12Binding) { bEntry.setBindingType(BindingEntry.TYPE_SOAP); SOAP12Binding sb = (SOAP12Binding) obj; String style = sb.getStyle(); if ("rpc".equalsIgnoreCase(style)) { bEntry.setBindingStyle(Style.RPC); } } } // Step through the binding operations, setting the following as appropriate: // - hasLiteral // - body types // - mimeTypes // - headers HashMap attributes = new HashMap(); List bindList = binding.getBindingOperations(); HashMap faultMap = new HashMap(); // name to SOAPFault from WSDL4J for (Iterator opIterator = bindList.iterator(); opIterator.hasNext();) { BindingOperation bindOp = (BindingOperation) opIterator.next(); Operation operation = bindOp.getOperation(); BindingInput bindingInput = bindOp.getBindingInput(); BindingOutput bindingOutput = bindOp.getBindingOutput(); String opName = bindOp.getName(); // First, make sure the binding operation matches a portType operation String inputName = (bindingInput == null) ? null : bindingInput.getName(); String outputName = (bindingOutput == null) ? null : bindingOutput.getName(); if (binding.getPortType().getOperation( opName, inputName, outputName) == null) { throw new IOException(Messages.getMessage("unmatchedOp", new String[]{ opName, inputName, outputName})); } ArrayList faults = new ArrayList(); // input if (bindingInput != null) { if (bindingInput.getExtensibilityElements() != null) { Iterator inIter = bindingInput.getExtensibilityElements().iterator(); fillInBindingInfo(bEntry, operation, inIter, faults, true); } } // output if (bindingOutput != null) { if (bindingOutput.getExtensibilityElements() != null) { Iterator outIter = bindingOutput.getExtensibilityElements().iterator(); fillInBindingInfo(bEntry, operation, outIter, faults, false); } } // faults faultsFromSOAPFault(binding, bindOp, operation, faults); // Add this fault name and info to the map faultMap.put(bindOp, faults); Use inputBodyType = bEntry.getInputBodyType(operation); Use outputBodyType = bEntry.getOutputBodyType(operation); // Associate the portType operation that goes with this binding // with the body types. attributes.put(bindOp.getOperation(), new BindingEntry.OperationAttr(inputBodyType, outputBodyType, faultMap)); // If the input or output body uses literal, flag the binding as using literal. // NOTE: should I include faultBodyType in this check? if ((inputBodyType == Use.LITERAL) || (outputBodyType == Use.LITERAL)) { bEntry.setHasLiteral(true); } bEntry.setFaultBodyTypeMap(operation, faultMap); } // binding operations bEntry.setFaults(faultMap); } } // populateBindings /** * Fill in some binding information: bodyType, mimeType, header info. * * @param bEntry * @param operation * @param it * @param faults * @param input * @throws IOException */ private void fillInBindingInfo( BindingEntry bEntry, Operation operation, Iterator it, ArrayList faults, boolean input) throws IOException { for (; it.hasNext();) { Object obj = it.next(); if (obj instanceof SOAPBody) { setBodyType(((SOAPBody) obj).getUse(), bEntry, operation, input); } else if (obj instanceof SOAPHeader) { SOAPHeader header = (SOAPHeader) obj; setBodyType(header.getUse(), bEntry, operation, input); // Note, this only works for explicit headers - those whose // parts come from messages used in the portType's operation // input/output clauses - it does not work for implicit // headers - those whose parts come from messages not used in // the portType's operation's input/output clauses. I don't // know what we're supposed to emit for implicit headers. bEntry.setHeaderPart(operation.getName(), header.getPart(), input ? BindingEntry.IN_HEADER : BindingEntry.OUT_HEADER); // Add any soap:headerFault info to the faults array Iterator headerFaults = header.getSOAPHeaderFaults().iterator(); while (headerFaults.hasNext()) { SOAPHeaderFault headerFault = (SOAPHeaderFault) headerFaults.next(); faults.add(new FaultInfo(headerFault, this)); } } else if (obj instanceof MIMEMultipartRelated) { bEntry.setBodyType( operation, addMIMETypes( bEntry, (MIMEMultipartRelated) obj, operation), input); } else if (obj instanceof SOAP12Body) { setBodyType(((SOAP12Body) obj).getUse(), bEntry, operation, input); } else if (obj instanceof SOAP12Header) { SOAP12Header header = (SOAP12Header) obj; setBodyType(header.getUse(), bEntry, operation, input); // Note, this only works for explicit headers - those whose // parts come from messages used in the portType's operation // input/output clauses - it does not work for implicit // headers - those whose parts come from messages not used in // the portType's operation's input/output clauses. I don't // know what we're supposed to emit for implicit headers. bEntry.setHeaderPart(operation.getName(), header.getPart(), input ? BindingEntry.IN_HEADER : BindingEntry.OUT_HEADER); // Add any soap12:headerFault info to the faults array Iterator headerFaults = header.getSOAP12HeaderFaults().iterator(); while (headerFaults.hasNext()) { SOAP12HeaderFault headerFault = (SOAP12HeaderFault) headerFaults.next(); faults.add(new FaultInfo(headerFault.getMessage(), headerFault.getPart(), headerFault.getUse(), headerFault.getNamespaceURI(), this)); } } else if (obj instanceof UnknownExtensibilityElement) { UnknownExtensibilityElement unkElement = (UnknownExtensibilityElement) obj; QName name = unkElement.getElementType(); if (name.getNamespaceURI().equals(Constants.URI_DIME_WSDL) && name.getLocalPart().equals("message")) { fillInDIMEInformation(unkElement, input, operation, bEntry); } } } } // fillInBindingInfo /** * Fill in DIME information * * @param unkElement * @param input * @param operation * @param bEntry */ private void fillInDIMEInformation(UnknownExtensibilityElement unkElement, boolean input, Operation operation, BindingEntry bEntry) { String layout = unkElement.getElement().getAttribute("layout"); // TODO: what to do with layout info? if (layout.equals(Constants.URI_DIME_CLOSED_LAYOUT)) { } else if (layout.equals(Constants.URI_DIME_OPEN_LAYOUT)) { } Map parts = null; if (input) { parts = operation.getInput().getMessage().getParts(); } else { parts = operation.getOutput().getMessage().getParts(); } if (parts != null) { Iterator iterator = parts.values().iterator(); while (iterator.hasNext()) { Part part = (Part) iterator.next(); if (part != null) { String dims = ""; org.w3c.dom.Element element = null; if (part.getTypeName() != null) { TypeEntry partType = getType(part.getTypeName()); if (partType.getDimensions().length() > 0) { dims = partType.getDimensions(); partType = partType.getRefType(); } element = (org.w3c.dom.Element) partType.getNode(); } else if (part.getElementName() != null) { TypeEntry partElement = getElement(part.getElementName()).getRefType(); element = (org.w3c.dom.Element) partElement.getNode(); QName name = getInnerCollectionComponentQName(element); if (name != null) { dims += "[]"; partElement = getType(name); element = (org.w3c.dom.Element) partElement.getNode(); } else { name = getInnerTypeQName(element); if (name != null) { partElement = getType(name); element = (org.w3c.dom.Element) partElement.getNode(); } } } if (element != null) { org.w3c.dom.Element e = (org.w3c.dom.Element) XMLUtils.findNode( element, new QName( Constants.URI_DIME_CONTENT, "mediaType")); if (e != null) { String value = e.getAttribute("value"); bEntry.setOperationDIME(operation.getName()); bEntry.setMIMEInfo(operation.getName(), part.getName(), value, dims); } } } } } } /** * Get the faults from the soap:fault clause. * * @param binding * @param bindOp * @param operation * @param faults * @throws IOException */ private void faultsFromSOAPFault( Binding binding, BindingOperation bindOp, Operation operation, ArrayList faults) throws IOException { Iterator faultMapIter = bindOp.getBindingFaults().values().iterator(); for (; faultMapIter.hasNext();) { BindingFault bFault = (BindingFault) faultMapIter.next(); // Set default entry for this fault String faultName = bFault.getName(); // Check to make sure this fault is named if ((faultName == null) || (faultName.length() == 0)) { throw new IOException( Messages.getMessage( "unNamedFault00", bindOp.getName(), binding.getQName().toString())); } boolean foundSOAPFault = false; String soapFaultUse = ""; String soapFaultNamespace = ""; Iterator faultIter = bFault.getExtensibilityElements().iterator(); for (; faultIter.hasNext();) { Object obj = faultIter.next(); if (obj instanceof SOAPFault) { foundSOAPFault = true; soapFaultUse = ((SOAPFault) obj).getUse(); soapFaultNamespace = ((SOAPFault) obj).getNamespaceURI(); break; } else if (obj instanceof SOAP12Fault) { foundSOAPFault = true; soapFaultUse = ((SOAP12Fault) obj).getUse(); soapFaultNamespace = ((SOAP12Fault) obj).getNamespaceURI(); break; } } // Check to make sure we have a soap:fault element if (!foundSOAPFault) { throw new IOException( Messages.getMessage( "missingSoapFault00", faultName, bindOp.getName(), binding.getQName().toString())); } // TODO error checking: // if use=literal, no use of namespace on the soap:fault // if use=encoded, no use of element on the part // Check this fault to make sure it matches the one // in the matching portType Operation Fault opFault = operation.getFault(bFault.getName()); if (opFault == null) { throw new IOException(Messages.getMessage("noPortTypeFault", new String[]{ bFault.getName(), bindOp.getName(), binding.getQName().toString()})); } // put the updated entry back in the map faults.add(new FaultInfo(opFault, Use.getUse(soapFaultUse), soapFaultNamespace, this)); } } // faultsFromSOAPFault /** * Set the body type. * * @param use * @param bEntry * @param operation * @param input */ private void setBodyType(String use, BindingEntry bEntry, Operation operation, boolean input) { if (use == null) { // Deprecated // throw new IOException(Messages.getMessage("noUse", // operation.getName())); // for WS-I BP 1.0 R2707. // Set default of use to literal. use = "literal"; } if (use.equalsIgnoreCase("literal")) { bEntry.setBodyType(operation, Use.LITERAL, input); } } // setBodyType /** * Add the parts that are really MIME types as MIME types. * A side effect is to return the body Type of the given * MIMEMultipartRelated object. * * @param bEntry * @param mpr * @param op * @return * @throws IOException */ private Use addMIMETypes( BindingEntry bEntry, MIMEMultipartRelated mpr, Operation op) throws IOException { Use bodyType = Use.ENCODED; List parts = mpr.getMIMEParts(); Iterator i = parts.iterator(); while (i.hasNext()) { MIMEPart part = (MIMEPart) i.next(); List elems = part.getExtensibilityElements(); Iterator j = elems.iterator(); while (j.hasNext()) { Object obj = j.next(); if (obj instanceof MIMEContent) { MIMEContent content = (MIMEContent) obj; TypeEntry typeEntry = findPart(op, content.getPart()); if (typeEntry == null) { throw new RuntimeException(Messages.getMessage("cannotFindPartForOperation00", content.getPart(), op.getName(), content.getType())); } String dims = typeEntry.getDimensions(); if ((dims.length() <= 0) && (typeEntry.getRefType() != null)) { Node node = typeEntry.getRefType().getNode(); if (getInnerCollectionComponentQName(node) != null) { dims += "[]"; } } String type = content.getType(); if ((type == null) || (type.length() == 0)) { type = "text/plain"; } bEntry.setMIMEInfo(op.getName(), content.getPart(), type, dims); } else if (obj instanceof SOAPBody) { String use = ((SOAPBody) obj).getUse(); if (use == null) { throw new IOException( Messages.getMessage("noUse", op.getName())); } if (use.equalsIgnoreCase("literal")) { bodyType = Use.LITERAL; } } else if (obj instanceof SOAP12Body) { String use = ((SOAP12Body) obj).getUse(); if (use == null) { throw new IOException( Messages.getMessage("noUse", op.getName())); } if (use.equalsIgnoreCase("literal")) { bodyType = Use.LITERAL; } } } } return bodyType; } // addMIMETypes /** * Method findPart * * @param operation * @param partName * @return */ private TypeEntry findPart(Operation operation, String partName) { Map parts = operation.getInput().getMessage().getParts(); Iterator iterator = parts.values().iterator(); TypeEntry part = findPart(iterator, partName); if (part == null) { parts = operation.getOutput().getMessage().getParts(); iterator = parts.values().iterator(); part = findPart(iterator, partName); } return part; } /** * Method findPart * * @param iterator * @param partName * @return */ private TypeEntry findPart(Iterator iterator, String partName) { while (iterator.hasNext()) { Part part = (Part) iterator.next(); if (part != null) { String typeName = part.getName(); if (partName.equals(typeName)) { if (part.getTypeName() != null) { return getType(part.getTypeName()); } else if (part.getElementName() != null) { return getElement(part.getElementName()); } } } } return null; } /** * Populate the symbol table with all of the ServiceEntry's from the Definition. * * @param def * @throws IOException */ private void populateServices(Definition def) throws IOException { String originalName = null; Iterator i = def.getServices().values().iterator(); while (i.hasNext()) { Service service = (Service) i.next(); originalName = service.getQName().getLocalPart(); // do a bit of name validation if ((service.getQName() == null) || (service.getQName().getLocalPart() == null) || service.getQName().getLocalPart().equals("")) { throw new IOException(Messages.getMessage("BadServiceName00")); } // behave as though backslashes were never there service.setQName(BackslashUtil.getQNameWithBackslashlessLocal(service.getQName())); ServiceEntry sEntry = new ServiceEntry(service); // we'll need this later when it is time print a backslash escaped service name sEntry.setOriginalServiceName(originalName); symbolTablePut(sEntry); populatePorts(service.getPorts()); } } // populateServices /** * populates the symbol table with port elements defined within a &lt;service&gt; * element. * * @param ports a map of name->port pairs (i.e. what is returned by service.getPorts() * @throws IOException thrown, if an IO or WSDL error is detected * @see javax.wsdl.Service#getPorts() * @see javax.wsdl.Port */ private void populatePorts(Map ports) throws IOException { if (ports == null) { return; } Iterator it = ports.values().iterator(); while (it.hasNext()) { Port port = (Port) it.next(); String portName = port.getName(); Binding portBinding = port.getBinding(); // make sure there is a port name. The 'name' attribute for WSDL ports is // mandatory // if (portName == null) { // REMIND: should rather be a javax.wsdl.WSDLException ? throw new IOException( Messages.getMessage("missingPortNameException")); } // make sure there is a binding for the port. The 'binding' attribute for // WSDL ports is mandatory // if (portBinding == null) { // REMIND: should rather be a javax.wsdl.WSDLException ? throw new IOException( Messages.getMessage("missingBindingException")); } // make sure the port name is unique among all port names defined in this // WSDL document. // // NOTE: there's a flaw in com.ibm.wsdl.xml.WSDLReaderImpl#parsePort() and // com.ibm.wsdl.xml.WSDLReaderImpl#addPort(). These methods do not enforce // the port name exists and is unique. Actually, if two port definitions with // the same name exist within the same service element, only *one* port // element is present after parsing and the following exception is not thrown. // // If two ports with the same name exist in different service elements, // the exception below is thrown. This is conformant to the WSDL 1.1 spec (sec 2.6) // , which states: "The name attribute provides a unique name among all ports // defined within in the enclosing WSDL document." // // if (existsPortWithName(new QName(portName))) { // REMIND: should rather be a javax.wsdl.WSDLException ? throw new IOException( Messages.getMessage("twoPortsWithSameName", portName)); } PortEntry portEntry = new PortEntry(port); symbolTablePut(portEntry); } } /** * Set each SymTabEntry's isReferenced flag. The default is false. If no other symbol * references this symbol, then leave it false, otherwise set it to true. * (An exception to the rule is that derived types are set as referenced if * their base type is referenced. This is necessary to support generation and * registration of derived types.) * * @param def * @param doc */ private void setReferences(Definition def, Document doc) { Map stuff = def.getServices(); if (stuff.isEmpty()) { stuff = def.getBindings(); if (stuff.isEmpty()) { stuff = def.getPortTypes(); if (stuff.isEmpty()) { stuff = def.getMessages(); if (stuff.isEmpty()) { for (Iterator i = elementTypeEntries.values().iterator(); i.hasNext();) { setTypeReferences((TypeEntry) i.next(), doc, false); } for (Iterator i = typeTypeEntries.values().iterator(); i.hasNext();) { setTypeReferences((TypeEntry) i.next(), doc, false); } } else { Iterator i = stuff.values().iterator(); while (i.hasNext()) { Message message = (Message) i.next(); MessageEntry mEntry = getMessageEntry(message.getQName()); setMessageReferences(mEntry, def, doc, false); } } } else { Iterator i = stuff.values().iterator(); while (i.hasNext()) { PortType portType = (PortType) i.next(); PortTypeEntry ptEntry = getPortTypeEntry(portType.getQName()); setPortTypeReferences(ptEntry, null, def, doc); } } } else { Iterator i = stuff.values().iterator(); while (i.hasNext()) { Binding binding = (Binding) i.next(); BindingEntry bEntry = getBindingEntry(binding.getQName()); setBindingReferences(bEntry, def, doc); } } } else { Iterator i = stuff.values().iterator(); while (i.hasNext()) { Service service = (Service) i.next(); ServiceEntry sEntry = getServiceEntry(service.getQName()); setServiceReferences(sEntry, def, doc); } } } // setReferences /** * Set the isReferenced flag to true on the given TypeEntry and all * SymTabEntries that it refers to. * * @param entry * @param doc * @param literal */ private void setTypeReferences(TypeEntry entry, Document doc, boolean literal) { // Check to see if already processed. if ((entry.isReferenced() && !literal) || (entry.isOnlyLiteralReferenced() && literal)) { return; } if (wrapped) { // If this type is ONLY referenced from a literal usage in a binding, // then isOnlyLiteralReferenced should return true. if (!entry.isReferenced() && literal) { entry.setOnlyLiteralReference(true); } // If this type was previously only referenced as a literal type, // but now it is referenced in a non-literal manner, turn off the // onlyLiteralReference flag. else if (entry.isOnlyLiteralReferenced() && !literal) { entry.setOnlyLiteralReference(false); } } // If we don't want to emit stuff from imported files, only set the // isReferenced flag if this entry exists in the immediate WSDL file. Node node = entry.getNode(); if (addImports || (node == null) || (node.getOwnerDocument() == doc)) { entry.setIsReferenced(true); if (entry instanceof DefinedElement) { BooleanHolder forElement = new BooleanHolder(); QName referentName = Utils.getTypeQName(node, forElement, false); if (referentName != null) { TypeEntry referent = getTypeEntry(referentName, forElement.value); if (referent != null) { setTypeReferences(referent, doc, literal); } } // If the Defined Element has an anonymous type, // process it with the current literal flag setting. QName anonQName = SchemaUtils.getElementAnonQName(entry.getNode()); if (anonQName != null) { TypeEntry anonType = getType(anonQName); if (anonType != null) { setTypeReferences(anonType, doc, literal); return; } } } } HashSet nestedTypes = entry.getNestedTypes(this, true); Iterator it = nestedTypes.iterator(); while (it.hasNext()) { TypeEntry nestedType = (TypeEntry) it.next(); TypeEntry refType = entry.getRefType(); if (nestedType == null) { continue; } // If this entry has a referenced type that isn't // the same as the nested type // AND the OnlyLiteral reference switch is on // THEN turn the OnlyLiteral reference switch off. // If only someone had put a comment here saying why we do this... if ((refType != null) && !refType.equals(nestedType) && nestedType.isOnlyLiteralReferenced()) { nestedType.setOnlyLiteralReference(false); } if (!nestedType.isReferenced()) { // setTypeReferences(nestedType, doc, literal); if (nestedType != entry) { setTypeReferences(nestedType, doc, false); } } } } // setTypeReferences /** * Set the isReferenced flag to true on the given MessageEntry and all * SymTabEntries that it refers to. * * @param entry * @param def * @param doc * @param literal */ private void setMessageReferences(MessageEntry entry, Definition def, Document doc, boolean literal) { // If we don't want to emit stuff from imported files, only set the // isReferenced flag if this entry exists in the immediate WSDL file. Message message = entry.getMessage(); if (addImports) { entry.setIsReferenced(true); } else { // NOTE: I thought I could have simply done: // if (def.getMessage(message.getQName()) != null) // but that method traces through all imported messages. Map messages = def.getMessages(); if (messages.containsValue(message)) { entry.setIsReferenced(true); } } // Set all the message's types Iterator parts = message.getParts().values().iterator(); while (parts.hasNext()) { Part part = (Part) parts.next(); TypeEntry type = getType(part.getTypeName()); if (type != null) { setTypeReferences(type, doc, literal); } type = getElement(part.getElementName()); if (type != null) { setTypeReferences(type, doc, literal); TypeEntry refType = type.getRefType(); if (refType != null) { setTypeReferences(refType, doc, literal); } } } } // setMessageReference /** * Set the isReferenced flag to true on the given PortTypeEntry and all * SymTabEntries that it refers to. * * @param entry * @param bEntry * @param def * @param doc */ private void setPortTypeReferences(PortTypeEntry entry, BindingEntry bEntry, Definition def, Document doc) { // If we don't want to emit stuff from imported files, only set the // isReferenced flag if this entry exists in the immediate WSDL file. PortType portType = entry.getPortType(); if (addImports) { entry.setIsReferenced(true); } else { // NOTE: I thought I could have simply done: // if (def.getPortType(portType.getQName()) != null) // but that method traces through all imported portTypes. Map portTypes = def.getPortTypes(); if (portTypes.containsValue(portType)) { entry.setIsReferenced(true); } } // Set all the portType's messages Iterator operations = portType.getOperations().iterator(); // For each operation, query its input, output, and fault messages while (operations.hasNext()) { Operation operation = (Operation) operations.next(); Input input = operation.getInput(); Output output = operation.getOutput(); // Find out if this reference is a literal reference or not. boolean literalInput = false; boolean literalOutput = false; if (bEntry != null) { literalInput = bEntry.getInputBodyType(operation) == Use.LITERAL; literalOutput = bEntry.getOutputBodyType(operation) == Use.LITERAL; } // Query the input message if (input != null) { Message message = input.getMessage(); if (message != null) { MessageEntry mEntry = getMessageEntry(message.getQName()); if (mEntry != null) { setMessageReferences(mEntry, def, doc, literalInput); } } } // Query the output message if (output != null) { Message message = output.getMessage(); if (message != null) { MessageEntry mEntry = getMessageEntry(message.getQName()); if (mEntry != null) { setMessageReferences(mEntry, def, doc, literalOutput); } } } // Query the fault messages Iterator faults = operation.getFaults().values().iterator(); while (faults.hasNext()) { Message message = ((Fault) faults.next()).getMessage(); if (message != null) { MessageEntry mEntry = getMessageEntry(message.getQName()); if (mEntry != null) { setMessageReferences(mEntry, def, doc, false); } } } } } // setPortTypeReferences /** * Set the isReferenced flag to true on the given BindingEntry and all * SymTabEntries that it refers to ONLY if this binding is a SOAP binding. * * @param entry * @param def * @param doc */ private void setBindingReferences(BindingEntry entry, Definition def, Document doc) { if (entry.getBindingType() == BindingEntry.TYPE_SOAP) { // If we don't want to emit stuff from imported files, only set the // isReferenced flag if this entry exists in the immediate WSDL file. Binding binding = entry.getBinding(); if (addImports) { entry.setIsReferenced(true); } else { // NOTE: I thought I could have simply done: // if (def.getBindng(binding.getQName()) != null) // but that method traces through all imported bindings. Map bindings = def.getBindings(); if (bindings.containsValue(binding)) { entry.setIsReferenced(true); } } // Set all the binding's portTypes PortType portType = binding.getPortType(); PortTypeEntry ptEntry = getPortTypeEntry(portType.getQName()); if (ptEntry != null) { setPortTypeReferences(ptEntry, entry, def, doc); } } } // setBindingReferences /** * Set the isReferenced flag to true on the given ServiceEntry and all * SymTabEntries that it refers to. * * @param entry * @param def * @param doc */ private void setServiceReferences(ServiceEntry entry, Definition def, Document doc) { // If we don't want to emit stuff from imported files, only set the // isReferenced flag if this entry exists in the immediate WSDL file. Service service = entry.getService(); if (addImports) { entry.setIsReferenced(true); } else { // NOTE: I thought I could have simply done: // if (def.getService(service.getQName()) != null) // but that method traces through all imported services. Map services = def.getServices(); if (services.containsValue(service)) { entry.setIsReferenced(true); } } // Set all the service's bindings Iterator ports = service.getPorts().values().iterator(); while (ports.hasNext()) { Port port = (Port) ports.next(); Binding binding = port.getBinding(); if (binding != null) { BindingEntry bEntry = getBindingEntry(binding.getQName()); if (bEntry != null) { setBindingReferences(bEntry, def, doc); } } } } // setServiceReferences /** * Put the given SymTabEntry into the symbol table, if appropriate. * * @param entry * @throws IOException */ private SymTabEntry symbolTablePut(SymTabEntry entry) throws IOException { QName name = entry.getQName(); SymTabEntry e = get(name, entry.getClass()); if (e == null) { e = entry; // An entry of the given qname of the given type doesn't exist yet. if ((entry instanceof Type) && (get(name, UndefinedType.class) != null)) { // A undefined type exists in the symbol table, which means // that the type is used, but we don't yet have a definition for // the type. Now we DO have a definition for the type, so // replace the existing undefined type with the real type. if (((TypeEntry) get(name, UndefinedType.class)).isSimpleType() && !((TypeEntry) entry).isSimpleType()) { // Problem if the undefined type was used in a // simple type context. throw new IOException( Messages.getMessage( "AttrNotSimpleType01", name.toString())); } Vector v = (Vector) symbolTable.get(name); for (int i = 0; i < v.size(); ++i) { Object oldEntry = v.elementAt(i); if (oldEntry instanceof UndefinedType) { // Replace it in the symbol table v.setElementAt(entry, i); // Replace it in the types index typeTypeEntries.put(name, entry); // Update all of the entries that refer to the unknown type ((UndefinedType) oldEntry).update((Type) entry); } } } else if ((entry instanceof Element) && (get(name, UndefinedElement.class) != null)) { // A undefined element exists in the symbol table, which means // that the element is used, but we don't yet have a definition for // the element. Now we DO have a definition for the element, so // replace the existing undefined element with the real element. Vector v = (Vector) symbolTable.get(name); for (int i = 0; i < v.size(); ++i) { Object oldEntry = v.elementAt(i); if (oldEntry instanceof UndefinedElement) { // Replace it in the symbol table v.setElementAt(entry, i); // Replace it in the elements index elementTypeEntries.put(name, entry); // Update all of the entries that refer to the unknown type ((Undefined) oldEntry).update((Element) entry); } } } else { // Add this entry to the symbol table Vector v = (Vector) symbolTable.get(name); if (v == null) { v = new Vector(); symbolTable.put(name, v); } v.add(entry); // add TypeEntries to specialized indices for // fast lookups during reference resolution. if (entry instanceof Element) { elementTypeEntries.put(name, entry); } else if (entry instanceof Type) { typeTypeEntries.put(name, entry); } } } else { if (!quiet) { System.out.println(Messages.getMessage("alreadyExists00", "" + name)); } } return e; } // symbolTablePut /** * checks whether there exists a WSDL port with a given name in the current * symbol table * * @param name the QName of the port. Note: only the local part of the qname is relevant, * since port names are not qualified with a namespace. They are of type nmtoken in WSDL 1.1 * and of type ncname in WSDL 1.2 * @return true, if there is a port element with the specified name; false, otherwise */ protected boolean existsPortWithName(QName name) { Vector v = (Vector) symbolTable.get(name); if (v == null) { return false; } Iterator it = v.iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof PortEntry) { return true; } } return false; } /** * Method getInnerCollectionComponentQName * * @param node * @return */ private QName getInnerCollectionComponentQName(Node node) { if (node == null) { return null; } QName name = SchemaUtils.getCollectionComponentQName(node, new QNameHolder(), new BooleanHolder(), this); if (name != null) { return name; } // Dive into the node if necessary NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { name = getInnerCollectionComponentQName(children.item(i)); if (name != null) { return name; } } return null; } /** * Method getInnerTypeQName * * @param node * @return */ private static QName getInnerTypeQName(Node node) { if (node == null) { return null; } BooleanHolder forElement = new BooleanHolder(); QName name = Utils.getTypeQName(node, forElement, true); if (name != null) { return name; } // Dive into the node if necessary NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { name = getInnerTypeQName(children.item(i)); if (name != null) { return name; } } return null; } protected void processTypes() { for (Iterator i = typeTypeEntries.values().iterator(); i.hasNext(); ) { Type type = (Type) i.next(); Node node = type.getNode(); // Process the attributes Vector attributes = SchemaUtils.getContainedAttributeTypes(node, this); if (attributes != null) { type.setContainedAttributes(attributes); } // Process the elements Vector elements = SchemaUtils.getContainedElementDeclarations(node, this); if (elements != null) { type.setContainedElements(elements); } } } public List getMessageEntries() { List messageEntries = new ArrayList(); Iterator iter = symbolTable.values().iterator(); while (iter.hasNext()) { Vector v = (Vector)iter.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry)v.elementAt(i); if (entry instanceof MessageEntry) { messageEntries.add(entry); } } } return messageEntries; } public void setWrapArrays(boolean wrapArrays) { this.wrapArrays = wrapArrays; } public Map getElementFormDefaults() { return elementFormDefaults; } }
7,724
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/CollectionElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This Element is for a QName that is a 'collection'. * For example, * &lt;element ref="bar" maxOccurs="unbounded" /&gt; * We need a way to indicate in the symbol table that a foo is * 'collection of bars', In such cases a collection element is * added with the special QName &lt;name&gt;[&lt;minOccurs&gt;, &lt;maxOccurs&gt;] */ public class CollectionElement extends DefinedElement implements CollectionTE { /** * Constructor CollectionElement * * @param pqName * @param refType * @param pNode * @param dims */ public CollectionElement(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName, refType, pNode, dims); } }
7,725
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Parameter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; /** * This class simply collects */ public class Parameter { // constant values for the parameter mode. /** Field IN */ public static final byte IN = 1; /** Field OUT */ public static final byte OUT = 2; /** Field INOUT */ public static final byte INOUT = 3; // The QName of the element associated with this param. Defaults to // null, which means it'll be new QName("", name) /** Field qname */ private QName qname; // The part name of this parameter, just a string. /** Field name */ private String name; // The MIME type of this parameter, null if it isn't a MIME type. /** Field mimeInfo */ private MimeInfo mimeInfo = null; /** Field type */ private TypeEntry type; /** Field mode */ private byte mode = IN; // Flags indicating whether the parameter goes into the soap message as // a header. /** Field inHeader */ private boolean inHeader = false; /** Field outHeader */ private boolean outHeader = false; /** Is this an omittable param? */ private boolean omittable = false; /** Is this a nilliable param? */ private boolean nillable = false; /** * Method toString * * @return */ public String toString() { return "(" + type + ((mimeInfo == null) ? "" : "(" + mimeInfo + ")") + ", " + getName() + ", " + ((mode == IN) ? "IN)" : (mode == INOUT) ? "INOUT)" : "OUT)" + (inHeader ? "(IN soap:header)" : "") + (outHeader ? "(OUT soap:header)" : "")); } // toString /** * Get the fully qualified name of this parameter. * * @return */ public QName getQName() { return qname; } /** * Get the name of this parameter. This call is equivalent to * getQName().getLocalPart(). * * @return */ public String getName() { if ((name == null) && (qname != null)) { return qname.getLocalPart(); } return name; } /** * Set the name of the parameter. This replaces both the * name and the QName (the namespaces becomes ""). * * @param name */ public void setName(String name) { this.name = name; if (qname == null) { this.qname = new QName("", name); } } /** * Set the QName of the parameter. * * @param qname */ public void setQName(QName qname) { this.qname = qname; } /** * Get the MIME type of the parameter. * * @return */ public MimeInfo getMIMEInfo() { return mimeInfo; } // getMIMEType /** * Set the MIME type of the parameter. * * @param mimeInfo */ public void setMIMEInfo(MimeInfo mimeInfo) { this.mimeInfo = mimeInfo; } // setMIMEType /** * Get the TypeEntry of the parameter. * * @return */ public TypeEntry getType() { return type; } /** * Set the TypeEntry of the parameter. * * @param type */ public void setType(TypeEntry type) { this.type = type; } /** * Get the mode (IN, INOUT, OUT) of the parameter. * * @return */ public byte getMode() { return mode; } /** * Set the mode (IN, INOUT, OUT) of the parameter. If the input * to this method is not one of IN, INOUT, OUT, then the value * remains unchanged. * * @param mode */ public void setMode(byte mode) { if (mode <= INOUT && mode >= IN) { this.mode = mode; } } /** * Is this parameter in the input message header? * * @return */ public boolean isInHeader() { return inHeader; } // isInHeader /** * Set the inHeader flag for this parameter. * * @param inHeader */ public void setInHeader(boolean inHeader) { this.inHeader = inHeader; } // setInHeader /** * Is this parameter in the output message header? * * @return */ public boolean isOutHeader() { return outHeader; } // isOutHeader /** * Set the outHeader flag for this parameter. * * @param outHeader */ public void setOutHeader(boolean outHeader) { this.outHeader = outHeader; } // setOutHeader public boolean isOmittable() { return omittable; } public void setOmittable(boolean omittable) { this.omittable = omittable; } /** * Indicates whether this parameter is nillable or not. * @return whether this parameter is nilliable */ public boolean isNillable() { return nillable; } /** * Indicate whether this parameter is nillable or not. * @param nillable whether this parameter is nilliable */ public void setNillable(boolean nillable) { this.nillable = nillable; } } // class Parameter
7,726
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Undefined.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import java.io.IOException; /** * This Undefined interface is implemented by UndefinedType and UndefinedElement. */ public interface Undefined { /** * Register referrant TypeEntry so that * the code can update the TypeEntry when the Undefined Element or Type is defined * * @param referrant */ public void register(TypeEntry referrant); /** * Call update with the actual TypeEntry. This updates all of the * referrant TypeEntry's that were registered. * * @param def * @throws IOException */ public void update(TypeEntry def) throws IOException; }
7,727
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/NullEntityResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.wsdl.symbolTable; import java.io.IOException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; class NullEntityResolver implements EntityResolver { static final NullEntityResolver INSTANCE = new NullEntityResolver(); private NullEntityResolver() {} public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }
7,728
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/ContainedAttribute.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; public class ContainedAttribute extends ContainedEntry { /** Field optional */ private boolean optional = false; /** * @param qname */ protected ContainedAttribute(TypeEntry type, QName qname) { super(type, qname); } /** * Method setOptional * * @param optional */ public void setOptional(boolean optional) { this.optional = optional; } /** * Method getOptional * * @return */ public boolean getOptional() { return optional; } }
7,729
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/BaseTypeMapping.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; /** * Get the base language name for a qname */ public abstract class BaseTypeMapping { /** * If the qname is registered in the target language, * return the name of the registered type. * * @param qName QName representing a type * @return name of the registered type or null if not registered. */ public abstract String getBaseName(QName qName); }
7,730
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/DefinedType.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This Type is for a QName that is a complex or simple type, these types are * always emitted. */ public class DefinedType extends Type { // cache lookups for our base type /** Field extensionBase */ protected TypeEntry extensionBase; /** Field searchedForExtensionBase */ protected boolean searchedForExtensionBase = false; /** * Constructor DefinedType * * @param pqName * @param pNode */ public DefinedType(QName pqName, Node pNode) { super(pqName, pNode); } /** * Constructor DefinedType * * @param pqName * @param refType * @param pNode * @param dims */ public DefinedType(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName, refType, pNode, dims); } /** * Get a TypeEntry for the base type of this type, if one exists. * * @param symbolTable a <code>SymbolTable</code> value * @return a <code>TypeEntry</code> value */ public TypeEntry getComplexTypeExtensionBase(SymbolTable symbolTable) { if(!searchedForExtensionBase) { if (null == extensionBase) { extensionBase = SchemaUtils.getComplexElementExtensionBase(getNode(), symbolTable); } searchedForExtensionBase = true; } return extensionBase; } }
7,731
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Utils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.Input; import javax.wsdl.Operation; import javax.wsdl.Part; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.mime.MIMEMultipartRelated; import javax.wsdl.extensions.soap.SOAPBody; import javax.wsdl.extensions.soap12.SOAP12Body; import javax.xml.namespace.QName; import javax.xml.rpc.holders.BooleanHolder; import java.util.*; /** * This class contains static utility methods for the emitter. * * @author Rich Scheuerle (scheu@us.ibm.com) * @author Tom Jordahl (tomj@macromedia.com) */ public class Utils { private static final Log log = LogFactory.getLog(Utils.class.getName()); /** cache of namespaces -> maps of localNames -> QNames */ static final Map nsmap = new HashMap(); /** * Find or create a QName with the specified namespace/localName. * * @param namespace * @param localName * @return */ static QName findQName(String namespace, String localName) { QName qname = null; // get the inner map, using the namespace as a key Map ln2qn = (Map) nsmap.get(namespace); if (null == ln2qn) { // cache miss ln2qn = new HashMap(); nsmap.put(namespace, ln2qn); qname = new QName(namespace, localName); ln2qn.put(localName, qname); } else { // cache hit qname = (QName) ln2qn.get(localName); if (null == qname) { // cache miss qname = new QName(namespace, localName); ln2qn.put(localName, qname); } else { // cache hit } } return qname; } /** * Given a node, return the value of the given attribute. * If the attribute does not exist, searching continues through ancestor nodes until found. * This method is useful for finding attributes that pertain to a group of contained * nodes (i.e. xlmns, xmlns:tns, targetNamespace, name) * * @param node * @param attr * @return */ public static String getScopedAttribute(Node node, String attr) { if (node == null) { return null; } if (node.getAttributes() == null) { return getScopedAttribute(node.getParentNode(), attr); } Node attrNode = node.getAttributes().getNamedItem(attr); if (attrNode != null) { return attrNode.getNodeValue(); } else { return getScopedAttribute(node.getParentNode(), attr); } } /** * Given a node, return the value of the given attribute. * Returns null if the attribute is not found * * @param node * @param attr * @return */ public static String getAttribute(Node node, String attr) { if ((node == null) || (node.getAttributes() == null)) { return null; } Node attrNode = node.getAttributes().getNamedItem(attr); if (attrNode != null) { return attrNode.getNodeValue(); } else { return null; } } /** * Given a node, return the attributes that have the specified local name. * Returns null if the attribute is not found * * @param node * @param localName * @return */ public static Vector getAttributesWithLocalName(Node node, String localName) { Vector v = new Vector(); if (node == null) { return v; } NamedNodeMap map = node.getAttributes(); if (map != null) { for (int i = 0; i < map.getLength(); i++) { Node attrNode = map.item(i); if ((attrNode != null) && attrNode.getLocalName().equals(localName)) { v.add(attrNode); } } } return v; } /** * An xml element may have a name. * For example &lt;element name="foo" type="b:bar"&gt; * has the name "element". This routine gets the full QName of the element. * * @param node * @return */ public static QName getNodeQName(Node node) { if (node == null) { return null; } String localName = node.getLocalName(); if (localName == null) { return null; } String namespace = node.getNamespaceURI(); return (findQName(namespace, localName)); } /** * XML nodes may have a name attribute. * For example &lt;element name="foo" type="b:bar"&gt; * has the name attribute value "foo". This routine gets the QName of the name attribute value. * * @param node * @return */ public static QName getNodeNameQName(Node node) { if (node == null) { return null; } String localName = null; String namespace = null; // First try to get the name directly localName = getAttribute(node, "name"); // If this fails and the node has a ref, use the ref name. if (localName == null) { QName ref = getTypeQNameFromAttr(node, "ref"); if (ref != null) { localName = ref.getLocalPart(); namespace = ref.getNamespaceURI(); } } // This routine may be called for complexType elements. In some cases, // the complexType may be anonymous, which is why the getScopedAttribute // method is used. Node search = node.getParentNode(); while (search != null) { String ln = search.getLocalName(); if (ln.equals("schema")) { search = null; } else if (ln.equals("element") || ln.equals("attribute")) { localName = SymbolTable.ANON_TOKEN + getNodeNameQName(search).getLocalPart(); search = null; } else if (ln.equals("complexType") || ln.equals("simpleType")) { localName = getNodeNameQName(search).getLocalPart() + SymbolTable.ANON_TOKEN + localName; search = null; } else { search = search.getParentNode(); } } if (localName == null) { return null; } // Build and return the QName if (namespace == null) { namespace = getScopedAttribute(node, "targetNamespace"); } return (findQName(namespace, localName)); } /** * An XML element or attribute node has several ways of * identifying the type of the element or attribute: * - use the type attribute to reference a complexType/simpleType * - use the ref attribute to reference another element, group or attributeGroup * - use of an anonymous type (i.e. a nested type underneath itself) * - a wsdl:part can use the element attribute. * - an extension can use the base attribute. * <p> * This routine returns a QName representing this "type". * The forElement value is also returned to indicate whether the * QName represents an element (i.e. obtained using the ref attribute) * or a type. * <p> * Other attributes affect the QName that is returned. * If the "minOccurs" and "maxOccurs" are set such that the * type is a collection of "types", then an artificial qname is * returned to represent the collection. * * @param node of the reference * @param forElement output parameter is set to true if QName is for an element * (i.e. ref= or element= attribute was used). * @param ignoreMaxOccurs indicates whether minOccurs/maxOccurs affects the QName * @return QName representing the type of this element */ public static QName getTypeQName(Node node, BooleanHolder forElement, boolean ignoreMaxOccurs) { if (node == null) { return null; } forElement.value = false; // Assume QName returned is for a type // Try getting the QName of the type attribute. // Note this also retrieves the type if an anonymous type is used. QName qName = getTypeQNameFromAttr(node, "type"); // If not successful, try using the ref attribute. if (qName == null) { String localName = node.getLocalName(); // bug 23145: support attributeGroup (Brook Richan) // a ref can be for an element or attributeGroup if ((localName != null) && !(localName.equals("attributeGroup") || localName.equals("group") || localName.equals("list"))) { forElement.value = true; } qName = getTypeQNameFromAttr(node, "ref"); } // in case of a list get the itemType if (qName == null) { qName = getTypeQNameFromAttr(node, "itemType"); } // If the node has "type"/"ref" and "maxOccurs" then the type is really // a collection. There is no qname in the wsdl which we can use to represent // the collection, so we need to invent one. // The local part of the qname is changed to <local>[minOccurs, maxOccurs] // The namespace uri is changed to the targetNamespace of this node if (!ignoreMaxOccurs) { if (qName != null) { String maxOccursValue = getAttribute(node, "maxOccurs"); String minOccursValue = getAttribute(node, "minOccurs"); String nillableValue = getAttribute(node, "nillable"); if (maxOccursValue == null) { maxOccursValue = "1"; } if (minOccursValue == null) { minOccursValue = "1"; } if (minOccursValue.equals("0") && maxOccursValue.equals("1")) { // If we have a minoccurs="0"/maxoccurs="1", this is just // like a nillable single value, so treat it as such. // qName = getNillableQName(qName); } else if (!maxOccursValue.equals("1") || !minOccursValue.equals("1")) { String localPart = qName.getLocalPart(); String wrapped = (nillableValue != null && nillableValue.equals("true") ? " wrapped" : ""); String range = "["; if (!minOccursValue.equals("1")) { range += minOccursValue; } range += ","; if (!maxOccursValue.equals("1")) { range += maxOccursValue; } range += "]"; localPart += range + wrapped; qName = findQName(qName.getNamespaceURI(), localPart); } } } // A WSDL Part uses the element attribute instead of the ref attribute if (qName == null) { forElement.value = true; qName = getTypeQNameFromAttr(node, "element"); } // "base" references a "type" if (qName == null) { forElement.value = false; qName = getTypeQNameFromAttr(node, "base"); } return qName; } /** * Method getMemberTypeQNames * * @param node * @return */ public static QName[] getMemberTypeQNames(Node node) { String attribute = getAttribute(node, "memberTypes"); if (attribute == null) { return null; } StringTokenizer tokenizer = new StringTokenizer(attribute, " "); QName[] memberTypes = new QName[tokenizer.countTokens()]; for (int i = 0; tokenizer.hasMoreElements(); i++) { String element = (String) tokenizer.nextElement(); memberTypes[i] = XMLUtils.getFullQNameFromString(element, node); } return memberTypes; } /** * Gets the QName of the type of the node via the specified attribute * name. * <p/> * If "type", the QName represented by the type attribute's value is * returned. If the type attribute is not set, the anonymous type * or anyType is returned if no other type information is available. * Note that the QName returned in these cases is affected by * the presence of the nillable attribute. * <p/> * If "ref", the QName represented by the ref attribute's value is * returned. * <p/> * If "base" or "element", the QName represented by the base/element * attribute's value is returned. * * @param node in the dom * @param typeAttrName (type, base, element, ref) * @return */ private static QName getTypeQNameFromAttr(Node node, String typeAttrName) { if (node == null) { return null; } // Get the raw prefixed value String prefixedName = getAttribute(node, typeAttrName); // If "type" was specified but there is no type attribute, // check for an anonymous type. If no anonymous type // then the type is anyType. if ((prefixedName == null) && typeAttrName.equals("type")) { if ((getAttribute(node, "ref") == null) && (getAttribute(node, "base") == null) && (getAttribute(node, "element") == null)) { // Try getting the anonymous qname QName anonQName = SchemaUtils.getElementAnonQName(node); if (anonQName == null) { anonQName = SchemaUtils.getAttributeAnonQName(node); } if (anonQName != null) { return anonQName; } // Try returning anyType String localName = node.getLocalName(); if ((localName != null) && Constants.isSchemaXSD(node.getNamespaceURI()) && (localName.equals("element") || localName.equals("attribute"))) { return Constants.XSD_ANYTYPE; } } } // Return null if not found if (prefixedName == null) { return null; } // Change the prefixed name into a full qname QName qName = getQNameFromPrefixedName(node, prefixedName); // An alternate qname is returned if nillable // if (typeAttrName.equals("type")) { // if (JavaUtils.isTrueExplicitly(getAttribute(node, "nillable"))) { // qName = getNillableQName(qName); // } // } return qName; } /** * Convert a prefixed name into a qname * * @param node * @param prefixedName * @return */ public static QName getQNameFromPrefixedName(Node node, String prefixedName) { String localName = prefixedName.substring(prefixedName.lastIndexOf(":") + 1); String namespace = null; // Associate the namespace prefix with a namespace if (prefixedName.length() == localName.length()) { namespace = getScopedAttribute( node, "xmlns"); // Get namespace for unqualified reference } else { namespace = getScopedAttribute(node, "xmlns:" + prefixedName.substring(0, prefixedName.lastIndexOf(":"))); } return (findQName(namespace, localName)); } /** * This method returns a set of all types that are derived * from this type via an extension of a complexType * * @param type * @param symbolTable * @return */ public static HashSet getDerivedTypes(TypeEntry type, SymbolTable symbolTable) { HashSet types = (HashSet)symbolTable.derivedTypes.get(type); if (types != null) { return types; } types = new HashSet(); symbolTable.derivedTypes.put(type, types); if ((type != null) && (type.getNode() != null)) { getDerivedTypes(type, types, symbolTable); } else if (type != null && Constants.isSchemaXSD(type.getQName().getNamespaceURI()) && (type.getQName().getLocalPart().equals("anyType") || type.getQName().getLocalPart().equals("any"))) { // All types are derived from anyType, except anonymous ones final Collection typeValues = symbolTable.getTypeIndex().values(); types.addAll(typeValues); // Currently we are unable to mark anonymous types correctly. // So, this filtering has to wait until a fix is made. /* for (Iterator it = typeValues.iterator(); it.hasNext();) { SymTabEntry e = (SymTabEntry) it.next(); if (! e.getQName().getLocalPart().startsWith(SymbolTable.ANON_TOKEN)) types.add(e); } */ } return types; } // getNestedTypes /** * Method getDerivedTypes * * @param type * @param types * @param symbolTable */ private static void getDerivedTypes(TypeEntry type, HashSet types, SymbolTable symbolTable) { // If all types are in the set, return if (types.size() == symbolTable.getTypeEntryCount()) { return; } // Search the dictionary for derived types of type for (Iterator it = symbolTable.getTypeIndex().values().iterator(); it.hasNext();) { Type t = (Type) it.next(); if ((t instanceof DefinedType) && (t.getNode() != null) && !types.contains(t) && (((DefinedType) t).getComplexTypeExtensionBase(symbolTable) == type)) { types.add(t); getDerivedTypes(t, types, symbolTable); } } } // getDerivedTypes /** * This method returns a set of all the nested types. * Nested types are types declared within this TypeEntry (or descendents) * plus any extended types and the extended type nested types * The elements of the returned HashSet are Types. * * @param type is the type entry to consider * @param symbolTable is the symbolTable * @param derivedFlag should be set if all dependendent derived types should also be * returned. * @return */ protected static HashSet getNestedTypes(TypeEntry type, SymbolTable symbolTable, boolean derivedFlag) { HashSet types = new HashSet(); getNestedTypes(type, types, symbolTable, derivedFlag); return types; } // getNestedTypes /** * Method getNestedTypes * * @param type * @param types * @param symbolTable * @param derivedFlag */ private static void getNestedTypes(TypeEntry type, HashSet types, SymbolTable symbolTable, boolean derivedFlag) { if (type == null) { return; } // If all types are in the set, return if (types.size() == symbolTable.getTypeEntryCount()) { return; } // Process types derived from this type if (derivedFlag) { HashSet derivedTypes = getDerivedTypes(type, symbolTable); Iterator it = derivedTypes.iterator(); while (it.hasNext()) { TypeEntry derivedType = (TypeEntry) it.next(); if (!types.contains(derivedType)) { types.add(derivedType); getNestedTypes(derivedType, types, symbolTable, derivedFlag); } } } // Continue only if the node exists if (type.getNode() == null) { return; } Node node = type.getNode(); // Process types declared in this type Vector v = SchemaUtils.getContainedElementDeclarations(node, symbolTable); if (v != null) { for (int i = 0; i < v.size(); i++) { ElementDecl elem = (ElementDecl) v.get(i); if (!types.contains(elem.getType())) { types.add(elem.getType()); getNestedTypes(elem.getType(), types, symbolTable, derivedFlag); } } } // Process attributes declared in this type v = SchemaUtils.getContainedAttributeTypes(node, symbolTable); if (v != null) { for (int i = 0; i < v.size(); i++) { ContainedAttribute attr = (ContainedAttribute) v.get(i); TypeEntry te = attr.getType(); if (!types.contains(te)) { types.add(te); getNestedTypes(te, types, symbolTable, derivedFlag); } } } // Process referenced types if ((type.getRefType() != null) && !types.contains(type.getRefType())) { types.add(type.getRefType()); getNestedTypes(type.getRefType(), types, symbolTable, derivedFlag); } /* * Anonymous processing and should be automatically handled by the * reference processing above * // Get the anonymous type of the element * QName anonQName = SchemaUtils.getElementAnonQName(node); * if (anonQName != null) { * TypeEntry anonType = symbolTable.getType(anonQName); * if (anonType != null && !types.contains(anonType)) { * types.add(anonType); * } * } * * // Get the anonymous type of an attribute * anonQName = SchemaUtils.getAttributeAnonQName(node); * if (anonQName != null) { * TypeEntry anonType = symbolTable.getType(anonQName); * if (anonType != null && !types.contains(anonType)) { * types.add(anonType); * } * } */ // Process extended types TypeEntry extendType = SchemaUtils.getComplexElementExtensionBase(node, symbolTable); if (extendType != null) { if (!types.contains(extendType)) { types.add(extendType); getNestedTypes(extendType, types, symbolTable, derivedFlag); } } /* * Array component processing should be automatically handled by the * reference processing above. * // Process array components * QName componentQName = SchemaUtils.getArrayComponentQName(node, new IntHolder(0)); * TypeEntry componentType = symbolTable.getType(componentQName); * if (componentType == null) { * componentType = symbolTable.getElement(componentQName); * } * if (componentType != null) { * if (!types.contains(componentType)) { * types.add(componentType); * getNestedTypes(componentType, types, symbolTable, derivedFlag); * } * } */ } // getNestedTypes public static String getLastLocalPart(String localPart) { int anonymousDelimitorIndex = localPart.lastIndexOf('>'); if (anonymousDelimitorIndex > -1 && anonymousDelimitorIndex < localPart.length()-1) { localPart = localPart.substring(anonymousDelimitorIndex + 1); } return localPart; } /** * Get the QName that could be used in the xsi:type * when serializing an object of the given type. * * @param te is the type entry * @return the QName of the type's xsi type */ public static QName getXSIType(TypeEntry te) { QName xmlType = null; // If the TypeEntry describes an Element, get // the referenced Type. if ((te != null) && (te instanceof Element) && (te.getRefType() != null)) { te = te.getRefType(); } // If the TypeEntry is a CollectionTE, use // the TypeEntry representing the component Type // So for example a parameter that takes a // collection type for // <element name="A" type="xsd:string" maxOccurs="unbounded"/> // will be // new ParameterDesc(<QName of A>, IN, // <QName of xsd:string>, // String[]) if ((te != null) && (te instanceof CollectionTE) && (te.getRefType() != null)) { te = te.getRefType(); } if (te != null) { xmlType = te.getQName(); } return xmlType; } /** * Given a MIME type, return the AXIS-specific type QName. * * @param mimeName the MIME type name * @return the AXIS-specific QName for the MIME type */ public static QName getMIMETypeQName(String mimeName) { if ("text/plain".equals(mimeName)) { return Constants.MIME_PLAINTEXT; } else if ("image/gif".equals(mimeName) || "image/jpeg".equals(mimeName)) { return Constants.MIME_IMAGE; } else if ("text/xml".equals(mimeName) || "applications/xml".equals(mimeName)) { return Constants.MIME_SOURCE; } else if ("application/octet-stream".equals(mimeName) || "application/octetstream".equals(mimeName)) { return Constants.MIME_OCTETSTREAM; } else if ((mimeName != null) && mimeName.startsWith("multipart/")) { return Constants.MIME_MULTIPART; } else { return Constants.MIME_DATA_HANDLER; } } // getMIMEType /** * Get the QName that could be used in the xsi:type * when serializing an object for this parameter/return * * @param param is a parameter * @return the QName of the parameter's xsi type */ public static QName getXSIType(Parameter param) { if (param.getMIMEInfo() != null) { return getMIMETypeQName(param.getMIMEInfo().getType()); } return getXSIType(param.getType()); } // getXSIType /** * Are there any MIME parameters in the given binding? * * @param bEntry * @return */ public static boolean hasMIME(BindingEntry bEntry) { List operations = bEntry.getBinding().getBindingOperations(); for (int i = 0; i < operations.size(); ++i) { BindingOperation operation = (BindingOperation) operations.get(i); if (hasMIME(bEntry, operation)) { return true; } } return false; } // hasMIME /** * Are there any MIME parameters in the given binding's operation? * * @param bEntry * @param operation * @return */ public static boolean hasMIME(BindingEntry bEntry, BindingOperation operation) { Parameters parameters = bEntry.getParameters(operation.getOperation()); if (parameters != null) { for (int idx = 0; idx < parameters.list.size(); ++idx) { Parameter p = (Parameter) parameters.list.get(idx); if (p.getMIMEInfo() != null) { return true; } } } return false; } // hasMIME /** * Return the operation QName. The namespace is determined from * the soap:body namespace, if it exists, otherwise it is "". * * @param bindingOper the operation * @param bEntry the symbol table binding entry * @param symbolTable SymbolTable * @return the operation QName */ public static QName getOperationQName(BindingOperation bindingOper, BindingEntry bEntry, SymbolTable symbolTable) { Operation operation = bindingOper.getOperation(); String operationName = operation.getName(); // For the wrapped case, use the part element's name...which is // is the same as the operation name, but may have a different // namespace ? // example: // <part name="paramters" element="ns:myelem"> if ((bEntry.getBindingStyle() == Style.DOCUMENT) && symbolTable.isWrapped()) { Input input = operation.getInput(); if (input != null) { Map parts = input.getMessage().getParts(); if ((parts != null) && !parts.isEmpty()) { Iterator i = parts.values().iterator(); Part p = (Part) i.next(); return p.getElementName(); } } } String ns = null; // Get a namespace from the soap:body tag, if any // example: // <soap:body namespace="this_is_what_we_want" ..> BindingInput bindInput = bindingOper.getBindingInput(); if (bindInput != null) { Iterator it = bindInput.getExtensibilityElements().iterator(); while (it.hasNext()) { ExtensibilityElement elem = (ExtensibilityElement) it.next(); if (elem instanceof SOAPBody) { SOAPBody body = (SOAPBody) elem; ns = body.getNamespaceURI(); if (bEntry.getInputBodyType(operation) == Use.ENCODED && (ns == null || ns.length() == 0)) { log.warn(Messages.getMessage("badNamespaceForOperation00", bEntry.getName(), operation.getName())); } break; } else if (elem instanceof MIMEMultipartRelated) { Object part = null; javax.wsdl.extensions.mime.MIMEMultipartRelated mpr = (javax.wsdl.extensions.mime.MIMEMultipartRelated) elem; List l = mpr.getMIMEParts(); for (int j = 0; (l != null) && (j < l.size()) && (part == null); j++) { javax.wsdl.extensions.mime.MIMEPart mp = (javax.wsdl.extensions.mime.MIMEPart) l.get(j); List ll = mp.getExtensibilityElements(); for (int k = 0; (ll != null) && (k < ll.size()) && (part == null); k++) { part = ll.get(k); if (part instanceof SOAPBody) { SOAPBody body = (SOAPBody) part; ns = body.getNamespaceURI(); if (bEntry.getInputBodyType(operation) == Use.ENCODED && (ns == null || ns.length() == 0)) { log.warn(Messages.getMessage("badNamespaceForOperation00", bEntry.getName(), operation.getName())); } break; } else { part = null; } } } } else if (elem instanceof SOAP12Body) { ns = ((SOAP12Body)elem).getNamespaceURI(); } } } // If we didn't get a namespace from the soap:body, then // use "". We should probably use the targetNamespace, // but the target namespace of what? binding? portType? // Also, we don't have enough info for to get it. if (ns == null) { ns = ""; } return new QName(ns, operationName); } /** A simple map of the primitive types and their holder objects */ protected static HashMap TYPES = new HashMap(7); static { TYPES.put("int", "java.lang.Integer"); TYPES.put("float", "java.lang.Float"); TYPES.put("boolean", "java.lang.Boolean"); TYPES.put("double", "java.lang.Double"); TYPES.put("byte", "java.lang.Byte"); TYPES.put("short", "java.lang.Short"); TYPES.put("long", "java.lang.Long"); } /** * Return a "wrapper" type for the given type name. In other words, * if it's a primitive type ("int") return the java wrapper class * ("java.lang.Integer"). Otherwise return the type name itself. * * @param type * @return the name of a java wrapper class for the type, or the type's * name if it's not primitive. */ public static String getWrapperType(String type) { String ret = (String)TYPES.get(type); return (ret == null) ? type : ret; } /** * Determines if the DOM Node represents an xs:&lt;node&gt; */ public static boolean isXsNode (Node node, String nameName) { return (node.getLocalName().equals(nameName) && Constants.isSchemaXSD (node.getNamespaceURI ())); } }
7,732
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/PortEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.wsdl.Port; import javax.xml.namespace.QName; /** * This class represents the symbol table entry for a WSDL port. * * @author <a href="mailto:karl.guggisberg@guggis.ch">Karl Guggisberg</a> */ public class PortEntry extends SymTabEntry { /** the WSDL port element represented by this symbol table entry */ private Port port = null; /** * constructor * * @param port the WSDL port element */ public PortEntry(Port port) { super(new QName(port.getName())); this.port = port; } /** * replies the WSDL port element represented by this symbol table entry * * @return the WSDL port element represented by this symbol table entry */ public Port getPort() { return port; } }
7,733
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/UndefinedDelegate.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import java.io.IOException; import java.util.Vector; /** * This UndefinedDelegate class implements the common functions of UndefinedType and UndefinedElement. */ public class UndefinedDelegate implements Undefined { /** Field list */ private Vector list; /** Field undefinedType */ private TypeEntry undefinedType; /** * Constructor * * @param te */ UndefinedDelegate(TypeEntry te) { list = new Vector(); undefinedType = te; } /** * Register referrant TypeEntry so that * the code can update the TypeEntry when the Undefined Element or Type is defined * * @param referrant */ public void register(TypeEntry referrant) { list.add(referrant); } /** * Call update with the actual TypeEntry. This updates all of the * referrant TypeEntry's that were registered. * * @param def * @throws IOException */ public void update(TypeEntry def) throws IOException { boolean done = false; while (!done) { done = true; // Assume this is the last pass // Call updatedUndefined for all items on the list // updateUndefined returns true if the state of the te TypeEntry // is changed. The outer loop is traversed until there are no more // state changes. for (int i = 0; i < list.size(); i++) { TypeEntry te = (TypeEntry) list.elementAt(i); if (te.updateUndefined(undefinedType, def)) { done = false; // Items still undefined, need another pass } } } // It is possible that the def TypeEntry depends on an Undefined type. // If so, register all of the entries with the undefined type. TypeEntry uType = def.getUndefinedTypeRef(); if (uType != null) { for (int i = 0; i < list.size(); i++) { TypeEntry te = (TypeEntry) list.elementAt(i); ((Undefined) uType).register(te); } } } }
7,734
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/DefinedElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This Type is for a QName that is an element, these types are only emitted if * referenced by a ref= or an element=. * An element type can be defined inline or it can be defined via * a ref/type attribute. */ public class DefinedElement extends Element { /** * Create an element type defined by a ref/type attribute * * @param pqName * @param refType * @param pNode * @param dims */ public DefinedElement(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName, refType, pNode, dims); } /** * Create an element type defined directly. * * @param pqName * @param pNode */ public DefinedElement(QName pqName, Node pNode) { super(pqName, pNode); } }
7,735
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/MimeInfo.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; /** * Class MimeInfo * * @version %I%, %G% */ public class MimeInfo { /** Field type */ String type; /** Field dims */ String dims; /** * Constructor MimeInfo * * @param type * @param dims */ public MimeInfo(String type, String dims) { this.type = type; this.dims = dims; } /** * Method getDimensions * * @return */ public String getDimensions() { return this.dims; } /** * Method getType * * @return */ public String getType() { return this.type; } /** * Method toString * * @return */ public String toString() { return "(" + type + "," + dims + ")"; } }
7,736
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/SymTabEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * SymTabEntry is the base class for all symbol table entries. It contains four things: * - a QName * - space for a Writer-specific name (for example, in Wsdl2java, this will be the Java name) * - isReferenced flag indicating whether this entry is referenced by other entries * - dynamicVars; a mechanism for Writers to add additional context information onto entries. */ public abstract class SymTabEntry { // The QName of this entry is immutable. There is no setter for it. /** Field qname */ protected QName qname; // The name is Writer implementation dependent. For example, in Wsdl2java, this will become // the Java name. /** Field name */ protected String name; // Is this entry referenced by any other entry? /** Field isReferenced */ private boolean isReferenced = false; /** Field dynamicVars */ private HashMap dynamicVars = new HashMap(); /** * Construct a symbol table entry with the given QName. * * @param qname */ protected SymTabEntry(QName qname) { this.qname = qname; } // ctor /** * Get the QName of this entry. * * @return */ public final QName getQName() { return qname; } // getQName /** * Get the name of this entry. The name is Writer-implementation-dependent. For example, in * Wsdl2java, this will become the Java name. * * @return */ public String getName() { return name; } // getName /** * Set the name of this entry. This method is not called by the framework, it is only called * by the Writer implementation. * * @param name */ public void setName(String name) { this.name = name; } // setName /** * Is this entry referenced by any other entry in the symbol table? * * @return */ public final boolean isReferenced() { return isReferenced; } // isReferenced /** * Set the isReferenced variable, default value is true. * * @param isReferenced */ public final void setIsReferenced(boolean isReferenced) { this.isReferenced = isReferenced; } // setIsReferenced /** * There may be information that does not exist in WSDL4J/DOM * structures and does not exist in * our additional structures, but that Writer implementation * will need. This information is * most likely context-relative, so the DynamicVar map is * provided for the Writers to store and * retrieve their particular information. * * @param key * @return */ public Object getDynamicVar(Object key) { return dynamicVars.get(key); } // getDynamicVar /** * Method setDynamicVar * * @param key * @param value */ public void setDynamicVar(Object key, Object value) { dynamicVars.put(key, value); } // setDynamicVar /** * Collate the info in this object in string form. * * @return */ public String toString() { return toString(""); } // toString /** * Collate the info in this object in string form with indentation. * * @param indent * @return */ protected String toString(String indent) { StringBuffer buffer = new StringBuffer(); buffer.append(indent).append("QName: ").append(qname).append('\n'); buffer.append(indent).append("Class: ").append(this.getClass().getName()).append('\n'); buffer.append(indent).append("name: ").append(name).append('\n'); buffer.append(indent).append("isReferenced? ").append(isReferenced).append('\n'); String prefix = indent + "dynamicVars: "; Iterator entries = dynamicVars.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Object key = entry.getKey(); buffer.append(prefix).append(key).append(" = ").append(entry.getValue()).append('\n'); prefix = indent + " "; } return buffer.toString(); } // toString } // abstract class SymTabEntry
7,737
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/ServiceEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.wsdl.Service; /** * This class represents a WSDL service. It simply encompasses the WSDL4J Service object so it can * reside in the SymbolTable. */ public class ServiceEntry extends SymTabEntry { /** Field service */ private Service service; private String originalServiceName; /** * Construct a ServiceEntry from a WSDL4J Service object. * * @param service */ public ServiceEntry(Service service) { super(service.getQName()); this.service = service; } // ctor public String getOriginalServiceName(){ return this.originalServiceName; } public void setOriginalServiceName(String originalName){ this.originalServiceName = originalName; } /** * Get this entry's Service object. * * @return */ public Service getService() { return service; } // getService } // class ServiceEntry
7,738
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/ElementDecl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; /** * Simple utility struct for holding element declarations. * <p> * This simply correlates a QName to a TypeEntry. * * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@apache.org) */ public class ElementDecl extends ContainedEntry { /** Field documentation */ private String documentation; // The following property is set if minOccurs=0. // An item that is not set and has minOccurs=0 // should not be passed over the wire. This // is slightly different than nillable=true which // causes nil=true to be passed over the wire. /** Field minOccursIs0 */ private boolean minOccursIs0 = false; /** Field nillable */ private boolean nillable = false; /** Field optional */ private boolean optional = false; // Indicate if the ElementDecl represents // an xsd:any element /** Field anyElement */ private boolean anyElement = false; /** Field maxOccursIsUnbounded */ private boolean maxOccursIsUnbounded = false; private boolean maxOccursExactOne; /** * Constructor ElementDecl * * @param type * @param name */ public ElementDecl(TypeEntry type, QName name) { super(type, name); } /** * Method getMinOccursIs0 * * @return */ public boolean getMinOccursIs0() { return minOccursIs0; } /** * Method setMinOccursIs0 * * @param minOccursIs0 */ public void setMinOccursIs0(boolean minOccursIs0) { this.minOccursIs0 = minOccursIs0; } /** * Method getMaxOccursIsUnbounded * * @return */ public boolean getMaxOccursIsUnbounded() { return maxOccursIsUnbounded; } /** * Method setMaxOccursIsUnbounded * * @param maxOccursIsUnbounded */ public void setMaxOccursIsUnbounded(boolean maxOccursIsUnbounded) { this.maxOccursIsUnbounded = maxOccursIsUnbounded; } /** * Method getMaxOccursIsExactlyOne * * @return */ public boolean getMaxOccursIsExactlyOne() { return maxOccursExactOne; } /** * Method setMaxOccursIsExactlyOne * * @param exactOne */ public void setMaxOccursIsExactlyOne(boolean exactOne) { maxOccursExactOne = exactOne; } /** * Method setNillable * * @param nillable */ public void setNillable(boolean nillable) { this.nillable = nillable; } /** * Method getNillable * * @return */ public boolean getNillable() { return nillable; } /** * Method setOptional * * @param optional */ public void setOptional(boolean optional) { this.optional = optional; } /** * Method getOptional * * @return */ public boolean getOptional() { return optional; } /** * Method getAnyElement * * @return */ public boolean getAnyElement() { return anyElement; } /** * Method setAnyElement * * @param anyElement */ public void setAnyElement(boolean anyElement) { this.anyElement = anyElement; } /** * Method getDocumentation * * @return string */ public String getDocumentation() { return documentation; } /** * Method setDocumentation * @param documentation */ public void setDocumentation(String documentation) { this.documentation = documentation; } }
7,739
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/TypeEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.utils.Messages; import org.w3c.dom.Node; import javax.xml.namespace.QName; import java.io.IOException; import java.io.Serializable; import java.util.HashSet; import java.util.Vector; /** * This class represents a wsdl types entry that is supported by the WSDL2Java emitter. * A TypeEntry has a QName representing its XML name and a name, which in the * WSDL2Java back end is its full java name. The TypeEntry may also have a Node, * which locates the definition of the emit type in the xml. * A TypeEntry object extends SymTabEntry and is built by the SymbolTable class for * each supported root complexType, simpleType, and elements that are * defined or encountered. * <p> * SymTabEntry * | * TypeEntry * / \ * Type Element * | | * (BaseType, (DefinedElement, * CollectionType CollectionElement, * DefinedType, UndefinedElement) * UndefinedType) * <p> * UndefinedType and UndefinedElement are placeholders when the real type or element * is not encountered yet. Both of these implement the Undefined interface. * <p> * A TypeEntry whose java (or other language) name depends on an Undefined type, will * have its name initialization deferred until the Undefined type is replaced with * a defined type. The updateUndefined() method is invoked by the UndefinedDelegate to * update the information. * <p> * Each TypeEntry whose language name depends on another TypeEntry will have the refType * field set. For example: * &lt;element name="foo" type="bar" /&gt; * The TypeEntry for "foo" will have a refType set to the TypeEntry of "bar". * <p> * Another Example: * &lt;xsd:complexType name="hobbyArray"&gt; * &lt;xsd:complexContent&gt; * &lt;xsd:restriction base="soapenc:Array"&gt; * &lt;xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:string[]"/&gt; * &lt;/xsd:restriction&gt; * &lt;/xsd:complexContent&gt; * &lt;/xsd:complexType&gt; * The TypeEntry for "hobbyArray" will have a refType that locates the TypeEntry for xsd:string * and the dims field will be "[]" * * @author Rich Scheuerle (scheu@us.ibm.com) */ public abstract class TypeEntry extends SymTabEntry implements Serializable { /** Field node */ protected Node node; // Node /** Field refType */ protected TypeEntry refType; // Some TypeEntries refer to other types. /** Field dims */ protected String dims = ""; // If refType is an element, dims indicates // the array dims (for example "[]"). protected boolean underlTypeNillable = false; // if this is an array, underlTypeNillable indicates // whether the underlying type of the array is nillable. protected QName componentType = null; // If this is an array, the component type /** If this TypeEntry represents an array with elements inside a "wrapper" * this field can optionally change the inner QName (default is &lt;item&gt;). */ protected QName itemQName = null; /** Field undefined */ protected boolean undefined; // If refType is an Undefined type // (or has a refType that is Undefined) // then the undefined flag is set. // The name cannot be determined // until the Undefined type is found. /** Field isBaseType */ protected boolean isBaseType; // Indicates if represented by a // primitive or util class /** Field isSimpleType */ protected boolean isSimpleType = false; // Indicates if this type is a simple type /** Field onlyLiteralReference */ protected boolean onlyLiteralReference = false; // Indicates /** Field types */ protected HashSet types = null; /** contained elements in the schema's type definition */ protected Vector containedElements; /** contained attributes in the schema's type definition */ protected Vector containedAttributes; // whether this type is only referenced // via a binding's literal use. /** * Create a TypeEntry object for an xml construct that references another type. * Defer processing until refType is known. * * @param pqName * @param refType * @param pNode * @param dims */ protected TypeEntry(QName pqName, TypeEntry refType, Node pNode, String dims) { super(pqName); node = pNode; this.undefined = refType.undefined; this.refType = refType; if (dims == null) { dims = ""; } this.dims = dims; if (refType.undefined) { // Need to defer processing until known. TypeEntry uType = refType; while (!(uType instanceof Undefined)) { uType = uType.refType; } ((Undefined) uType).register(this); } else { isBaseType = (refType.isBaseType && refType.dims.equals("") && dims.equals("")); } } /** * Create a TypeEntry object for an xml construct that is not a base type * * @param pqName * @param pNode */ protected TypeEntry(QName pqName, Node pNode) { super(pqName); node = pNode; refType = null; undefined = false; dims = ""; isBaseType = false; } /** * Create a TypeEntry object for an xml construct name that represents a base type * * @param pqName */ protected TypeEntry(QName pqName) { super(pqName); node = null; undefined = false; dims = ""; isBaseType = true; } /** * Query the node for this type. * * @return */ public Node getNode() { return node; } /** * Returns the Base Type Name. * For example if the Type represents a schema integer, "int" is returned. * If this is a user defined type, null is returned. * * @return */ public String getBaseType() { if (isBaseType) { return name; } else { return null; } } /** * Method isBaseType * * @return */ public boolean isBaseType() { return isBaseType; } /** * Method setBaseType * * @param baseType */ public void setBaseType(boolean baseType) { isBaseType = baseType; } /** * Method isSimpleType * * @return */ public boolean isSimpleType() { return isSimpleType; } /** * Method setSimpleType * * @param simpleType */ public void setSimpleType(boolean simpleType) { isSimpleType = simpleType; } /** * Is this type references ONLY as a literal type? If a binding's * message's soapBody says: use="literal", then a type is referenced * literally. Note that that type's contained types (ie., an address * contains a phone#) are not referenced literally. Since a type * that is ONLY referenced as a literal may cause a generator to act * differently (like WSDL2Java), this extra reference distinction is * needed. * * @return */ public boolean isOnlyLiteralReferenced() { return onlyLiteralReference; } // isOnlyLiteralReferenced /** * Set the isOnlyLiteralReference flag. * * @param set */ public void setOnlyLiteralReference(boolean set) { onlyLiteralReference = set; } // setOnlyLiteralRefeerence /** * getUndefinedTypeRef returns the Undefined TypeEntry that this entry depends on or NULL. * * @return */ protected TypeEntry getUndefinedTypeRef() { if (this instanceof Undefined) { return this; } if (undefined && (refType != null)) { if (refType.undefined) { TypeEntry uType = refType; while (!(uType instanceof Undefined)) { uType = uType.refType; } return uType; } } return null; } /** * UpdateUndefined is called when the ref TypeEntry is finally known. * * @param oldRef The TypeEntry representing the Undefined TypeEntry * @param newRef The replacement TypeEntry * @return true if TypeEntry is changed in any way. * @throws IOException */ protected boolean updateUndefined(TypeEntry oldRef, TypeEntry newRef) throws IOException { boolean changedState = false; // Replace refType with the new one if applicable if (refType == oldRef) { refType = newRef; changedState = true; // Detect a loop TypeEntry te = refType; while ((te != null) && (te != this)) { te = te.refType; } if (te == this) { // Detected a loop. undefined = false; isBaseType = false; node = null; throw new IOException( Messages.getMessage( "undefinedloop00", getQName().toString())); } } // Update information if refType is now defined if ((refType != null) && undefined && (refType.undefined == false)) { undefined = false; changedState = true; isBaseType = (refType.isBaseType && refType.dims.equals("") && dims.equals("")); } return changedState; } /** * If this type references another type, return that type, otherwise return null. * * @return */ public TypeEntry getRefType() { return refType; } // getRefType /** * Method setRefType * * @param refType */ public void setRefType(TypeEntry refType) { this.refType = refType; } /** * Return the dimensions of this type, which can be 0 or more "[]". * * @return */ public String getDimensions() { return dims; } // getDimensions /** * Return whether the underlying type is nillable if this is an array type. * @return true if it is an array and nillable */ public boolean getUnderlTypeNillable() { // refType could refer to array with underlying nillable // type - set the underlTypeNillable to true if this is // the case. if (!underlTypeNillable && !getDimensions().equals("") && refType != null) { underlTypeNillable = refType.getUnderlTypeNillable(); } return underlTypeNillable; } /** * Set the boolean indicating whether underlying type of array is nillable. */ public void setUnderlTypeNillable(boolean underlTypeNillable) { this.underlTypeNillable = underlTypeNillable; } /** * Return the QName of the component if this is an array type * @return QName of array elements or null */ public QName getComponentType() { return componentType; } /** * Set the QName of the component if this is an array type */ public void setComponentType(QName componentType) { this.componentType = componentType; } public QName getItemQName() { return itemQName; } public void setItemQName(QName itemQName) { this.itemQName = itemQName; } /** * Get string representation with indentation * * @param indent * @return */ protected String toString(String indent) { String refString = indent + "RefType: null \n"; if (refType != null) { refString = indent + "RefType:\n" + refType.toString(indent + " ") + "\n"; } return super.toString(indent) + indent + "Base?: " + isBaseType + "\n" + indent + "Undefined?: " + undefined + "\n" + indent + "isSimpleType? " + isSimpleType + "\n" + indent + "Node: " + getNode() + "\n" + indent + "Dims: " + dims + "\n" + indent + "isOnlyLiteralReferenced: " + onlyLiteralReference + "\n" + refString; } /** * This method returns a set of all the nested types. * Nested types are types declared within this TypeEntry (or descendents) * plus any extended types and the extended type nested types * The elements of the returned HashSet are Types. * * @param symbolTable is the symbolTable * @param derivedFlag should be set if all dependendent derived types should also be * returned. * @return */ public HashSet getNestedTypes(SymbolTable symbolTable, boolean derivedFlag) { if( types == null) { types = Utils.getNestedTypes(this, symbolTable, derivedFlag); } return types; } // getNestedTypes /** * @return Returns the containedAttributes. */ public Vector getContainedAttributes() { return containedAttributes; } /** * @param containedAttributes The containedAttributes to set. */ public void setContainedAttributes(Vector containedAttributes) { this.containedAttributes = containedAttributes; } /** * @return Returns the containedElements. */ public Vector getContainedElements() { return containedElements; } /** * @param containedElements The containedElements to set. */ public void setContainedElements(Vector containedElements) { this.containedElements = containedElements; } }
7,740
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/FaultInfo.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.constants.Use; import org.apache.axis.utils.Messages; import javax.wsdl.Fault; import javax.wsdl.Message; import javax.wsdl.Part; import javax.wsdl.extensions.soap.SOAPHeaderFault; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Map; /** * Fault information object. This should probably really be FaultEntry and * it should be a subclass of SymTabEntry, but faults aren't first-class * objects in WSDL, so I'm not sure what the FaultEntry should contain and * how it should be constructed, so for now leave it as a simple object. */ public class FaultInfo { /** Field message */ private Message message; /** Field xmlType */ private QName xmlType; /** Field use */ private Use use; /** Field qName */ private QName qName; /** Field name */ private String name; /** * This constructor creates FaultInfo for a binding fault. * <p> * If the part of the fault is a type, then the QName is * derived from the element name and the provided namespace * (this namespace SHOULD come from the binding). * <p> * If the part of the fault is an element, then the QName is * the QName of the element, and the given namespace is ignored. * * @param fault * @param use * @param namespace * @param symbolTable */ public FaultInfo(Fault fault, Use use, String namespace, SymbolTable symbolTable) { this.message = fault.getMessage(); this.xmlType = getFaultType(symbolTable, getFaultPart()); this.use = (use != null) ? use : Use.LITERAL; this.name = fault.getName(); Part part = getFaultPart(); if (part == null) { this.qName = null; } else if (part.getTypeName() != null) { this.qName = new QName(namespace, part.getName()); } else { this.qName = part.getElementName(); } } // ctor /** * This constructor creates FaultInfo for a soap:headerFault. * * @param fault * @param symbolTable * @throws IOException */ public FaultInfo(SOAPHeaderFault fault, SymbolTable symbolTable) throws IOException { MessageEntry mEntry = symbolTable.getMessageEntry(fault.getMessage()); if (mEntry == null) { throw new IOException( Messages.getMessage("noMsg", fault.getMessage().toString())); } this.message = mEntry.getMessage(); Part part = message.getPart(fault.getPart()); this.xmlType = getFaultType(symbolTable, part); this.use = Use.getUse(fault.getUse()); if (part == null) { this.qName = null; } else if (part.getTypeName() != null) { this.qName = new QName(fault.getNamespaceURI(), part.getName()); } else { this.qName = part.getElementName(); } this.name = qName.getLocalPart(); } // ctor /** * Constructor FaultInfo * * @param faultMessage * @param faultPart * @param faultUse * @param faultNamespaceURI * @param symbolTable * @throws IOException */ public FaultInfo( QName faultMessage, String faultPart, String faultUse, String faultNamespaceURI, SymbolTable symbolTable) throws IOException { MessageEntry mEntry = symbolTable.getMessageEntry(faultMessage); if (mEntry == null) { throw new IOException(Messages.getMessage("noMsg", faultMessage.toString())); } this.message = mEntry.getMessage(); Part part = message.getPart(faultPart); this.xmlType = getFaultType(symbolTable, part); this.use = Use.getUse(faultUse); if (part == null) { this.qName = null; } else if (part.getTypeName() != null) { this.qName = new QName(faultNamespaceURI, part.getName()); } else { this.qName = part.getElementName(); } this.name = qName.getLocalPart(); } // ctor /** * Method getMessage * * @return */ public Message getMessage() { return message; } // getMessage /** * Method getXMLType * * @return */ public QName getXMLType() { return xmlType; } // getXMLType /** * Method getUse * * @return */ public Use getUse() { return use; } // getUse /** * Return the QName of a fault. This method may return null if no parts * are in the fault message. * <p> * If the part of the fault is a type, then the QName is * derived from the element name and the provided namespace * (this namespace SHOULD come from the binding). * <p> * If the part of the fault is an element, then the QName is * the QName of the element, and the given namespace is ignored. * * @return */ public QName getQName() { return qName; } // getQName /** * Return the name of the fault. * This is the name= attribute from a portType fault * or the localname of a header fault. * * @return */ public String getName() { return name; } // getName /** * It is assumed at this point that the fault message has only * 0 or 1 parts. If 0, return null. If 1, return it. * * @return */ private Part getFaultPart() { // get the name of the part Map parts = message.getParts(); // If no parts, skip it if (parts.size() == 0) { return null; } else { return (Part) parts.values().iterator().next(); } } /** * Get the XML type (QName) for a Fault - look in the (single) fault * part for type="" or element="" - if type, return the QName. If * element, return the reference type for the element. * * @param part the Fault to dig into * @param st the SymbolTable we're using * @return the XML type of the Fault's part, or null */ private QName getFaultType(SymbolTable st, Part part) { if (part != null) { if (part.getTypeName() != null) { return part.getTypeName(); } // Literal, so get the element's type TypeEntry entry = st.getElement(part.getElementName()); if ((entry != null) && (entry.getRefType() != null)) { return entry.getRefType().getQName(); } } return null; } }
7,741
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/BaseType.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; /** * This Type is for a QName represents a Base Type (i.e. xsd:string represents a java.lang.String) */ public class BaseType extends Type { /** * Constructor BaseType * * @param pqName */ public BaseType(QName pqName) { super(pqName); } }
7,742
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/SchemaUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.Constants; import org.apache.axis.i18n.Messages; import org.apache.axis.utils.JavaUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.namespace.QName; import javax.xml.rpc.holders.BooleanHolder; import javax.xml.rpc.holders.IntHolder; import javax.xml.rpc.holders.QNameHolder; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import java.io.IOException; /** * This class contains static utility methods specifically for schema type queries. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class SchemaUtils { /** Field VALUE_QNAME */ static final QName VALUE_QNAME = Utils.findQName("", "_value"); /** * This method checks mixed=true attribute is set either on * complexType or complexContent element. */ public static boolean isMixed(Node node) { // Expecting a schema complexType if (isXSDNode(node, "complexType")) { String mixed = ((Element)node).getAttribute("mixed"); if (mixed != null && mixed.length() > 0) { return ("true".equalsIgnoreCase(mixed) || "1".equals(mixed)); } // Under the complexType there could be complexContent with // mixed="true" NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent")) { mixed = ((Element)kid).getAttribute("mixed"); return ("true".equalsIgnoreCase(mixed) || "1".equals(mixed)); } } } return false; } public static Node getUnionNode(Node node) { // Expecting a schema complexType if (isXSDNode(node, "simpleType")) { // Under the simpleType there could be union NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "union")) { return kid; } } } return null; } public static Node getListNode(Node node) { // Expecting a schema simpleType if (isXSDNode(node, "simpleType")) { // Under the simpleType there could be list NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "list")) { return kid; } } } return null; } public static boolean isSimpleTypeWithUnion(Node node) { return (getUnionNode(node) != null); } /** * This method checks out if the given node satisfies the 3rd condition * of the "wrapper" style: * such an element (a wrapper) must be of a complex type defined using the * xsd:sequence compositor and containing only elements declarations. * (excerpt from JAX-RPC spec 1.1 Maintenanace Review 2 Chapter 6 Section 4.1.) * * @param node * @return */ public static boolean isWrappedType(Node node) { if (node == null) { return false; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); boolean hasComplexType = false; for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType")) { node = kid; hasComplexType = true; break; } } if (!hasComplexType) { return false; } } // Expecting a schema complexType if (isXSDNode(node, "complexType")) { // Under the complexType there could be complexContent/simpleContent // and extension elements if this is a derived type. // A wrapper element must be complex-typed. NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent")) { return false; } else if (isXSDNode(kid, "simpleContent")) { return false; } } // Under the complexType there may be choice, sequence, group and/or all nodes. // (There may be other #text nodes, which we will ignore). // The complex type of a wrapper element must have only sequence // and again element declarations in the sequence. children = node.getChildNodes(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("sequence")) { Node sequenceNode = kid; NodeList sequenceChildren = sequenceNode.getChildNodes(); int sequenceLen = sequenceChildren.getLength(); for (int k = 0; k < sequenceLen; k++) { Node sequenceKid = sequenceChildren.item(k); String sequenceLocalName = sequenceKid.getLocalName(); if (sequenceLocalName != null && Constants.isSchemaXSD(sequenceKid.getNamespaceURI())) { // allow choice with element children if (sequenceLocalName.equals("choice")) { Node choiceNode = sequenceKid; NodeList choiceChildren = choiceNode.getChildNodes(); int choiceLen = choiceChildren.getLength(); for (int l = 0; l < choiceLen; l++) { Node choiceKid = choiceChildren.item(l); String choiceLocalName = choiceKid.getLocalName(); if (choiceLocalName != null && Constants.isSchemaXSD(choiceKid.getNamespaceURI())) { if (!choiceLocalName.equals("element")) { return false; } } } } else if (!sequenceLocalName.equals("element")) { return false; } } } return true; } else { return false; } } } } // allows void type return true; } /** * If the specified node represents a supported JAX-RPC complexType or * simpleType, a Vector is returned which contains ElementDecls for the * child element names. * If the element is a simpleType, an ElementDecls is built representing * the restricted type with the special name "value". * If the element is a complexType which has simpleContent, an ElementDecl * is built representing the extended type with the special name "value". * This method does not return attribute names and types * (use the getContainedAttributeTypes) * If the specified node is not a supported * JAX-RPC complexType/simpleType/element null is returned. * * @param node * @param symbolTable * @return */ public static Vector getContainedElementDeclarations(Node node, SymbolTable symbolTable) { if (node == null) { return null; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType")) { node = kid; break; } } } // Expecting a schema complexType or simpleType if (isXSDNode(node, "complexType")) { // Under the complexType there could be complexContent/simpleContent // and extension elements if this is a derived type. Skip over these. NodeList children = node.getChildNodes(); Node complexContent = null; Node simpleContent = null; Node extension = null; for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent")) { complexContent = kid; break; // REMIND: should this be here or on either branch? } else if (isXSDNode(kid, "simpleContent")) { simpleContent = kid; } } if (complexContent != null) { children = complexContent.getChildNodes(); for (int j = 0; (j < children.getLength()) && (extension == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "extension") || isXSDNode(kid, "restriction")) { extension = kid; } } } if (simpleContent != null) { children = simpleContent.getChildNodes(); int len = children.getLength(); for (int j = 0; (j < len) && (extension == null); j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if ((localName != null) && (localName.equals("extension") || localName.equals("restriction")) && Constants.isSchemaXSD(kid.getNamespaceURI())) { // get the type of the extension/restriction from the "base" attribute QName extendsOrRestrictsTypeName = Utils.getTypeQName(children.item(j), new BooleanHolder(), false); TypeEntry extendsOrRestrictsType = symbolTable.getTypeEntry(extendsOrRestrictsTypeName, false); // If this type extends a simple type, then add the // special "value" ElementDecl, else this type is // extending another simpleContent type and will // already have a "value". if (extendsOrRestrictsType == null || extendsOrRestrictsType.isBaseType()) { // Return an element declaration with a fixed name // ("value") and the correct type. Vector v = new Vector(); ElementDecl elem = new ElementDecl(extendsOrRestrictsType, VALUE_QNAME); v.add(elem); return v; } else { // There can't be any other elements in a // simpleContent node. return null; } } } } if (extension != null) { node = extension; // Skip over complexContent and extension } // Under the complexType there may be choice, sequence, group and/or all nodes. // (There may be other #text nodes, which we will ignore). children = node.getChildNodes(); Vector v = new Vector(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("sequence")) { v.addAll(processSequenceNode(kid, symbolTable)); } else if (localName.equals("all")) { v.addAll(processAllNode(kid, symbolTable)); } else if (localName.equals("choice")) { v.addAll(processChoiceNode(kid, symbolTable)); } else if (localName.equals("group")) { v.addAll(processGroupNode(kid, symbolTable)); } } } return v; } else if (isXSDNode(node, "group")) { /* * Does this else clause make any sense anymore if * we're treating refs to xs:groups like a macro inclusion * into the referencing type? * Maybe this else clause should never be possible? * NodeList children = node.getChildNodes(); Vector v = new Vector(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("sequence")) { v.addAll(processSequenceNode(kid, symbolTable)); } else if (localName.equals("all")) { v.addAll(processAllNode(kid, symbolTable)); } else if (localName.equals("choice")) { v.addAll(processChoiceNode(kid, symbolTable)); } } } return v; */ return null; } else { // This may be a simpleType, return the type with the name "value" QName[] simpleQName = getContainedSimpleTypes(node); if (simpleQName != null) { Vector v = null; for (int i = 0; i < simpleQName.length; i++) { Type simpleType = symbolTable.getType(simpleQName[i]); if (simpleType != null) { if (v == null) { v = new Vector(); } QName qname = null; if (simpleQName.length > 1) { qname = new QName("", simpleQName[i].getLocalPart() + "Value"); } else { qname = new QName("", "value"); } v.add(new ElementDecl(simpleType, qname)); } } return v; } } return null; } /** * Invoked by getContainedElementDeclarations to get the child element types * and child element names underneath a Choice Node * * @param choiceNode * @param symbolTable * @return */ private static Vector processChoiceNode(Node choiceNode, SymbolTable symbolTable) { Vector v = new Vector(); NodeList children = choiceNode.getChildNodes(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("choice")) { v.addAll(processChoiceNode(kid, symbolTable)); } else if (localName.equals("sequence")) { v.addAll(processSequenceNode(kid, symbolTable)); } else if (localName.equals("group")) { v.addAll(processGroupNode(kid, symbolTable)); } else if (localName.equals("element")) { ElementDecl elem = processChildElementNode(kid, symbolTable); if (elem != null) { // XXX: forces minOccurs="0" so that a null choice // element can be serialized ok. elem.setMinOccursIs0(true); v.add(elem); } } else if (localName.equals("any")) { // Represent this as an element named any of type any type. // This will cause it to be serialized with the element // serializer. Type type = symbolTable.getType(Constants.XSD_ANY); ElementDecl elem = new ElementDecl(type, Utils.findQName("", "any")); elem.setAnyElement(true); v.add(elem); } } } return v; } /** * Returns named child node. * * @param parentNode Parent node. * @param name Element name of child node to return. */ private static Node getChildByName(Node parentNode, String name) throws DOMException { if (parentNode == null) return null; NodeList children = parentNode.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child != null) { if ((child.getNodeName() != null && (name.equals(child.getNodeName()))) || (child.getLocalName() != null && (name.equals(child.getLocalName())))) { return child; } } } } return null; } /** * Returns all textual nodes of a subnode defined by a parent node * and a path of element names to that subnode. * * @param root Parent node. * @param path Path of element names to text of interest, delimited by "/". */ public static String getTextByPath(Node root, String path) throws DOMException { StringTokenizer st = new StringTokenizer(path, "/"); Node node = root; while (st.hasMoreTokens()) { String elementName = st.nextToken(); Node child = getChildByName(node, elementName); if (child == null) throw new DOMException(DOMException.NOT_FOUND_ERR, "could not find " + elementName); node = child; } // should have found the node String text = ""; NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child != null) { if (child.getNodeName() != null && (child.getNodeName().equals("#text") || child.getNodeName().equals("#cdata-section"))) { text += child.getNodeValue(); } } } } return text; } /** * Returns the complete text of the child xsd:annotation/xsd:documentation * element from the provided node. Only the first annotation element and * the first documentation element in the annotation element will be used. * * @param typeNode Parent node. */ public static String getAnnotationDocumentation(Node typeNode) { Node annotationNode = typeNode.getFirstChild(); while (annotationNode != null) { if (isXSDNode(annotationNode, "annotation")) { break; } annotationNode = annotationNode.getNextSibling(); } Node documentationNode; if (annotationNode != null) { documentationNode = annotationNode.getFirstChild(); while (documentationNode != null) { if (isXSDNode(documentationNode, "documentation")) { break; } documentationNode = documentationNode.getNextSibling(); } } else { documentationNode = null; } // should have found the node if it exists String text = ""; if (documentationNode != null) { NodeList children = documentationNode.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child != null) { if (child.getNodeName() != null && (child.getNodeName().equals("#text") || child.getNodeName().equals("#cdata-section"))) { text += child.getNodeValue(); } } } } } return text; } /** * Invoked by getContainedElementDeclarations to get the child element types * and child element names underneath a Sequence Node * * @param sequenceNode * @param symbolTable * @return */ private static Vector processSequenceNode(Node sequenceNode, SymbolTable symbolTable) { Vector v = new Vector(); NodeList children = sequenceNode.getChildNodes(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("choice")) { v.addAll(processChoiceNode(kid, symbolTable)); } else if (localName.equals("sequence")) { v.addAll(processSequenceNode(kid, symbolTable)); } else if (localName.equals("group")) { v.addAll(processGroupNode(kid, symbolTable)); } else if (localName.equals("any")) { // Represent this as an element named any of type any type. // This will cause it to be serialized with the element // serializer. Type type = symbolTable.getType(Constants.XSD_ANY); ElementDecl elem = new ElementDecl(type, Utils.findQName("", "any")); elem.setAnyElement(true); v.add(elem); } else if (localName.equals("element")) { ElementDecl elem = processChildElementNode(kid, symbolTable); if (elem != null) { v.add(elem); } } } } return v; } /** * Invoked by getContainedElementDeclarations to get the child element types * and child element names underneath a group node. If a ref attribute is * specified, only the referenced group element is returned. * * @param groupNode * @param symbolTable * @return */ private static Vector processGroupNode(Node groupNode, SymbolTable symbolTable) { Vector v = new Vector(); if (groupNode.getAttributes().getNamedItem("ref") == null) { NodeList children = groupNode.getChildNodes(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); String localName = kid.getLocalName(); if (localName != null && Constants.isSchemaXSD(kid.getNamespaceURI())) { if (localName.equals("choice")) { v.addAll(processChoiceNode(kid, symbolTable)); } else if (localName.equals("sequence")) { v.addAll(processSequenceNode(kid, symbolTable)); } else if (localName.equals("all")) { v.addAll(processAllNode(kid, symbolTable)); } } } } else { QName nodeName = Utils.getNodeNameQName(groupNode); QName nodeType = Utils.getTypeQName(groupNode, new BooleanHolder(), false); // The value of the second argument is 'false' since global model group // definitions are always represented by objects whose type is // assignment compatible with 'org.apache.axis.wsdl.symbolTable.Type'. Type type = (Type) symbolTable.getTypeEntry(nodeType, false); if (type != null && type.getNode() != null) { //v.add(new ElementDecl(type, nodeName)); Node node = type.getNode(); NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { QName subNodeKind = Utils.getNodeQName(children.item(j)); if ((subNodeKind != null) && Constants.isSchemaXSD( subNodeKind.getNamespaceURI())) { if (subNodeKind.getLocalPart().equals("sequence")) { v.addAll(processSequenceNode(children.item(j), symbolTable)); } else if (subNodeKind.getLocalPart().equals("all")) { v.addAll(processAllNode(children.item(j), symbolTable)); } else if (subNodeKind.getLocalPart().equals("choice")) { v.addAll(processChoiceNode(children.item(j), symbolTable)); } } } } } return v; } /** * Invoked by getContainedElementDeclarations to get the child element types * and child element names underneath an all node. * * @param allNode * @param symbolTable * @return */ private static Vector processAllNode(Node allNode, SymbolTable symbolTable) { Vector v = new Vector(); NodeList children = allNode.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "element")) { ElementDecl elem = processChildElementNode(kid, symbolTable); if (elem != null) { v.add(elem); } } } return v; } /** * Invoked by getContainedElementDeclarations to get the child element type * and child element name for a child element node. * <p/> * If the specified node represents a supported JAX-RPC child element, * we return an ElementDecl containing the child element name and type. * * @param elementNode * @param symbolTable * @return */ private static ElementDecl processChildElementNode(Node elementNode, SymbolTable symbolTable) { // Get the name qnames. QName nodeName = Utils.getNodeNameQName(elementNode); BooleanHolder forElement = new BooleanHolder(); String comments = null; comments = getAnnotationDocumentation(elementNode); // The type qname is used to locate the TypeEntry, which is then // used to retrieve the proper java name of the type. QName nodeType = Utils.getTypeQName(elementNode, forElement, false); TypeEntry type = symbolTable.getTypeEntry(nodeType, forElement.value); // An element inside a complex type is either qualified or unqualified. // If the ref= attribute is used, the name of the ref'd element is used // (which must be a root element). If the ref= attribute is not // used, the name of the element is unqualified. if (!forElement.value) { // check the Form (or elementFormDefault) attribute of this node to // determine if it should be namespace quailfied or not. String form = Utils.getAttribute(elementNode, "form"); if ((form != null) && form.equals("unqualified")) { // Unqualified nodeName nodeName = Utils.findQName("", nodeName.getLocalPart()); } else if (form == null) { // check elementFormDefault on schema element String def = Utils.getScopedAttribute(elementNode, "elementFormDefault"); if ((def == null) || def.equals("unqualified")) { // Unqualified nodeName nodeName = Utils.findQName("", nodeName.getLocalPart()); } } } if (type != null) { ElementDecl elem = new ElementDecl(type, nodeName); elem.setDocumentation(comments); String minOccurs = Utils.getAttribute(elementNode, "minOccurs"); if ((minOccurs != null) && minOccurs.equals("0")) { elem.setMinOccursIs0(true); } String maxOccurs = Utils.getAttribute(elementNode, "maxOccurs"); if (maxOccurs != null) { if (maxOccurs.equals("unbounded")) { elem.setMaxOccursIsUnbounded(true); } else if(maxOccurs.equals("1")) { elem.setMaxOccursIsExactlyOne(true); } } else { elem.setMaxOccursIsExactlyOne(true); } elem.setNillable( JavaUtils.isTrueExplicitly( Utils.getAttribute(elementNode, "nillable"))); String useValue = Utils.getAttribute(elementNode, "use"); if (useValue != null) { elem.setOptional(useValue.equalsIgnoreCase("optional")); } return elem; } return null; } /** * Returns the WSDL2Java QName for the anonymous type of the element * or null. * * @param node * @return */ public static QName getElementAnonQName(Node node) { if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType") || isXSDNode(kid, "simpleType")) { return Utils.getNodeNameQName(kid); } } } return null; } /** * Returns the WSDL2Java QName for the anonymous type of the attribute * or null. * * @param node * @return */ public static QName getAttributeAnonQName(Node node) { if (isXSDNode(node, "attribute")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType") || isXSDNode(kid, "simpleType")) { return Utils.getNodeNameQName(kid); } } } return null; } /** * If the specified node is a simple type or contains simpleContent, return true * * @param node * @return */ public static boolean isSimpleTypeOrSimpleContent(Node node) { if (node == null) { return false; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType")) { node = kid; break; } else if (isXSDNode(kid, "simpleType")) { return true; } } } // Expecting a schema complexType or simpleType if (isXSDNode(node, "simpleType")) { return true; } if (isXSDNode(node, "complexType")) { // Under the complexType there could be complexContent/simpleContent // and extension elements if this is a derived type. Skip over these. NodeList children = node.getChildNodes(); Node complexContent = null; Node simpleContent = null; for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent")) { complexContent = kid; break; } else if (isXSDNode(kid, "simpleContent")) { simpleContent = kid; } } if (complexContent != null) { return false; } if (simpleContent != null) { return true; } } return false; } /** * Test whether <tt>node</tt> is not null, belongs to the XML * Schema namespace, and has a localName that matches * <tt>schemaLocalName</tt> * <p/> * This can be used to determine that a given Node defines a * schema "complexType" "element" and so forth. * * @param node a <code>Node</code> value * @param schemaLocalName a <code>String</code> value * @return true if the node is matches the name in the schema namespace. */ private static boolean isXSDNode(Node node, String schemaLocalName) { if (node == null) { return false; } String localName = node.getLocalName(); if (localName == null) { return false; } return (localName.equals(schemaLocalName) && Constants.isSchemaXSD(node.getNamespaceURI())); } /** * Look for the base type of node iff node is a complex type that has been * derived by restriction; otherwise return null. * * @param node * @param symbolTable * @return */ public static TypeEntry getComplexElementRestrictionBase(Node node, SymbolTable symbolTable) { if (node == null) { return null; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); Node complexNode = null; for (int j = 0; (j < children.getLength()) && (complexNode == null); j++) { if (isXSDNode(children.item(j), "complexType")) { complexNode = children.item(j); node = complexNode; } } } // Expecting a schema complexType if (isXSDNode(node, "complexType")) { // Under the complexType there could be should be a complexContent & // restriction elements if this is a derived type. NodeList children = node.getChildNodes(); Node content = null; Node restriction = null; for (int j = 0; (j < children.getLength()) && (content == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent") || isXSDNode(kid, "simpleContent")) { content = kid; } } if (content != null) { children = content.getChildNodes(); for (int j = 0; (j < children.getLength()) && (restriction == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "restriction")) { restriction = kid; } } } if (restriction == null) { return null; } else { // Get the QName of the extension base QName restrictionType = Utils.getTypeQName(restriction, new BooleanHolder(), false); if (restrictionType == null) { return null; } else { // Return associated Type return symbolTable.getType(restrictionType); } } } else { return null; } } /** * If the specified node represents a supported JAX-RPC complexType/element * which extends another complexType. The Type of the base is returned. * * @param node * @param symbolTable * @return */ public static TypeEntry getComplexElementExtensionBase(Node node, SymbolTable symbolTable) { if (node == null) { return null; } TypeEntry cached = (TypeEntry) symbolTable.node2ExtensionBase.get(node); if (cached != null) { return cached; // cache hit } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); Node complexNode = null; for (int j = 0; (j < children.getLength()) && (complexNode == null); j++) { if (isXSDNode(children.item(j), "complexType")) { complexNode = children.item(j); node = complexNode; } } } // Expecting a schema complexType if (isXSDNode(node, "complexType")) { // Under the complexType there could be should be a complexContent & // extension elements if this is a derived type. NodeList children = node.getChildNodes(); Node content = null; Node extension = null; for (int j = 0; (j < children.getLength()) && (content == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent") || isXSDNode(kid, "simpleContent")) { content = kid; } } if (content != null) { children = content.getChildNodes(); for (int j = 0; (j < children.getLength()) && (extension == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "extension")) { extension = kid; } } } if (extension == null) { cached = null; } else { // Get the QName of the extension base QName extendsType = Utils.getTypeQName(extension, new BooleanHolder(), false); if (extendsType == null) { cached = null; } else { // Return associated Type cached = symbolTable.getType(extendsType); } } } symbolTable.node2ExtensionBase.put(node, cached); return cached; } /** * If the specified node represents a 'normal' non-enumeration simpleType, * the QName of the simpleType base is returned. * * @param node * @return */ public static QName getSimpleTypeBase(Node node) { QName[] qname = getContainedSimpleTypes(node); if ((qname != null) && (qname.length > 0)) { return qname[0]; } return null; } /** * Method getContainedSimpleTypes * * @param node * @return */ public static QName[] getContainedSimpleTypes(Node node) { QName[] baseQNames = null; if (node == null) { return null; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (isXSDNode(children.item(j), "simpleType")) { node = children.item(j); break; } } } // Get the node kind, expecting a schema simpleType if (isXSDNode(node, "simpleType")) { // Under the simpleType there should be a restriction. // (There may be other #text nodes, which we will ignore). NodeList children = node.getChildNodes(); Node restrictionNode = null; Node unionNode = null; for (int j = 0; (j < children.getLength()) && (restrictionNode == null); j++) { if (isXSDNode(children.item(j), "restriction")) { restrictionNode = children.item(j); } else if (isXSDNode(children.item(j), "union")) { unionNode = children.item(j); } } // The restriction node indicates the type being restricted // (the base attribute contains this type). if (restrictionNode != null) { baseQNames = new QName[1]; baseQNames[0] = Utils.getTypeQName(restrictionNode, new BooleanHolder(), false); } if (unionNode != null) { baseQNames = Utils.getMemberTypeQNames(unionNode); } // Look for enumeration elements underneath the restriction node if ((baseQNames != null) && (restrictionNode != null) && (unionNode != null)) { NodeList enums = restrictionNode.getChildNodes(); for (int i = 0; i < enums.getLength(); i++) { if (isXSDNode(enums.item(i), "enumeration")) { // Found an enumeration, this isn't a // 'normal' simple type. return null; } } } } return baseQNames; } /** * Returns the contained restriction or extension node underneath * the specified node. Returns null if not found * * @param node * @return */ public static Node getRestrictionOrExtensionNode(Node node) { Node re = null; if (node == null) { return re; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node n = children.item(j); if (isXSDNode(n, "simpleType") || isXSDNode(n, "complexType") || isXSDNode(n, "simpleContent")) { node = n; break; } } } // Get the node kind, expecting a schema simpleType if (isXSDNode(node, "simpleType") || isXSDNode(node, "complexType")) { // Under the complexType there could be a complexContent. NodeList children = node.getChildNodes(); Node complexContent = null; if (node.getLocalName().equals("complexType")) { for (int j = 0; (j < children.getLength()) && (complexContent == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent") || isXSDNode(kid, "simpleContent")) { complexContent = kid; } } node = complexContent; } // Now get the extension or restriction node if (node != null) { children = node.getChildNodes(); for (int j = 0; (j < children.getLength()) && (re == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "extension") || isXSDNode(kid, "restriction")) { re = kid; } } } } return re; } /** * If the specified node represents an array encoding of one of the following * forms, then return the qname repesenting the element type of the array. * * @param node is the node * @param dims is the output value that contains the number of dimensions if return is not null * @param itemQName will end up containing the "inner" QName for a * wrapped literal array * @return QName or null */ public static QName getArrayComponentQName(Node node, IntHolder dims, BooleanHolder underlTypeNillable, QNameHolder itemQName, BooleanHolder forElement, SymbolTable symbolTable) { dims.value = 1; // assume 1 dimension underlTypeNillable.value = false; // assume underlying type is not nillable QName qName = getCollectionComponentQName(node, itemQName, forElement, symbolTable); if (qName == null) { qName = getArrayComponentQName_JAXRPC(node, dims, underlTypeNillable, symbolTable); } return qName; } /** * If the specified node represents an element that references a collection * then return the qname repesenting the component of the collection. * <p> * &lt;xsd:element name="alias" type="xsd:string" maxOccurs="unbounded"/&gt; * returns qname for"xsd:string" * <p> * &lt;xsd:complexType&gt; * &lt;xsd:sequence&gt; * &lt;xsd:element name="alias" type="xsd:string" maxOccurs="unbounded"/&gt; * &lt;/xsd:sequence&gt; * &lt;/xsd:complexType&gt; * returns qname for"xsd:string" * <p> * &lt;xsd:element ref="alias" maxOccurs="unbounded"/&gt; * returns qname for "alias" * * @param node is the Node * @return QName of the compoent of the collection */ public static QName getCollectionComponentQName(Node node, QNameHolder itemQName, BooleanHolder forElement, SymbolTable symbolTable) { // If we're going to turn "wrapped" arrays into types such that // <complexType><sequence> // <element name="foo" type="xs:string" maxOccurs="unbounded"/> // </sequence></complexType> // becomes just "String []", we need to keep track of the inner // element name "foo" in metadata... This flag indicates whether to // do so. boolean storeComponentQName = false; if (node == null) { return null; } if (itemQName != null && isXSDNode(node, "complexType")) { // If this complexType is a sequence of exactly one element // we will continue processing below using that element, and // let the type checking logic determine if this is an array // or not. Node sequence = SchemaUtils.getChildByName(node, "sequence"); if (sequence == null) { return null; } NodeList children = sequence.getChildNodes(); Node element = null; for (int i = 0; i < children.getLength(); i++) { if (children.item(i).getNodeType() == Node.ELEMENT_NODE) { if (element == null) { element = children.item(i); } else { return null; } } } if (element == null) { return null; } // OK, exactly one element child of <sequence>, // continue the processing using that element ... node = element; storeComponentQName = true; try { symbolTable.createTypeFromRef(node); } catch (IOException e) { throw new RuntimeException(Messages.getMessage("exception01",e.toString())); } } // If the node kind is an element, dive to get its type. if (isXSDNode(node, "element")) { // Compare the componentQName with the name of the // full name. If different, return componentQName QName componentTypeQName = Utils.getTypeQName(node, forElement, true); if (componentTypeQName != null) { QName fullQName = Utils.getTypeQName(node, forElement, false); if (!componentTypeQName.equals(fullQName)) { if (storeComponentQName) { String name = Utils.getAttribute(node, "name"); if (name != null) { // check elementFormDefault on schema element String def = Utils.getScopedAttribute(node, "elementFormDefault"); String namespace = ""; if ((def != null) && def.equals("qualified")) { namespace = Utils.getScopedAttribute(node, "targetNamespace"); } itemQName.value = new QName(namespace, name); } } return componentTypeQName; } } } return null; } /** * If the specified node represents an array encoding of one of the following * forms, then return the qname repesenting the element type of the array. * * @param node is the node * @param dims is the output value that contains the number of dimensions if return is not null * @return QName or null * <p/> * JAX-RPC Style 2: * <xsd:complexType name="hobbyArray"> * <xsd:complexContent> * <xsd:restriction base="soapenc:Array"> * <xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:string[]"/> * </xsd:restriction> * </xsd:complexContent> * </xsd:complexType> * <p/> * JAX-RPC Style 3: * <xsd:complexType name="petArray"> * <xsd:complexContent> * <xsd:restriction base="soapenc:Array"> * <xsd:sequence> * <xsd:element name="alias" type="xsd:string" maxOccurs="unbounded"/> * </xsd:sequence> * </xsd:restriction> * </xsd:complexContent> * </xsd:complexType> */ private static QName getArrayComponentQName_JAXRPC(Node node, IntHolder dims, BooleanHolder underlTypeNillable, SymbolTable symbolTable) { dims.value = 0; // Assume 0 underlTypeNillable.value = false; if (node == null) { return null; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType")) { node = kid; break; } } } // Get the node kind, expecting a schema complexType if (isXSDNode(node, "complexType")) { // Under the complexType there should be a complexContent. // (There may be other #text nodes, which we will ignore). NodeList children = node.getChildNodes(); Node complexContentNode = null; for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent") || isXSDNode(kid, "simpleContent")) { complexContentNode = kid; break; } } // Under the complexContent there should be a restriction. // (There may be other #text nodes, which we will ignore). Node restrictionNode = null; if (complexContentNode != null) { children = complexContentNode.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "restriction")) { restrictionNode = kid; break; } } } // The restriction node must have a base of soapenc:Array. QName baseType = null; if (restrictionNode != null) { baseType = Utils.getTypeQName(restrictionNode, new BooleanHolder(), false); if (baseType != null) { if (!baseType.getLocalPart().equals("Array") || !Constants.isSOAP_ENC(baseType.getNamespaceURI())) { if (!symbolTable.arrayTypeQNames.contains(baseType)) { baseType = null; // Did not find base=soapenc:Array } } } } // Under the restriction there should be an attribute OR a sequence/all group node. // (There may be other #text nodes, which we will ignore). Node groupNode = null; Node attributeNode = null; if (baseType != null) { children = restrictionNode.getChildNodes(); for (int j = 0; (j < children.getLength()) && (groupNode == null) && (attributeNode == null); j++) { Node kid = children.item(j); if (isXSDNode(kid, "sequence") || isXSDNode(kid, "all")) { groupNode = kid; if (groupNode.getChildNodes().getLength() == 0) { // This covers the rather odd but legal empty sequence. // <complexType name="ArrayOfString"> // <complexContent> // <restriction base="soapenc:Array"> // <sequence/> // <attribute ref="soapenc:arrayType" wsdl:arrayType="string[]"/> // </restriction> // </complexContent> // </complexType> groupNode = null; } } if (isXSDNode(kid, "attribute")) { // If the attribute node does not have ref="soapenc:arrayType" // then keep looking. BooleanHolder isRef = new BooleanHolder(); QName refQName = Utils.getTypeQName(kid, isRef, false); if ((refQName != null) && isRef.value && refQName.getLocalPart().equals("arrayType") && Constants.isSOAP_ENC( refQName.getNamespaceURI())) { attributeNode = kid; } } } } // If there is an attribute node, look at wsdl:arrayType to get the element type if (attributeNode != null) { String wsdlArrayTypeValue = null; Vector attrs = Utils.getAttributesWithLocalName(attributeNode, "arrayType"); for (int i = 0; (i < attrs.size()) && (wsdlArrayTypeValue == null); i++) { Node attrNode = (Node) attrs.elementAt(i); String attrName = attrNode.getNodeName(); QName attrQName = Utils.getQNameFromPrefixedName(attributeNode, attrName); if (Constants.isWSDL(attrQName.getNamespaceURI())) { wsdlArrayTypeValue = attrNode.getNodeValue(); } } // The value could have any number of [] or [,] on the end // Strip these off to get the prefixed name. // The convert the prefixed name into a qname. // Count the number of [ and , to get the dim information. if (wsdlArrayTypeValue != null) { int i = wsdlArrayTypeValue.indexOf('['); if (i > 0) { String prefixedName = wsdlArrayTypeValue.substring(0, i); String mangledString = wsdlArrayTypeValue.replace(',', '['); dims.value = 0; int index = mangledString.indexOf('['); while (index > 0) { dims.value++; index = mangledString.indexOf('[', index + 1); } return Utils.getQNameFromPrefixedName(restrictionNode, prefixedName); } } } else if (groupNode != null) { // Get the first element node under the group node. NodeList elements = groupNode.getChildNodes(); Node elementNode = null; for (int i = 0; (i < elements.getLength()) && (elementNode == null); i++) { Node kid = elements.item(i); if (isXSDNode(kid, "element")) { elementNode = elements.item(i); break; } } // The element node should have maxOccurs="unbounded" and // a type if (elementNode != null) { String underlTypeNillableValue = Utils.getAttribute(elementNode, "nillable"); if (underlTypeNillableValue != null && underlTypeNillableValue.equals("true")) { underlTypeNillable.value = true; } String maxOccursValue = Utils.getAttribute(elementNode, "maxOccurs"); if ((maxOccursValue != null) && maxOccursValue.equalsIgnoreCase("unbounded")) { // Get the QName of the type without considering maxOccurs dims.value = 1; return Utils.getTypeQName(elementNode, new BooleanHolder(), true); } } } } return null; } /** * adds an attribute node's type and name to the vector * helper used by getContainedAttributeTypes * * @param v * @param child * @param symbolTable */ private static void addAttributeToVector(Vector v, Node child, SymbolTable symbolTable) { // Get the name and type qnames. // The type qname is used to locate the TypeEntry, which is then // used to retrieve the proper java name of the type. QName attributeName = Utils.getNodeNameQName(child); BooleanHolder forElement = new BooleanHolder(); QName attributeType = Utils.getTypeQName(child, forElement, false); // An attribute is either qualified or unqualified. // If the ref= attribute is used, the name of the ref'd element is used // (which must be a root element). If the ref= attribute is not // used, the name of the attribute is unqualified. if (!forElement.value) { // check the Form (or attributeFormDefault) attribute of // this node to determine if it should be namespace // quailfied or not. String form = Utils.getAttribute(child, "form"); if ((form != null) && form.equals("unqualified")) { // Unqualified nodeName attributeName = Utils.findQName("", attributeName.getLocalPart()); } else if (form == null) { // check attributeFormDefault on schema element String def = Utils.getScopedAttribute(child, "attributeFormDefault"); if ((def == null) || def.equals("unqualified")) { // Unqualified nodeName attributeName = Utils.findQName("", attributeName.getLocalPart()); } } } else { attributeName = attributeType; } // Get the corresponding TypeEntry from the symbol table TypeEntry type = symbolTable.getTypeEntry(attributeType, forElement.value); // Try to get the corresponding global attribute ElementEntry // from the symbol table. if (type instanceof org.apache.axis.wsdl.symbolTable.Element) { type = ((org.apache.axis.wsdl.symbolTable.Element) type).getRefType(); } // add type and name to vector, skip it if we couldn't parse it // XXX - this may need to be revisited. if ((type != null) && (attributeName != null)) { ContainedAttribute attr = new ContainedAttribute(type, attributeName); String useValue = Utils.getAttribute(child, "use"); if (useValue != null) { attr.setOptional(useValue.equalsIgnoreCase("optional")); } v.add(attr); } } /** * adds an attribute to the vector * helper used by addAttributeGroupToVector * * @param v * @param symbolTable * @param type * @param name */ private static void addAttributeToVector(Vector v, SymbolTable symbolTable, QName type, QName name) { TypeEntry typeEnt = symbolTable.getTypeEntry(type, false); if (typeEnt != null) // better not be null { v.add(new ContainedAttribute(typeEnt, name)); } } /** * adds each attribute group's attribute node to the vector * helper used by getContainedAttributeTypes * * @param v * @param attrGrpnode * @param symbolTable */ private static void addAttributeGroupToVector(Vector v, Node attrGrpnode, SymbolTable symbolTable) { // get the type of the attributeGroup QName attributeGroupType = Utils.getTypeQName(attrGrpnode, new BooleanHolder(), false); TypeEntry type = symbolTable.getTypeEntry(attributeGroupType, false); if (type != null) { if (type.getNode() != null) { // for each attribute or attributeGroup defined in the attributeGroup... NodeList children = type.getNode().getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node kid = children.item(j); if (isXSDNode(kid, "attribute")) { addAttributeToVector(v, kid, symbolTable); } else if (isXSDNode(kid, "attributeGroup")) { addAttributeGroupToVector(v, kid, symbolTable); } } } else if (type.isBaseType()) { // soap/encoding is treated as a "known" schema // so let's act like we know it if (type.getQName().equals(Constants.SOAP_COMMON_ATTRS11)) { // 1.1 commonAttributes contains two attributes addAttributeToVector(v, symbolTable, Constants.XSD_ID, new QName(Constants.URI_SOAP11_ENC, "id")); addAttributeToVector(v, symbolTable, Constants.XSD_ANYURI, new QName(Constants.URI_SOAP11_ENC, "href")); } else if (type.getQName().equals( Constants.SOAP_COMMON_ATTRS12)) { // 1.2 commonAttributes contains one attribute addAttributeToVector(v, symbolTable, Constants.XSD_ID, new QName(Constants.URI_SOAP12_ENC, "id")); } else if (type.getQName().equals( Constants.SOAP_ARRAY_ATTRS11)) { // 1.1 arrayAttributes contains two attributes addAttributeToVector(v, symbolTable, Constants.XSD_STRING, new QName(Constants.URI_SOAP12_ENC, "arrayType")); addAttributeToVector(v, symbolTable, Constants.XSD_STRING, new QName(Constants.URI_SOAP12_ENC, "offset")); } else if (type.getQName().equals( Constants.SOAP_ARRAY_ATTRS12)) { // 1.2 arrayAttributes contains two attributes // the type of "arraySize" is really "2003soapenc:arraySize" // which is rather of a hairy beast that is not yet supported // in Axis, so let's just use string; nobody should care for // now because arraySize wasn't used at all up until this // bug 23145 was fixed, which had nothing to do, per se, with // adding support for arraySize addAttributeToVector(v, symbolTable, Constants.XSD_STRING, new QName(Constants.URI_SOAP12_ENC, "arraySize")); addAttributeToVector(v, symbolTable, Constants.XSD_QNAME, new QName(Constants.URI_SOAP12_ENC, "itemType")); } } } } /** * Return the attribute names and types if any in the node * The even indices are the attribute types (TypeEntry) and * the odd indices are the corresponding names (Strings). * <p> * Example: * &lt;complexType name="Person"&gt; * &lt;sequence&gt; * &lt;element minOccurs="1" maxOccurs="1" name="Age" type="double" /&gt; * &lt;element minOccurs="1" maxOccurs="1" name="ID" type="xsd:float" /&gt; * &lt;/sequence&gt; * &lt;attribute name="Name" type="string" /&gt; * &lt;attribute name="Male" type="boolean" /&gt; * &lt;attributeGroup ref="s0:MyAttrSet" /&gt; * &lt;/complexType&gt; * * @param node * @param symbolTable * @return */ public static Vector getContainedAttributeTypes(Node node, SymbolTable symbolTable) { Vector v = null; // return value if (node == null) { return null; } // Check for SimpleContent // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexType")) { node = kid; break; } } } // Expecting a schema complexType if (isXSDNode(node, "complexType")) { // Under the complexType there could be complexContent/simpleContent // and extension elements if this is a derived type. Skip over these. NodeList children = node.getChildNodes(); Node content = null; int len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); if (isXSDNode(kid, "complexContent") || isXSDNode(kid, "simpleContent")) { content = kid; break; } } // Check for extensions or restrictions if (content != null) { children = content.getChildNodes(); len = children.getLength(); for (int j = 0; j < len; j++) { Node kid = children.item(j); if (isXSDNode(kid, "extension") || isXSDNode(kid, "restriction")) { node = kid; break; } } } // examine children of the node for <attribute> elements children = node.getChildNodes(); len = children.getLength(); for (int i = 0; i < len; i++) { Node child = children.item(i); if (isXSDNode(child, "attributeGroup")) { if (v == null) { v = new Vector(); } addAttributeGroupToVector(v, child, symbolTable); } else if (isXSDNode(child, "anyAttribute")) { // do nothing right now if (v == null) { v = new Vector(); } } else if (isXSDNode(child, "attribute")) { // we have an attribute if (v == null) { v = new Vector(); } addAttributeToVector(v, child, symbolTable); } } } return v; } // list of all of the XSD types in Schema 2001 /** Field schemaTypes[] */ private static String schemaTypes[] = { "string", "normalizedString", "token", "byte", "unsignedByte", "base64Binary", "hexBinary", "integer", "positiveInteger", "negativeInteger", "nonNegativeInteger", "nonPositiveInteger", "int", "unsignedInt", "long", "unsignedLong", "short", "unsignedShort", "decimal", "float", "double", "boolean", "time", "dateTime", "duration", "date", "gMonth", "gYear", "gYearMonth", "gDay", "gMonthDay", "Name", "QName", "NCName", "anyURI", "language", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NOTATION", "NMTOKEN", "NMTOKENS", "anySimpleType" }; /** Field schemaTypeSet */ private static final Set schemaTypeSet = new HashSet(Arrays.asList(schemaTypes)); /** * Determine if a string is a simple XML Schema type * * @param s * @return */ private static boolean isSimpleSchemaType(String s) { if (s == null) { return false; } return schemaTypeSet.contains(s); } /** * Determine if a QName is a simple XML Schema type * * @param qname * @return */ public static boolean isSimpleSchemaType(QName qname) { if ((qname == null) || !Constants.isSchemaXSD(qname.getNamespaceURI())) { return false; } return isSimpleSchemaType(qname.getLocalPart()); } /** * Returns the base type of a given type with its symbol table. * This logic is extracted from JavaTypeWriter's constructor() method * for reusing. * * @param type * @param symbolTable * @return */ public static TypeEntry getBaseType(TypeEntry type, SymbolTable symbolTable) { Node node = type.getNode(); TypeEntry base = getComplexElementExtensionBase( node, symbolTable); if (base == null) { base = getComplexElementRestrictionBase(node, symbolTable); } if (base == null) { QName baseQName = getSimpleTypeBase(node); if (baseQName != null) { base = symbolTable.getType(baseQName); } } return base; } /** * Returns whether the specified node represents a &lt;xsd:simpleType&gt; * with a nested &lt;xsd:list itemType="..."&gt;. * @param node * @return */ public static boolean isListWithItemType(Node node) { return getListItemType(node) != null; } /** * Returns the value of itemType attribute of &lt;xsd:list&gt; in &lt;xsd:simpleType&gt; * @param node * @return */ public static QName getListItemType(Node node) { if (node == null) { return null; } // If the node kind is an element, dive into it. if (isXSDNode(node, "element")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (isXSDNode(children.item(j), "simpleType")) { node = children.item(j); break; } } } // Get the node kind, expecting a schema simpleType if (isXSDNode(node, "simpleType")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (isXSDNode(children.item(j), "list")) { Node listNode = children.item(j); org.w3c.dom.Element listElement = (org.w3c.dom.Element) listNode; String type = listElement.getAttribute("itemType"); if (type.equals("")) { Node localType = null; children = listNode.getChildNodes(); for (j = 0; j < children.getLength() && localType == null; j++) { if (isXSDNode(children.item(j), "simpleType")) { localType = children.item(j); } } if (localType != null) { return getSimpleTypeBase(localType); } return null; } //int colonIndex = type.lastIndexOf(":"); //if (colonIndex > 0) { //type = type.substring(colonIndex + 1); //} //return new QName(Constants.URI_2001_SCHEMA_XSD, type + "[]"); return Utils.getQNameFromPrefixedName(node, type); } } } return null; } }
7,743
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/BackslashUtil.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; /** * @author dbyrne * * Created in response to AXIS-2088. This class exposes a handful of static utility * methods that are used to manipulate backslash chars w/in the context of QName objects. * */ public class BackslashUtil implements java.io.Serializable { /** * @param suspectQName QName[local] that may contain unescaped backslashes * @return QName[local] w/ no backslashes */ public static QName getQNameWithBackslashlessLocal(QName suspectQName) { String trustedString = null; // get a wsdl:service[@name] that we can trust trustedString = stripBackslashes(suspectQName.getLocalPart()); return getQNameWithDifferentLocal(suspectQName, trustedString); } /** * @param suspectQName QName[local] which may contain unescaped backslashes * @return QName[local] w/ escaped backslashes */ public static QName getQNameWithBackslashedLocal(QName suspectQName) { String trustedString = null; // get a wsdl:service[@name] with safe backslashes trustedString = applyBackslashes(suspectQName.getLocalPart()); return getQNameWithDifferentLocal(suspectQName, trustedString); } /** * Creates a copy of the supplied QName w/ the supplied local name */ public static QName getQNameWithDifferentLocal(QName qName, String localName) { QName trustedQName = null; // recreate the QName, only w/ a local name we can trust. trustedQName = new QName(qName.getNamespaceURI(), localName, qName.getPrefix()); return trustedQName; } /** * Slave method for getQNameWithBackslashedLocal() */ public static String applyBackslashes(String string) { return transformBackslashes(string, false); } /** * Slave method for getQNameWithBackslashlessLocal */ public static String stripBackslashes(String string) { return transformBackslashes(string, true); } /** * Slave method for applyBackslashes &amp; stripBackslashes . * */ public static String transformBackslashes(String string, boolean delete) { byte[] suspectBytes = null; StringBuffer stringBuffer = null; suspectBytes = string.getBytes(); stringBuffer = new StringBuffer(string); for (int b = suspectBytes.length - 1; b >= 0; b--) { if (suspectBytes[b] == 92) { if(delete){ stringBuffer.delete(b, b + 1); }else{ stringBuffer.insert(b, "\\"); } } } return stringBuffer.toString(); } }
7,744
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/WSDLLocatorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.wsdl.symbolTable; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.wsdl.xml.WSDLLocator; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; class WSDLLocatorAdapter implements WSDLLocator { /** * Contains a set of schemas that are always resolved locally. {@link SymbolTable} actually * doesn't need to read these schemas, and it will not read them if they are imported without * specifying a <tt>schemaLocation</tt> (see {@link SymbolTable#isKnownNamespace(String)}). * However, WSDL4J insists on loading them whenever they are references by a * <tt>schemaLocation</tt>. */ private final static Map/*<String,URL>*/ localSchemas; private final String baseURI; private final EntityResolver entityResolver; private String latestImportURI; static { localSchemas = new HashMap(); localSchemas.put("http://www.w3.org/2001/xml.xsd", WSDLLocatorAdapter.class.getResource("xml.xsd")); localSchemas.put("http://schemas.xmlsoap.org/soap/encoding/", WSDLLocatorAdapter.class.getResource("soap-encoding.xsd")); } WSDLLocatorAdapter(String baseURI, EntityResolver entityResolver) { this.baseURI = baseURI; this.entityResolver = entityResolver; } private InputSource getInputSource(String uri) { URL localSchema = (URL)localSchemas.get(uri); if (localSchema != null) { InputSource is; try { is = new InputSource(localSchema.openStream()); } catch (IOException ex) { return null; } is.setSystemId(uri); return is; } else { try { InputSource is = entityResolver.resolveEntity(null, uri); return is != null ? is : new InputSource(uri); } catch (SAXException ex) { return null; } catch (IOException ex) { return null; } } } public InputSource getBaseInputSource() { return getInputSource(baseURI); } public String getBaseURI() { return baseURI; } public InputSource getImportInputSource(String parentLocation, String importLocation) { if (parentLocation == null) { latestImportURI = importLocation; } else { try { latestImportURI = new URI(parentLocation).resolve(importLocation).toString(); } catch (URISyntaxException ex) { return null; } } return getInputSource(latestImportURI); } public String getLatestImportURI() { return latestImportURI; } public void close() { } }
7,745
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/ContainedEntry.java
package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; public class ContainedEntry extends SymTabEntry { protected TypeEntry type; // TypeEntry for nested type /** * @param qname */ protected ContainedEntry(TypeEntry type, QName qname) { super(qname); this.type = type; } /** * @return Returns the type. */ public TypeEntry getType() { return type; } /** * @param type The type to set. */ public void setType(TypeEntry type) { this.type = type; } }
7,746
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/Parameters.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.wsdl.OperationType; import java.util.Map; import java.util.Vector; /** * This class simply collects all the parameter or message data for an operation into one place. */ public class Parameters { /** The MEP for this operation (default is request-response) */ public OperationType mep = OperationType.REQUEST_RESPONSE; // This vector contains instances of the Parameter class /** Field list */ public Vector list = new Vector(); // The return info is stored as a Parameter. /** Field returnParam */ public Parameter returnParam = null; // A map of the faults /** Field faults */ public Map faults = null; // The signature that the interface and the stub will use /** Field signature */ public String signature = null; // The numbers of the respective parameters /** Field inputs */ public int inputs = 0; /** Field inouts */ public int inouts = 0; /** Field outputs */ public int outputs = 0; /** * Method toString * * @return */ public String toString() { return "\nreturnParam = " + returnParam + "\nfaults = " + faults + "\nsignature = " + signature + "\n(inputs, inouts, outputs) = (" + inputs + ", " + inouts + ", " + outputs + ")" + "\nlist = " + list; } // toString } // class Parameters
7,747
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/BindingEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import javax.wsdl.Binding; import javax.wsdl.Operation; import javax.wsdl.extensions.soap.SOAPFault; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * This class represents a WSDL binding. It encompasses the WSDL4J Binding object so it can * reside in the SymbolTable. It also adds a few bits of information that are a nuisance to get * from the WSDL4J Binding object: binding type, binding style, input/output/fault body types. */ public class BindingEntry extends SymTabEntry { // Binding types /** Field TYPE_SOAP */ public static final int TYPE_SOAP = 0; /** Field TYPE_HTTP_GET */ public static final int TYPE_HTTP_GET = 1; /** Field TYPE_HTTP_POST */ public static final int TYPE_HTTP_POST = 2; /** Field TYPE_UNKNOWN */ public static final int TYPE_UNKNOWN = 3; // Binding Operation use types /** Field USE_ENCODED */ public static final int USE_ENCODED = 0; /** Field USE_LITERAL */ public static final int USE_LITERAL = 1; /** Field binding */ private Binding binding; /** Field bindingType */ private int bindingType; /** Field bindingStyle */ private Style bindingStyle; /** Field hasLiteral */ private boolean hasLiteral; /** Field attributes */ private HashMap attributes; // operation to parameter info (Parameter) /** Field parameters */ private HashMap parameters = new HashMap(); // BindingOperation to faults (ArrayList of FaultBodyType) /** Field faults */ private HashMap faults = new HashMap(); // This is a map of a map. It's a map keyed on operation name whose values // are maps keyed on parameter name. The ultimate values are simple Strings. /** Field mimeTypes */ private Map mimeTypes; // This is a map of a map. It's a map keyed on operation name whose values // are maps keyed on part name. The ultimate values are simple // Booleans. /** Field headerParts */ private Map headerParts; // List of operations at need to use DIME /** Field dimeOps */ private ArrayList dimeOps = new ArrayList(); /** * Construct a BindingEntry from a WSDL4J Binding object and the additional binding info: * binding type, binding style, whether there is any literal binding, and the attributes which * contain the input/output/fault body type information. * * @param binding * @param bindingType * @param bindingStyle * @param hasLiteral * @param attributes * @param mimeTypes * @param headerParts */ public BindingEntry(Binding binding, int bindingType, Style bindingStyle, boolean hasLiteral, HashMap attributes, Map mimeTypes, Map headerParts) { super(binding.getQName()); this.binding = binding; this.bindingType = bindingType; this.bindingStyle = bindingStyle; this.hasLiteral = hasLiteral; if (attributes == null) { this.attributes = new HashMap(); } else { this.attributes = attributes; } if (mimeTypes == null) { this.mimeTypes = new HashMap(); } else { this.mimeTypes = mimeTypes; } if (headerParts == null) { this.headerParts = new HashMap(); } else { this.headerParts = headerParts; } } // ctor /** * This is a minimal constructor. Everything will be set up with * defaults. If the defaults aren't desired, then the appropriate * setter method should be called. The defaults are: * bindingType = TYPE_UNKNOWN * bindingStyle = DOCUMENT * hasLiteral = false * operation inputBodyTypes = USE_ENCODED * operation outputBodyTypes = USE_ENCODED * operation faultBodyTypes = USE_ENCODED * mimeTypes = null * <p> * The caller of this constructor should * also call the various setter methods to fully fill out this object: * setBindingType, setBindingStyle, setHasLiteral, setAttribute, * setMIMEType. * * @param binding */ public BindingEntry(Binding binding) { super(binding.getQName()); this.binding = binding; this.bindingType = TYPE_UNKNOWN; this.bindingStyle = Style.DOCUMENT; this.hasLiteral = false; this.attributes = new HashMap(); this.mimeTypes = new HashMap(); this.headerParts = new HashMap(); } // ctor /** * Get the Parameters object for the given operation. * * @param operation * @return */ public Parameters getParameters(Operation operation) { return (Parameters) parameters.get(operation); } // getParameters /** * Get all of the parameters for all operations. * * @return */ public HashMap getParameters() { return parameters; } // getParameters /** * Set the parameters for all operations * * @param parameters */ public void setParameters(HashMap parameters) { this.parameters = parameters; } /** * Get the mime mapping for the given parameter name. * If there is none, this returns null. * * @param operationName * @param parameterName * @return */ public MimeInfo getMIMEInfo(String operationName, String parameterName) { Map opMap = (Map) mimeTypes.get(operationName); if (opMap == null) { return null; } else { return (MimeInfo) opMap.get(parameterName); } } // getMIMEType /** * Get the MIME types map. * * @return */ public Map getMIMETypes() { return mimeTypes; } // getMIMETypes /** * Set the mime mapping for the given parameter name. * * @param operationName * @param parameterName * @param type * @param dims */ public void setMIMEInfo(String operationName, String parameterName, String type, String dims) { Map opMap = (Map) mimeTypes.get(operationName); if (opMap == null) { opMap = new HashMap(); mimeTypes.put(operationName, opMap); } opMap.put(parameterName, new MimeInfo(type, dims)); } // setMIMEType /** * Mark the operation as a DIME operation * * @param operationName */ public void setOperationDIME(String operationName) { if (dimeOps.indexOf(operationName) == -1) { dimeOps.add(operationName); } } /** * Check if this operation should use DIME * * @param operationName * @return */ public boolean isOperationDIME(String operationName) { return (dimeOps.indexOf(operationName) >= 0); } /** * Is this part an input header part?. * * @param operationName * @param partName * @return */ public boolean isInHeaderPart(String operationName, String partName) { return (headerPart(operationName, partName) & IN_HEADER) > 0; } // isInHeaderPart /** * Is this part an output header part?. * * @param operationName * @param partName * @return */ public boolean isOutHeaderPart(String operationName, String partName) { return (headerPart(operationName, partName) & OUT_HEADER) > 0; } // isInHeaderPart /** Get the flag indicating what sort of header this part is. */ public static final int NO_HEADER = 0; /** Field IN_HEADER */ public static final int IN_HEADER = 1; /** Field OUT_HEADER */ public static final int OUT_HEADER = 2; /** * Get the mime mapping for the given part name. * If there is none, this returns null. * * @param operationName * @param partName * @return flag indicating kind of header */ private int headerPart(String operationName, String partName) { Map opMap = (Map) headerParts.get(operationName); if (opMap == null) { return NO_HEADER; } else { Integer I = (Integer) opMap.get(partName); return (I == null) ? NO_HEADER : I.intValue(); } } // headerPart /** * Get the header parameter map. * * @return */ public Map getHeaderParts() { return headerParts; } // getHeaderParts /** * Set the header part mapping for the given part name. * * @param operationName * @param partName * @param headerFlags */ public void setHeaderPart(String operationName, String partName, int headerFlags) { Map opMap = (Map) headerParts.get(operationName); if (opMap == null) { opMap = new HashMap(); headerParts.put(operationName, opMap); } Integer I = (Integer) opMap.get(partName); int i = (I == null) ? headerFlags : (I.intValue() | headerFlags); opMap.put(partName, new Integer(i)); } // setHeaderPart /** * Get this entry's WSDL4J Binding object. * * @return */ public Binding getBinding() { return binding; } // getBinding /** * Get this entry's binding type. One of BindingEntry.TYPE_SOAP, BindingEntry.TYPE_HTTP_GET, * BindingEntry.TYPE_HTTP_POST. * * @return */ public int getBindingType() { return bindingType; } // getBindingType /** * Set this entry's binding type. * * @param bindingType */ protected void setBindingType(int bindingType) { if ((bindingType >= TYPE_SOAP) && (bindingType <= TYPE_UNKNOWN)) { } this.bindingType = bindingType; } // setBindingType /** * Get this entry's binding style. * * @return */ public Style getBindingStyle() { return bindingStyle; } // getBindingStyle /** * Set this entry's binding style. * * @param bindingStyle */ protected void setBindingStyle(Style bindingStyle) { this.bindingStyle = bindingStyle; } // setBindingStyle /** * Do any of the message stanzas contain a soap:body which uses literal? * * @return */ public boolean hasLiteral() { return hasLiteral; } // hasLiteral /** * Set the literal flag. * * @param hasLiteral */ protected void setHasLiteral(boolean hasLiteral) { this.hasLiteral = hasLiteral; } // setHashLiteral /** * Get the input body type for the given operation. * * @param operation * @return */ public Use getInputBodyType(Operation operation) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { return Use.ENCODED; // should really create an exception for this. } else { return attr.getInputBodyType(); } } // getInputBodyType /** * Set the input body type for the given operation. * * @param operation * @param inputBodyType */ protected void setInputBodyType(Operation operation, Use inputBodyType) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { attr = new OperationAttr(); attributes.put(operation, attr); } attr.setInputBodyType(inputBodyType); if (inputBodyType == Use.LITERAL) { setHasLiteral(true); } } // setInputBodyType /** * Get the output body type for the given operation. * * @param operation * @return */ public Use getOutputBodyType(Operation operation) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { return Use.ENCODED; // should really create an exception for this. } else { return attr.getOutputBodyType(); } } // getOutputBodyType /** * Set the output body type for the given operation. * * @param operation * @param outputBodyType */ protected void setOutputBodyType(Operation operation, Use outputBodyType) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { attr = new OperationAttr(); attributes.put(operation, attr); } attr.setOutputBodyType(outputBodyType); if (outputBodyType == Use.LITERAL) { setHasLiteral(true); } } // setOutputBodyType /** * Set the body type for the given operation. If input is true, * then this is the inputBodyType, otherwise it's the outputBodyType. * (NOTE: this method exists to enable reusing some SymbolTable code. * * @param operation * @param bodyType * @param input */ protected void setBodyType(Operation operation, Use bodyType, boolean input) { if (input) { setInputBodyType(operation, bodyType); } else { setOutputBodyType(operation, bodyType); } } // setBodyType /** * Get the fault body type for the given fault of the given operation. * * @param operation * @param faultName * @return Use.ENCODED or Use.LITERAL */ public Use getFaultBodyType(Operation operation, String faultName) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { return Use.ENCODED; // should really create an exception for this. } else { HashMap m = attr.getFaultBodyTypeMap(); SOAPFault soapFault = (SOAPFault) m.get(faultName); // This should never happen (error thrown in SymbolTable) if (soapFault == null) { return Use.ENCODED; } String use = soapFault.getUse(); if ("literal".equals(use)) { return Use.LITERAL; } return Use.ENCODED; } } /** * Return the map of BindingOperations to ArraList of FaultBodyType * * @return */ public HashMap getFaults() { return faults; } /** * Method setFaults * * @param faults */ public void setFaults(HashMap faults) { this.faults = faults; } /** * Get a {@link Set} of comprised {@link Operation} objects. * * @return */ public Set getOperations() { return attributes.keySet(); } /** * Set the fault body type map for the given operation. * * @param operation * @param faultBodyTypeMap */ protected void setFaultBodyTypeMap(Operation operation, HashMap faultBodyTypeMap) { OperationAttr attr = (OperationAttr) attributes.get(operation); if (attr == null) { attr = new OperationAttr(); attributes.put(operation, attr); } attr.setFaultBodyTypeMap(faultBodyTypeMap); } // setInputBodyTypeMap /** * Contains attributes for Operations * - Body type: encoded or literal */ protected static class OperationAttr { /** Field inputBodyType */ private Use inputBodyType; /** Field outputBodyType */ private Use outputBodyType; /** Field faultBodyTypeMap */ private HashMap faultBodyTypeMap; /** * Constructor OperationAttr * * @param inputBodyType * @param outputBodyType * @param faultBodyTypeMap */ public OperationAttr(Use inputBodyType, Use outputBodyType, HashMap faultBodyTypeMap) { this.inputBodyType = inputBodyType; this.outputBodyType = outputBodyType; this.faultBodyTypeMap = faultBodyTypeMap; } /** * Constructor OperationAttr */ public OperationAttr() { this.inputBodyType = Use.ENCODED; this.outputBodyType = Use.ENCODED; this.faultBodyTypeMap = null; } /** * Method getInputBodyType * * @return */ public Use getInputBodyType() { return inputBodyType; } /** * Method setInputBodyType * * @param inputBodyType */ protected void setInputBodyType(Use inputBodyType) { this.inputBodyType = inputBodyType; } /** * Method getOutputBodyType * * @return */ public Use getOutputBodyType() { return outputBodyType; } /** * Method setOutputBodyType * * @param outputBodyType */ protected void setOutputBodyType(Use outputBodyType) { this.outputBodyType = outputBodyType; } /** * Method getFaultBodyTypeMap * * @return */ public HashMap getFaultBodyTypeMap() { return faultBodyTypeMap; } /** * Method setFaultBodyTypeMap * * @param faultBodyTypeMap */ protected void setFaultBodyTypeMap(HashMap faultBodyTypeMap) { this.faultBodyTypeMap = faultBodyTypeMap; } } // class OperationAttr } // class BindingEntry
7,748
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/UndefinedType.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; import java.io.IOException; /** * This represents a QName found in a reference but is not defined. * If the type is later defined, the UndefinedType is replaced with a new Type */ public class UndefinedType extends Type implements Undefined { /** Field delegate */ private UndefinedDelegate delegate = null; /** * Construct a referenced (but as of yet undefined) type * * @param pqName */ public UndefinedType(QName pqName) { super(pqName, null); undefined = true; delegate = new UndefinedDelegate(this); } /** * Register referrant TypeEntry so that * the code can update the TypeEntry when the Undefined Element or Type is defined * * @param referrant */ public void register(TypeEntry referrant) { delegate.register(referrant); } /** * Call update with the actual TypeEntry. This updates all of the * referrant TypeEntry's that were registered. * * @param def * @throws IOException */ public void update(TypeEntry def) throws IOException { delegate.update(def); } }
7,749
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/CollectionType.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import org.w3c.dom.Node; import javax.xml.namespace.QName; /** * This Type is for a QName that is a 'collection'. * For example, * &lt;element name="foo" type="bar" maxOccurs="unbounded" /&gt; * We need a way to indicate in the symbol table that a foo is * 'collection of bars', In such cases a collection type is * added with the special QName &lt;name&gt;[&lt;minOccurs&gt;, &lt;maxOccurs&gt;] */ public class CollectionType extends DefinedType implements CollectionTE { /** Field wrapped */ private boolean wrapped; /** * Constructor CollectionType * * @param pqName * @param refType * @param pNode * @param dims */ public CollectionType(QName pqName, TypeEntry refType, Node pNode, String dims, boolean wrapped) { super(pqName, refType, pNode, dims); this.wrapped = wrapped; } public boolean isWrapped() { return wrapped; } }
7,750
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/PortTypeEntry.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.wsdl.PortType; /** * This class represents a WSDL portType. It encompasses the WSDL4J PortType object so it can * reside in the SymbolTable. It also adds the parameter information, which is missing from the * WSDL4J PortType object. */ public class PortTypeEntry extends SymTabEntry { /** Field portType */ private PortType portType; /** * Construct a PortTypeEntry from a WSDL4J PortType object and a HashMap of Parameters objects, * keyed off of the operation name. * * @param portType */ public PortTypeEntry(PortType portType) { super(portType.getQName()); this.portType = portType; } // ctor /** * Get this entry's PortType object. * * @return */ public PortType getPortType() { return portType; } // getPortType } // class PortTypeEntry
7,751
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/symbolTable/UndefinedElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.symbolTable; import javax.xml.namespace.QName; import java.io.IOException; /** * This represents a QName found in a reference but is not defined. * If the type is later defined, the UndefinedType is replaced with a new Type */ public class UndefinedElement extends Element implements Undefined { /** Field delegate */ private UndefinedDelegate delegate = null; /** * Construct a referenced (but as of yet undefined) element * * @param pqName */ public UndefinedElement(QName pqName) { super(pqName, null); undefined = true; delegate = new UndefinedDelegate(this); } /** * Register referrant TypeEntry so that * the code can update the TypeEntry when the Undefined Element or Type is defined * * @param referrant */ public void register(TypeEntry referrant) { delegate.register(referrant); } /** * Call update with the actual TypeEntry. This updates all of the * referrant TypeEntry's that were registered. * * @param def * @throws IOException */ public void update(TypeEntry def) throws IOException { delegate.update(def); } }
7,752
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/fromJava/Namespaces.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.fromJava; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.net.URL; import java.net.MalformedURLException; /** * <p>Description: A HashMap of packageNames and namespaces with some helper methods </p> * * @author rkumar@borland.com */ public class Namespaces extends HashMap { /** Field prefixCount */ private int prefixCount = 1; /** Field namespacePrefixMap */ private HashMap namespacePrefixMap = null; /** * Constructor Namespaces */ public Namespaces() { super(); namespacePrefixMap = new HashMap(); } /** * Get the namespaace for the given package If there is no entry in the HashMap for * this namespace, create one. * * @param key String representing packagename * @return the namespace either created or existing */ public String getCreate(String key) { Object value = super.get(key); if (value == null) { value = makeNamespaceFromPackageName(key); put(key, value, null); } return (String) value; } /** * Get the namespaace for the given package If there is no entry in the HashMap for * this namespace, create one. * * @param key String representing packagename * @param prefix the prefix to use for the generated namespace * @return the namespace either created or existing */ public String getCreate(String key, String prefix) { Object value = super.get(key); if (value == null) { value = makeNamespaceFromPackageName(key); put(key, value, prefix); } return (String) value; } /** * adds an entry to the packagename/namespace HashMap. In addition, * also makes an entry in the auxillary namespace/prefix HashMap if an * entry doesn't already exists * * @param key packageName String * @param value namespace value * @param prefix the prefix to use for the given namespace * @return old value for the specified key */ public Object put(Object key, Object value, String prefix) { if (prefix != null) { namespacePrefixMap.put(value, prefix); } else { getCreatePrefix((String) value); } return super.put(key, value); } /** * adds an entry to the packagename/namespace HashMap * for each of the entry in the map. In addition, also add an entries in the * auxillary namespace/prefix HashMap * * @param map packageName/namespace map */ public void putAll(Map map) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); put(entry.getKey(), entry.getValue(), null); } } /** * Get the prefix for the given namespace. If one exists, create one * * @param namespace namespace * @return prefix String */ public String getCreatePrefix(String namespace) { if (namespacePrefixMap.get(namespace) == null) { namespacePrefixMap.put(namespace, "tns" + prefixCount++); } return (String) namespacePrefixMap.get(namespace); } /** * put the gine namespace / prefix into the appropriate HashMap * * @param namespace * @param prefix */ public void putPrefix(String namespace, String prefix) { namespacePrefixMap.put(namespace, prefix); } /** * adds an entry to the namespace / prefix HashMap * for each of the entry in the map. * * @param map packageName/namespace map */ public void putAllPrefix(Map map) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); put(entry.getKey(), entry.getValue()); } } /** * Make namespace from a fully qualified class name * use the default protocol for the namespace * * @param clsName fully qualified class name * @return namespace namespace String */ public static String makeNamespace(String clsName) { return makeNamespace(clsName, "http"); } /** * Make namespace from a fully qualified class name * and the given protocol * * @param clsName fully qualified class name * @param protocol protocol String * @return namespace namespace String */ public static String makeNamespace(String clsName, String protocol) { if (clsName.startsWith("[L")) { clsName = clsName.substring(2, clsName.length() - 1); } if (clsName.lastIndexOf('.') == -1) { return protocol + "://" + "DefaultNamespace"; } String packageName = clsName.substring(0, clsName.lastIndexOf('.')); return makeNamespaceFromPackageName(packageName, protocol); } /** * Reverse the process. Get the package name from the namespace. * @param namespace * @return */ public static String getPackage(String namespace) { try { URL url = new URL(namespace); StringTokenizer st = new StringTokenizer(url.getHost(), "."); String[] words = new String[st.countTokens()]; for (int i = 0; i < words.length; ++i) { words[i] = st.nextToken(); } StringBuffer sb = new StringBuffer(80); for (int i = words.length - 1; i >= 0; --i) { String word = words[i]; // seperate with dot if (i != words.length - 1) { sb.append('.'); } sb.append(word); } String pkg = sb.toString(); if (pkg.equals("DefaultNamespace")) { return ""; } return pkg; } catch (MalformedURLException e) { } return null; } /** * Method makeNamespaceFromPackageName * * @param packageName * @return */ private static String makeNamespaceFromPackageName(String packageName) { return makeNamespaceFromPackageName(packageName, "http"); } /** * Method makeNamespaceFromPackageName * * @param packageName * @param protocol * @return */ private static String makeNamespaceFromPackageName(String packageName, String protocol) { if ((packageName == null) || packageName.equals("")) { return protocol + "://" + "DefaultNamespace"; } StringTokenizer st = new StringTokenizer(packageName, "."); String[] words = new String[st.countTokens()]; for (int i = 0; i < words.length; ++i) { words[i] = st.nextToken(); } StringBuffer sb = new StringBuffer(80); for (int i = words.length - 1; i >= 0; --i) { String word = words[i]; // seperate with dot if (i != words.length - 1) { sb.append('.'); } sb.append(word); } return protocol + "://" + sb.toString(); } /** * Get the list of namespaces currently registered * * @return iterator */ public Iterator getNamespaces() { return namespacePrefixMap.keySet().iterator(); } }
7,753
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/fromJava/Types.java
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.fromJava; import org.apache.axis.AxisFault; import org.apache.axis.AxisProperties; import org.apache.axis.Constants; import org.apache.axis.InternalException; import org.apache.axis.MessageContext; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.Serializer; import org.apache.axis.encoding.SerializerFactory; import org.apache.axis.encoding.SimpleType; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.ser.BeanSerializerFactory; import org.apache.axis.encoding.ser.EnumSerializerFactory; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.axis.utils.StringUtils; import org.apache.axis.wsdl.symbolTable.BaseTypeMapping; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.wsdl.Definition; import javax.wsdl.WSDLException; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; import javax.xml.rpc.holders.Holder; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * This class is used to recursively serializes a Java Class into * an XML Schema representation. * <p> * It has utility methods to create a schema node, assosiate namespaces to the various types * * @author unascribed */ public class Types { /** Field log */ protected static Log log = LogFactory.getLog(Types.class.getName()); /** Field def */ Definition def; /** Field namespaces */ Namespaces namespaces = null; /** Field tm */ TypeMapping tm; /** Field defaultTM */ TypeMapping defaultTM; /** Field targetNamespace */ String targetNamespace; /** Field wsdlTypesElem */ Element wsdlTypesElem = null; /** Field schemaTypes */ HashMap schemaTypes = null; /** Field schemaElementNames */ HashMap schemaElementNames = null; /** Field schemaUniqueElementNames */ HashMap schemaUniqueElementNames = null; /** Field wrapperMap */ HashMap wrapperMap = new HashMap(); /** Field stopClasses */ List stopClasses = null; /** Field beanCompatErrs */ List beanCompatErrs = new ArrayList(); /** Field serviceDesc */ private ServiceDesc serviceDesc = null; /** Keep track of the element QNames we've written to avoid dups */ private Set writtenElementQNames = new HashSet(); /** Which types have we already written? */ Class [] mappedTypes = null; /** The java to wsdl emitter */ Emitter emitter = null; public static boolean isArray(Class clazz) { return clazz.isArray() || java.util.Collection.class.isAssignableFrom(clazz); } private static Class getComponentType(Class clazz) { if (clazz.isArray()) { return clazz.getComponentType(); } else if (java.util.Collection.class.isAssignableFrom(clazz)) { return Object.class; } else { return null; } } /** * This class serailizes a <code>Class</code> to XML Schema. The constructor * provides the context for the streamed node within the WSDL document * * @param def WSDL Definition Element to declare namespaces * @param tm TypeMappingRegistry to handle known types * @param defaultTM default TM * @param namespaces user defined or autogenerated namespace and prefix maps * @param targetNamespace targetNamespace of the document * @param stopClasses * @param serviceDesc */ public Types(Definition def, TypeMapping tm, TypeMapping defaultTM, Namespaces namespaces, String targetNamespace, List stopClasses, ServiceDesc serviceDesc) { this.def = def; this.serviceDesc = serviceDesc; createDocumentFragment(); this.tm = tm; this.defaultTM = defaultTM; mappedTypes = tm.getAllClasses(); this.namespaces = namespaces; this.targetNamespace = targetNamespace; this.stopClasses = stopClasses; schemaElementNames = new HashMap(); schemaUniqueElementNames = new HashMap(); schemaTypes = new HashMap(); } /** * This class serailizes a <code>Class</code> to XML Schema. The constructor * provides the context for the streamed node within the WSDL document * * @param def WSDL Definition Element to declare namespaces * @param tm TypeMappingRegistry to handle known types * @param defaultTM default TM * @param namespaces user defined or autogenerated namespace and prefix maps * @param targetNamespace targetNamespace of the document * @param stopClasses * @param serviceDesc * @param emitter Java2Wsdl emitter */ public Types(Definition def, TypeMapping tm, TypeMapping defaultTM, Namespaces namespaces, String targetNamespace, List stopClasses, ServiceDesc serviceDesc, Emitter emitter) { this(def, tm, defaultTM, namespaces, targetNamespace, stopClasses, serviceDesc); this.emitter = emitter; } /** * Return the namespaces object for the current context * * @return */ public Namespaces getNamespaces() { return namespaces; } /** * Loads the types from the input schema file. * * @param inputSchema file or URL * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void loadInputSchema(String inputSchema) throws IOException, WSDLException, SAXException, ParserConfigurationException { // Read the input wsdl file into a Document Document doc = XMLUtils.newDocument(inputSchema); // Ensure that the root element is xsd:schema Element root = doc.getDocumentElement(); if (root.getLocalName().equals("schema") && Constants.isSchemaXSD(root.getNamespaceURI())) { Node schema = docHolder.importNode(root, true); if (null == wsdlTypesElem) { writeWsdlTypesElement(); } wsdlTypesElem.appendChild(schema); // Create a symbol table and populate it with the input types BaseTypeMapping btm = new BaseTypeMapping() { public String getBaseName(QName qNameIn) { QName qName = new QName(qNameIn.getNamespaceURI(), qNameIn.getLocalPart()); Class cls = defaultTM.getClassForQName(qName); if (cls == null) { return null; } else { return JavaUtils.getTextClassName(cls.getName()); } } }; SymbolTable symbolTable = new SymbolTable(btm, true, false, false); symbolTable.populateTypes(new URL(inputSchema), doc); processSymTabEntries(symbolTable); } else { // If not, we'll just bail out... perhaps we should log a warning // or throw an exception? ; } } /** * Walk the type/element entries in the symbol table and * add each one to the list of processed types. This prevents * the types from being duplicated. * * @param symbolTable */ private void processSymTabEntries(SymbolTable symbolTable) { Iterator iterator = symbolTable.getElementIndex().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry me = (Map.Entry) iterator.next(); QName name = (QName) me.getKey(); TypeEntry te = (TypeEntry) me.getValue(); String prefix = XMLUtils.getPrefix(name.getNamespaceURI(), te.getNode()); if (!((null == prefix) || "".equals(prefix))) { namespaces.putPrefix(name.getNamespaceURI(), prefix); def.addNamespace(prefix, name.getNamespaceURI()); } addToElementsList(name); } iterator = symbolTable.getTypeIndex().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry me = (Map.Entry) iterator.next(); QName name = (QName) me.getKey(); TypeEntry te = (TypeEntry) me.getValue(); String prefix = XMLUtils.getPrefix(name.getNamespaceURI(), te.getNode()); if (!((null == prefix) || "".equals(prefix))) { namespaces.putPrefix(name.getNamespaceURI(), prefix); def.addNamespace(prefix, name.getNamespaceURI()); } addToTypesList(name); } } /** * Load the types from the input wsdl file. * * @param inputWSDL file or URL * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void loadInputTypes(String inputWSDL) throws IOException, WSDLException, SAXException, ParserConfigurationException { // Read the input wsdl file into a Document Document doc = XMLUtils.newDocument(inputWSDL); // Search for the 'types' element NodeList elements = doc.getChildNodes(); if ((elements.getLength() > 0) && elements.item(0).getLocalName().equals("definitions")) { elements = elements.item(0).getChildNodes(); for (int i = 0; (i < elements.getLength()) && (wsdlTypesElem == null); i++) { Node node = elements.item(i); if ((node.getLocalName() != null) && node.getLocalName().equals("types")) { wsdlTypesElem = (Element) node; } } } // If types element not found, there is no need to continue. if (wsdlTypesElem == null) { return; } // Import the types element into the Types docHolder document wsdlTypesElem = (Element) docHolder.importNode(wsdlTypesElem, true); docHolder.appendChild(wsdlTypesElem); // Create a symbol table and populate it with the input wsdl document BaseTypeMapping btm = new BaseTypeMapping() { public String getBaseName(QName qNameIn) { QName qName = new QName(qNameIn.getNamespaceURI(), qNameIn.getLocalPart()); Class cls = tm.getClassForQName(qName); if (cls == null) { return null; } else { return JavaUtils.getTextClassName(cls.getName()); } } }; SymbolTable symbolTable = new SymbolTable(btm, true, false, false); symbolTable.populate(null, doc); processSymTabEntries(symbolTable); } /** * Write out a type referenced by a part type attribute. * * @param type <code>Class</code> to generate the XML Schema info for * @param qname <code>QName</code> of the type. If null, qname is * defaulted from the class. * @return the QName of the generated Schema type, null if void, * if the Class type cannot be converted to a schema type * then xsd:anytype is returned. * @throws AxisFault */ public QName writeTypeForPart(Class type, QName qname) throws AxisFault { // patch by costin to fix an NPE; commented out till we find out what the problem is // if you get NullPointerExceptions in this class, turn it on and submit some // replicable test data to the Axis team via bugzilla /* * if( type==null ) { * return null; * } */ if (type.getName().equals("void")) { return null; } if (Holder.class.isAssignableFrom(type)) { type = JavaUtils.getHolderValueType(type); } // Get the qname if ((qname == null) || (Constants.isSOAP_ENC(qname.getNamespaceURI()) && "Array".equals(qname.getLocalPart()))) { qname = getTypeQName(type); if (qname == null) { throw new AxisFault("Class:" + type.getName()); } } if (!makeTypeElement(type, qname, null)) { qname = Constants.XSD_ANYTYPE; } return qname; } /** * Write out a type (and its subtypes) referenced by a part type attribute. * * @param type <code>Class</code> to generate the XML Schema info for * @param qname <code>QName</code> of the type. If null, qname is * defaulted from the class. * @return the QName of the generated Schema type, null if void, * if the Class type cannot be converted to a schema type * then xsd:anytype is returned. */ public QName writeTypeAndSubTypeForPart(Class type, QName qname) throws AxisFault { // Write out type in parameter QName qNameRet = writeTypeForPart(type, qname); // If mappedTypesexists // Will write subTypes of the type in parameters if (mappedTypes != null) { for (int i = 0; i < mappedTypes.length; i++) { Class tempMappedType = mappedTypes[i]; QName name; // If tempMappedType is subtype of the "type" parameter // and type is not Object (Object superclass of all Java class...) // write the subtype if (tempMappedType != null && type != Object.class && tempMappedType != type && type.isAssignableFrom(tempMappedType)) { name = tm.getTypeQName(tempMappedType); if (!isAnonymousType(name)) { writeTypeForPart(tempMappedType, name); } // Only do each one once. This is OK to do because each // Types instance is for generating a single WSDL. mappedTypes[i] = null; } } } //if (mappedTyped != null) { return qNameRet; } /** * Write out an element referenced by a part element attribute. * * @param type <code>Class</code> to generate the XML Schema info for * @param qname <code>QName</code> of the element. If null, qname is * defaulted from the class. * @return the QName of the generated Schema type, null if no element * @throws AxisFault */ public QName writeElementForPart(Class type, QName qname) throws AxisFault { // patch by costin to fix an NPE; commented out till we find out what the problem is // if you get NullPointerExceptions in this class, turn it on and submit some // replicable test data to the Axis team via bugzilla /* * if( type==null ) { * return null; * } */ if (type.getName().equals("void")) { return null; } if (Holder.class.isAssignableFrom(type)) { type = JavaUtils.getHolderValueType(type); } // Get the qname if ((qname == null) || (Constants.isSOAP_ENC(qname.getNamespaceURI()) && "Array".equals(qname.getLocalPart()))) { qname = getTypeQName(type); if (qname == null) { throw new AxisFault("Class:" + type.getName()); } } // Return null it a simple type (not an element) String nsURI = qname.getNamespaceURI(); if (Constants.isSchemaXSD(nsURI) || (Constants.isSOAP_ENC(nsURI) && !"Array".equals(qname.getLocalPart()))) { return null; } // Make sure a types section is present if (wsdlTypesElem == null) { writeWsdlTypesElement(); } // Write Element, if problems occur return null. if (writeTypeAsElement(type, qname) == null) { qname = null; } return qname; } /** * Write the element definition for a WRAPPED operation. This will * write out any necessary namespace/schema declarations, an an element * definition with an internal (anonymous) complexType. The name of the * element will be *foo*Request or *foo*Response depending on whether the * request boolean is true. If the operation contains parameters, then * we also generate a &gt;sequence&lt; node underneath the complexType, * and return it for later use by writeWrappedParameter() below. * * @param qname the desired element QName * @param request true if we're writing the request wrapper, false if * writing the response. * @param hasParams true if there are parameters, and thus a sequence * node is needed * @return a DOM Element for the sequence, inside which we'll write the * parameters as elements, or null if there are no parameters * @throws AxisFault */ public Element writeWrapperElement( QName qname, boolean request, boolean hasParams) throws AxisFault { // Make sure a types section is present if (wsdlTypesElem == null) { writeWsdlTypesElement(); } // Write the namespace definition for the wrapper writeTypeNamespace(qname.getNamespaceURI()); // Create an <element> for the wrapper Element wrapperElement = docHolder.createElement("element"); writeSchemaElementDecl(qname, wrapperElement); wrapperElement.setAttribute("name", qname.getLocalPart()); // Create an anonymous <complexType> for the wrapper Element complexType = docHolder.createElement("complexType"); wrapperElement.appendChild(complexType); // If we have parameters in the operation, create a <sequence> // under the complexType and return it. if (hasParams) { Element sequence = docHolder.createElement("sequence"); complexType.appendChild(sequence); return sequence; } return null; } /** * Write a parameter (a sub-element) into a sequence generated by * writeWrapperElement() above. * * @param sequence the &lt;sequence&gt; in which we're writing * @param name is the name of an element to add to the wrapper element. * @param type is the QName of the type of the element. * @param javaType * @throws AxisFault */ public void writeWrappedParameter( Element sequence, String name, QName type, Class javaType) throws AxisFault { if (javaType == void.class) { return; } // JAX-RPC 1.1 says that byte[] should always be a Base64Binary // This (rather strange) hack will ensure that we don't map it // in to an maxoccurs=unbounded array. if (javaType.isArray() && !javaType.equals(byte[].class)) { type = writeTypeForPart(javaType.getComponentType(), null); } else { type = writeTypeForPart(javaType, type); } if (type == null) { // TODO: throw an Exception!! return; } Element childElem; if (isAnonymousType(type)) { childElem = createElementWithAnonymousType(name, javaType, false, docHolder); } else { // Create the child <element> and add it to the wrapper <sequence> childElem = docHolder.createElement("element"); childElem.setAttribute("name", name); String prefix = namespaces.getCreatePrefix(type.getNamespaceURI()); String prefixedName = prefix + ":" + type.getLocalPart(); childElem.setAttribute("type", prefixedName); // JAX-RPC 1.1 says that byte[] should always be a Base64Binary // This (rather strange) hack will ensure that we don't map it // in to an maxoccurs=unbounded array. if (javaType.isArray() && !javaType.equals(byte[].class)) { childElem.setAttribute("maxOccurs", "unbounded"); } } sequence.appendChild(childElem); } /** * Method isAnonymousType * * @param type * @return */ private boolean isAnonymousType(QName type) { return type.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) != -1; } /** * Create a schema element for the given type * * @param type the class type * @param qName * @return the QName of the generated Element or problems occur * @throws AxisFault */ private QName writeTypeAsElement(Class type, QName qName) throws AxisFault { if ((qName == null) || Constants.equals(Constants.SOAP_ARRAY, qName)) { qName = getTypeQName(type); } writeTypeNamespace(type, qName); String elementType = writeType(type, qName); if (elementType != null) { // Element element = createElementDecl(qName.getLocalPart(), type, qName, isNullable(type), false); // if (element != null) // writeSchemaElement(typeQName,element); return qName; } return null; } /** * write out the namespace declaration and return the type QName for the * given <code>Class</code> * * @param type input Class * @param qName qname of the Class * @return QName for the schema type representing the class */ private QName writeTypeNamespace(Class type, QName qName) { if (qName == null) { qName = getTypeQName(type); } writeTypeNamespace(qName.getNamespaceURI()); return qName; } /** * write out the namespace declaration. * * @param namespaceURI qname of the type */ private void writeTypeNamespace(String namespaceURI) { if ((namespaceURI != null) && !namespaceURI.equals("")) { String pref = def.getPrefix(namespaceURI); if (pref == null) { def.addNamespace(namespaces.getCreatePrefix(namespaceURI), namespaceURI); } } } /** * Return the QName of the specified javaType * * @param javaType input javaType Class * @return QName */ public QName getTypeQName(Class javaType) { QName qName = null; // Use the typeMapping information to lookup the qName. qName = tm.getTypeQName(javaType); // If the javaType is an array and the qName is // SOAP_ARRAY, construct the QName using the // QName of the component type if (isArray(javaType) && Constants.equals(Constants.SOAP_ARRAY, qName)) { Class componentType = getComponentType(javaType); // For WS-I BP compliance, we can't use "ArrayOf" as a type prefix // instead use "MyArrayOf" (gag) String arrayTypePrefix = "ArrayOf"; boolean isWSICompliant = JavaUtils.isTrue( AxisProperties.getProperty(Constants.WSIBP11_COMPAT_PROPERTY)); if (isWSICompliant) { arrayTypePrefix = "MyArrayOf"; } // If component namespace uri == targetNamespace // Construct ArrayOf<componentLocalPart> // Else // Construct ArrayOf_<componentPrefix>_<componentLocalPart> QName cqName = getTypeQName(componentType); if (targetNamespace.equals(cqName.getNamespaceURI())) { qName = new QName(targetNamespace, arrayTypePrefix + cqName.getLocalPart()); } else { String pre = namespaces.getCreatePrefix(cqName.getNamespaceURI()); qName = new QName(targetNamespace, arrayTypePrefix + "_" + pre + "_" + cqName.getLocalPart()); } return qName; } // If a qName was not found construct one using the // class name information. if (qName == null) { String pkg = getPackageNameFromFullName(javaType.getName()); String lcl = getLocalNameFromFullName(javaType.getName()); String ns = namespaces.getCreate(pkg); namespaces.getCreatePrefix(ns); String localPart = lcl.replace('$', '_'); qName = new QName(ns, localPart); } return qName; } /** * Return a string suitable for representing a given QName in the context * of this WSDL document. If the namespace of the QName is not yet * registered, we will register it up in the Definitions. * * @param qname a QName (typically a type) * @return a String containing a standard "ns:localPart" rep of the QName */ public String getQNameString(QName qname) { String prefix = namespaces.getCreatePrefix(qname.getNamespaceURI()); return prefix + ":" + qname.getLocalPart(); } /** * Utility method to get the package name from a fully qualified java class name * * @param full input class name * @return package name */ public static String getPackageNameFromFullName(String full) { if (full.lastIndexOf('.') < 0) { return ""; } else { return full.substring(0, full.lastIndexOf('.')); } } /** * Utility method to get the local class name from a fully qualified java class name * * @param full input class name * @return package name */ public static String getLocalNameFromFullName(String full) { String end = ""; if (full.startsWith("[L")) { end = "[]"; full = full.substring(3, full.length() - 1); } if (full.lastIndexOf('.') < 0) { return full + end; } else { return full.substring(full.lastIndexOf('.') + 1) + end; } } /** * Method writeSchemaTypeDecl * * @param qname * @param element * @throws AxisFault */ public void writeSchemaTypeDecl(QName qname, Element element) throws AxisFault { writeSchemaElement(qname.getNamespaceURI(), element); } /** * Method writeSchemaElementDecl * * @param qname * @param element * @throws AxisFault */ public void writeSchemaElementDecl(QName qname, Element element) throws AxisFault { if (writtenElementQNames.contains(qname)) { throw new AxisFault( Constants.FAULT_SERVER_GENERAL, Messages.getMessage( "duplicateSchemaElement", qname.toString()), null, null); } writeSchemaElement(qname.getNamespaceURI(), element); writtenElementQNames.add(qname); } /** * @deprecated * Please use writeSchemaElement(String namespaceURI, Element element) * * @param qName qName to get the namespace of the schema node * @param element the Element to append to the Schema node * @throws AxisFault */ public void writeSchemaElement(QName qName, Element element) throws AxisFault { writeSchemaElement(qName.getNamespaceURI(), element); } /** * Write out the given Element into the appropriate schema node. * If need be create the schema node as well * * @param namespaceURI namespace this node should get dropped into * @param element the Element to append to the Schema node * @throws AxisFault */ public void writeSchemaElement(String namespaceURI, Element element) throws AxisFault { if (wsdlTypesElem == null) { try { writeWsdlTypesElement(); } catch (Exception e) { log.error(e); return; } } if ((namespaceURI == null) || namespaceURI.equals("")) { throw new AxisFault( Constants.FAULT_SERVER_GENERAL, Messages.getMessage("noNamespace00", namespaceURI), null, null); } Element schemaElem = null; NodeList nl = wsdlTypesElem.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { NamedNodeMap attrs = nl.item(i).getAttributes(); if (attrs != null) { for (int n = 0; n < attrs.getLength(); n++) { Attr a = (Attr) attrs.item(n); if (a.getName().equals("targetNamespace") && a.getValue().equals(namespaceURI)) { schemaElem = (Element) nl.item(i); } } } } if (schemaElem == null) { schemaElem = docHolder.createElement("schema"); wsdlTypesElem.appendChild(schemaElem); schemaElem.setAttribute("xmlns", Constants.URI_DEFAULT_SCHEMA_XSD); schemaElem.setAttribute("targetNamespace", namespaceURI); // Add SOAP-ENC namespace import if necessary if (serviceDesc.getStyle() == Style.RPC) { Element importElem = docHolder.createElement("import"); schemaElem.appendChild(importElem); importElem.setAttribute("namespace", Constants.URI_DEFAULT_SOAP_ENC); } SOAPService service = null; if(MessageContext.getCurrentContext() != null) { service = MessageContext.getCurrentContext().getService(); } if(service != null && isPresent((String) service.getOption("schemaQualified"), namespaceURI)){ schemaElem.setAttribute("elementFormDefault", "qualified"); } else if(service != null && isPresent((String) service.getOption("schemaUnqualified"), namespaceURI)){ // DO nothing..default is unqualified. } else if ((serviceDesc.getStyle() == Style.DOCUMENT) || (serviceDesc.getStyle() == Style.WRAPPED)) { schemaElem.setAttribute("elementFormDefault", "qualified"); } writeTypeNamespace(namespaceURI); } schemaElem.appendChild(element); } /** * check if the namespace is present in the list. * @param list * @param namespace * @return */ private boolean isPresent(String list, String namespace) { if(list == null || list.length()==0) return false; String[] array = StringUtils.split(list,','); for(int i=0;i<array.length;i++){ if(array[i].equals(namespace)) return true; } return false; } /** * Get the Types element for the WSDL document. If not present, create one */ private void writeWsdlTypesElement() { if (wsdlTypesElem == null) { // Create a <wsdl:types> element corresponding to the wsdl namespaces. wsdlTypesElem = docHolder.createElementNS(Constants.NS_URI_WSDL11, "types"); wsdlTypesElem.setPrefix(Constants.NS_PREFIX_WSDL); } } /** * Write a schema representation for the given <code>Class</code>. Recurse * through all the public fields as well as fields represented by java * bean compliant accessor methods. * <p> * Then return the qualified string representation of the generated type * * @param type Class for which to generate schema * @return a prefixed string for the schema type * @throws AxisFault */ public String writeType(Class type) throws AxisFault { return writeType(type, null); } /** * Write a schema representation for the given <code>Class</code>. Recurse * through all the public fields as well as fields represented by java * bean compliant accessor methods. * <p> * Then return the qualified string representation of the generated type * * @param type Class for which to generate schema * @param qName of the type to write * @return a prefixed string for the schema type or null if problems occur * @throws AxisFault */ public String writeType(Class type, QName qName) throws AxisFault { // Get a corresponding QName if one is not provided if ((qName == null) || Constants.equals(Constants.SOAP_ARRAY, qName)) { qName = getTypeQName(type); } if (!makeTypeElement(type, qName, null)) { return null; } return getQNameString(qName); } /** * Method createArrayElement * * @param componentTypeName * @return */ public Element createArrayElement(String componentTypeName) { SOAPConstants constants; MessageContext mc = MessageContext.getCurrentContext(); if(mc==null||mc.getSOAPConstants()==null){ constants = SOAPConstants.SOAP11_CONSTANTS; } else { constants = mc.getSOAPConstants(); } String prefix = namespaces.getCreatePrefix(constants.getEncodingURI()); // ComplexType representation of array Element complexType = docHolder.createElement("complexType"); Element complexContent = docHolder.createElement("complexContent"); complexType.appendChild(complexContent); Element restriction = docHolder.createElement("restriction"); complexContent.appendChild(restriction); restriction.setAttribute("base", prefix + ":Array"); Element attribute = docHolder.createElement("attribute"); restriction.appendChild(attribute); attribute.setAttribute("ref", prefix + ":arrayType"); prefix = namespaces.getCreatePrefix(Constants.NS_URI_WSDL11); attribute.setAttribute(prefix + ":arrayType", componentTypeName); return complexType; } /** * Create an array which is a wrapper type for "item" elements * of a component type. This is basically the unencoded parallel to * a SOAP-encoded array. * * @param componentType * @param itemName the QName of the inner element (right now we only use the localPart) * @return */ public Element createLiteralArrayElement(String componentType, QName itemName) { String itemLocalName = "item"; if (itemName != null) { itemLocalName = itemName.getLocalPart(); } Element complexType = docHolder.createElement("complexType"); Element sequence = docHolder.createElement("sequence"); complexType.appendChild(sequence); Element elem = docHolder.createElement("element"); elem.setAttribute("name", itemLocalName); elem.setAttribute("type", componentType); elem.setAttribute("minOccurs", "0"); elem.setAttribute("maxOccurs", "unbounded"); sequence.appendChild(elem); return complexType; } /** * Returns true if indicated type matches the JAX-RPC enumeration class. * Note: supports JSR 101 version 0.6 Public Draft * * @param cls * @return */ public static boolean isEnumClass(Class cls) { try { java.lang.reflect.Method m = cls.getMethod("getValue", null); java.lang.reflect.Method m2 = cls.getMethod("toString", null); if ((m != null) && (m2 != null)) { java.lang.reflect.Method m3 = cls.getDeclaredMethod("fromString", new Class[]{ java.lang.String.class}); java.lang.reflect.Method m4 = cls.getDeclaredMethod("fromValue", new Class[]{ m.getReturnType()}); if ((m3 != null) && Modifier.isStatic(m3.getModifiers()) && Modifier.isPublic(m3.getModifiers()) && (m4 != null) && Modifier.isStatic(m4.getModifiers()) && Modifier.isPublic(m4.getModifiers())) { // Return false if there is a setValue member method try { if (cls.getMethod("setValue", new Class[]{ m.getReturnType()}) == null) { return true; } return false; } catch (java.lang.NoSuchMethodException e) { return true; } } } } catch (java.lang.NoSuchMethodException e) { } return false; } /** * Write Enumeration Complex Type * (Only supports enumeration classes of string types) * * @param qName QName of type. * @param cls class of type * @return * @throws NoSuchMethodException * @throws IllegalAccessException * @throws AxisFault */ public Element writeEnumType(QName qName, Class cls) throws NoSuchMethodException, IllegalAccessException, AxisFault { if (!isEnumClass(cls)) { return null; } // Get the base type of the enum class java.lang.reflect.Method m = cls.getMethod("getValue", null); Class base = m.getReturnType(); // Create simpleType, restriction elements Element simpleType = docHolder.createElement("simpleType"); simpleType.setAttribute("name", qName.getLocalPart()); Element restriction = docHolder.createElement("restriction"); simpleType.appendChild(restriction); String baseType = writeType(base, null); restriction.setAttribute("base", baseType); // Create an enumeration using the field values Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mod = field.getModifiers(); // Inspect each public static final field of the same type // as the base if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod) && (field.getType() == base)) { // Create an enumeration using the value specified Element enumeration = docHolder.createElement("enumeration"); enumeration.setAttribute("value", field.get(null).toString()); restriction.appendChild(enumeration); } } return simpleType; } /** * Create a top-level element declaration in our generated schema * * @param qname * @param javaType * @param typeQName * @param nillable nillable attribute of the element * @param itemQName * @throws AxisFault */ public void writeElementDecl(QName qname, Class javaType, QName typeQName, boolean nillable, QName itemQName) throws AxisFault { if (writtenElementQNames.contains(qname)) { return; } String name = qname.getLocalPart(); Element element = docHolder.createElement("element"); // Generate an element name that matches the type. element.setAttribute("name", name); if (nillable) { element.setAttribute("nillable", "true"); } /* * These are not legal on top-level elements! * (feel free to delete this block after say Oct 2005) if (omittable) { element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "1"); } if (javaType.isArray()) { element.setAttribute("maxOccurs", "unbounded"); } */ if (javaType.isArray()) { // TODO : Should check to see if this array type is specifically mapped String componentType = writeType(javaType.getComponentType()); Element complexType = createLiteralArrayElement(componentType, itemQName); element.appendChild(complexType); } else { // Write the type for this element, handling anonymous or named // types appropriately. makeTypeElement(javaType, typeQName, element); } writeSchemaElementDecl(qname, element); } /** * Create Element with a given name and type * * @param elementName the name of the created element * @param elementType schema type representation of the element * @param nullable nullable attribute of the element * @param omittable * @param docHolder * @return the created Element */ public Element createElement(String elementName, String elementType, boolean nullable, boolean omittable, Document docHolder) { Element element = docHolder.createElement("element"); element.setAttribute("name", elementName); if (nullable) { element.setAttribute("nillable", "true"); } if (omittable) { element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "1"); } if (elementType != null) { element.setAttribute("type", elementType); } return element; } /** * Create Attribute Element with a given name and type * * @param elementName the name of the created element * @param javaType * @param xmlType * @param nullable nullable attribute of the element * @param docHolder * @return the created Element * @throws AxisFault */ public Element createAttributeElement( String elementName, Class javaType, QName xmlType, boolean nullable, Document docHolder) throws AxisFault { Element element = docHolder.createElement("attribute"); element.setAttribute("name", elementName); if (nullable) { element.setAttribute("nillable", "true"); } makeTypeElement(javaType, xmlType, element); return element; } /** * Is the given class one of the simple types? In other words, * do we have a mapping for this type which is in the xsd or * soap-enc namespaces? * * @param type input Class * @return true if the type is a simple type */ boolean isSimpleType(Class type) { QName qname = tm.getTypeQName(type); if (qname == null) { return false; // No mapping } String nsURI = qname.getNamespaceURI(); return (Constants.isSchemaXSD(nsURI) || Constants.isSOAP_ENC(nsURI)); } /** * Is the given class acceptable as an attribute * * @param type input Class * @return true if the type is a simple, enum type or extends SimpleType */ public boolean isAcceptableAsAttribute(Class type) { return isSimpleType(type) || isEnumClass(type) || implementsSimpleType(type); } /** * Does the class implement SimpleType * * @param type input Class * @return true if the type implements SimpleType */ boolean implementsSimpleType(Class type) { Class[] impls = type.getInterfaces(); for (int i = 0; i < impls.length; i++) { if (impls[i] == SimpleType.class) { return true; } } return false; } /** * Generates a unique element name for a given namespace of the form * el0, el1 .... * * @param qName the namespace for the generated element * @return elementname */ // *** NOT USED? *** // // private String generateUniqueElementName(QName qName) { // Integer count = (Integer)schemaUniqueElementNames.get(qName.getNamespaceURI()); // if (count == null) // count = new Integer(0); // else // count = new Integer(count.intValue() + 1); // schemaUniqueElementNames.put(qName.getNamespaceURI(), count); // return "el" + count.intValue(); // } /** * Add the type to an ArrayList and return true if the Schema node * needs to be generated * If the type already exists, just return false to indicate that the type is already * generated in a previous iteration * * @param qName of the type. * @return if the type is added returns true, * else if the type is already present returns false */ private boolean addToTypesList(QName qName) { boolean added = false; String namespaceURI = qName.getNamespaceURI(); ArrayList types = (ArrayList) schemaTypes.get(namespaceURI); // Quick return if schema type (will never add these ourselves) if (Constants.isSchemaXSD(namespaceURI) || (Constants.isSOAP_ENC(namespaceURI) && !"Array".equals(qName.getLocalPart()))) { // Make sure we do have the namespace declared, though... writeTypeNamespace(namespaceURI); return false; } if (types == null) { types = new ArrayList(); types.add(qName.getLocalPart()); writeTypeNamespace(namespaceURI); schemaTypes.put(namespaceURI, types); added = true; } else { if (!types.contains(qName.getLocalPart())) { types.add(qName.getLocalPart()); added = true; } } // If addded, look at the namespace uri to see if the schema element should be // generated. if (added) { String prefix = namespaces.getCreatePrefix(namespaceURI); if (prefix.equals(Constants.NS_PREFIX_SOAP_ENV) || prefix.equals(Constants.NS_PREFIX_SOAP_ENC) || prefix.equals(Constants.NS_PREFIX_SCHEMA_XSD) || prefix.equals(Constants.NS_PREFIX_WSDL) || prefix.equals(Constants.NS_PREFIX_WSDL_SOAP)) { return false; } else { return true; } } return false; } /** * Add the element to an ArrayList and return true if the Schema element * needs to be generated * If the element already exists, just return false to indicate that the type is already * generated in a previous iteration * * @param qName the name space of the element * @return if the type is added returns true, else if the type is already present returns false */ private boolean addToElementsList(QName qName) { if (qName == null) { return false; } boolean added = false; ArrayList elements = (ArrayList) schemaElementNames.get(qName.getNamespaceURI()); if (elements == null) { elements = new ArrayList(); elements.add(qName.getLocalPart()); schemaElementNames.put(qName.getNamespaceURI(), elements); added = true; } else { if (!elements.contains(qName.getLocalPart())) { elements.add(qName.getLocalPart()); added = true; } } return added; } /** * Determines if the field is nullable. All non-primitives are nillable. * * @param type input Class * @return true if nullable */ public static boolean isNullable(Class type) { if (type.isPrimitive()) { return false; } else { return true; } } /** * todo ravi: Get rid of Doccument fragment and import node stuuf, * once I have a handle on the wsdl4j mechanism to get at types. * <p/> * Switch over notes: remove docHolder, docFragment in favor of wsdl4j Types * <p/> * DocumentFragment docFragment; * <p/> * DocumentFragment docFragment; * <p/> * DocumentFragment docFragment; * <p/> * DocumentFragment docFragment; */ // DocumentFragment docFragment; Document docHolder; /** * Method createDocumentFragment */ private void createDocumentFragment() { try { this.docHolder = XMLUtils.newDocument(); } catch (ParserConfigurationException e) { // This should not occur throw new InternalException(e); } } /** * Method updateNamespaces */ public void updateNamespaces() { Namespaces namespaces = getNamespaces(); Iterator nspIterator = namespaces.getNamespaces(); while (nspIterator.hasNext()) { String nsp = (String) nspIterator.next(); String pref = def.getPrefix(nsp); if (pref == null) { def.addNamespace(namespaces.getCreatePrefix(nsp), nsp); } } } /** * Inserts the type fragment into the given wsdl document and ensures * that definitions from each embedded schema are allowed to reference * schema components from the other sibling schemas. * @param doc */ public void insertTypesFragment(Document doc) { updateNamespaces(); if (wsdlTypesElem == null) return; // Make sure that definitions from each embedded schema are allowed // to reference schema components from the other sibling schemas. Element schemaElem = null; String tns = null; NodeList nl = wsdlTypesElem.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { NamedNodeMap attrs = nl.item(i).getAttributes(); if (attrs == null) continue; // Should never happen. for (int n = 0; n < attrs.getLength(); n++) { Attr a = (Attr) attrs.item(n); if (a.getName().equals("targetNamespace")) { tns = a.getValue(); schemaElem = (Element) nl.item(i); break; } } // Ignore what appears to be a not namespace-qualified // schema definition. if (tns != null && !"".equals(tns.trim())) { // By now we know that an import element might be necessary // for some sibling schemas. However, in the absence of // a symbol table proper, the best we can do is add one // for each sibling schema. Iterator it = schemaTypes.keySet().iterator(); String otherTns; Element importElem; while (it.hasNext()) { if (!tns.equals(otherTns = (String) it.next())) { importElem = docHolder.createElement("import"); importElem.setAttribute("namespace", otherTns); schemaElem.insertBefore(importElem, schemaElem.getFirstChild()); } } } schemaElem = null; tns = null; } // Import the wsdlTypesElement into the doc. org.w3c.dom.Node node = doc.importNode(wsdlTypesElem, true); // Insert the imported element at the beginning of the document doc.getDocumentElement(). insertBefore(node, doc.getDocumentElement().getFirstChild()); } /** * Return the list of classes that we should not emit WSDL for. * * @return */ public List getStopClasses() { return stopClasses; } /** * Create a DOM Element in this context * * @param elementName * @return */ public Element createElement(String elementName) { return docHolder.createElement(elementName); } /** * isBeanCompatible * * @param javaType Class * @param issueErrors if true, issue messages if not compatible * Returns true if it appears that this class is a bean and * can be mapped to a complexType * @return */ protected boolean isBeanCompatible(Class javaType, boolean issueErrors) { // Must be a non-primitive and non array if (javaType.isArray() || javaType.isPrimitive()) { if (issueErrors && !beanCompatErrs.contains(javaType)) { log.warn(Messages.getMessage("beanCompatType00", javaType.getName())); beanCompatErrs.add(javaType); } return false; } // Anything in the java or javax package that // does not have a defined mapping is excluded. if (javaType.getName().startsWith("java.") || javaType.getName().startsWith("javax.")) { if (issueErrors && !beanCompatErrs.contains(javaType)) { log.warn(Messages.getMessage("beanCompatPkg00", javaType.getName())); beanCompatErrs.add(javaType); } return false; } // Return true if appears to be an enum class if (JavaUtils.isEnumClass(javaType)) { return true; } // Must have a default public constructor if not // Throwable if (!java.lang.Throwable.class.isAssignableFrom(javaType)) { try { javaType.getConstructor(new Class[]{ }); } catch (java.lang.NoSuchMethodException e) { if (issueErrors && !beanCompatErrs.contains(javaType)) { log.warn(Messages.getMessage("beanCompatConstructor00", javaType.getName())); beanCompatErrs.add(javaType); } return false; } } // Make sure superclass is compatible Class superClass = javaType.getSuperclass(); if ((superClass != null) && (superClass != java.lang.Object.class) && (superClass != java.lang.Exception.class) && (superClass != java.lang.Throwable.class) && (superClass != java.rmi.RemoteException.class) && (superClass != org.apache.axis.AxisFault.class) && ((stopClasses == null) || !(stopClasses.contains(superClass.getName())))) { if (!isBeanCompatible(superClass, false)) { if (issueErrors && !beanCompatErrs.contains(javaType)) { log.warn(Messages.getMessage("beanCompatExtends00", javaType.getName(), superClass.getName(), javaType.getName())); beanCompatErrs.add(javaType); } return false; } } return true; } /** * Write an &lt;element&gt; with an anonymous internal ComplexType * * @param elementName * @param fieldType * @param omittable * @param ownerDocument * @return * @throws AxisFault */ public Element createElementWithAnonymousType(String elementName, Class fieldType, boolean omittable, Document ownerDocument) throws AxisFault { Element element = docHolder.createElement("element"); element.setAttribute("name", elementName); if (isNullable(fieldType)) { element.setAttribute("nillable", "true"); } if (omittable) { element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "1"); } makeTypeElement(fieldType, null, element); return element; } /** * Create a schema type element (either simpleType or complexType) for * the particular type/qName combination. If the type is named, we * handle inserting the new type into the appropriate &lt;schema&gt; * in the WSDL types section. If the type is anonymous, we append the * definition underneath the Element which was passed as the container * (typically a field of a higher-level type or a parameter in a wrapped * operation). * * @param type Java type to write * @param qName the desired type QName * @param containingElement a schema element ("element" or "attribute") * which should either receive a type="" attribute decoration * (for named types) or a child element defining an anonymous * type * @return true if the type was already present or was added, false if there was a problem * @throws AxisFault */ private boolean makeTypeElement(Class type, QName qName, Element containingElement) throws AxisFault { // Get a corresponding QName if one is not provided if ((qName == null) || Constants.equals(Constants.SOAP_ARRAY, qName)) { qName = getTypeQName(type); } boolean anonymous = isAnonymousType(qName); // Can't have an anonymous type outside of a containing element if (anonymous && (containingElement == null)) { throw new AxisFault( Messages.getMessage( "noContainerForAnonymousType", qName.toString())); } // If we've already got this type (because it's a native type or // because we've already written it), just add the type="" attribute // (if appropriate) and return. if (!addToTypesList(qName) && !anonymous) { if (containingElement != null) { containingElement.setAttribute("type", getQNameString(qName)); } return true; } // look up the serializer in the TypeMappingRegistry SerializerFactory factory; factory = (SerializerFactory) tm.getSerializer(type, qName); // If no factory is found, use the BeanSerializerFactory // if applicable, otherwise issue errors and treat as an anyType if (factory == null) { if (isEnumClass(type)) { factory = new EnumSerializerFactory(type, qName); } else if (isBeanCompatible(type, true)) { factory = new BeanSerializerFactory(type, qName); } else { return false; } } // factory is not null Serializer ser = (Serializer) factory.getSerializerAs(Constants.AXIS_SAX); // if we can't get a serializer, that is bad. if (ser == null) { throw new AxisFault(Messages.getMessage("NoSerializer00", type.getName())); } Element typeEl; try { typeEl = ser.writeSchema(type, this); } catch (Exception e) { throw AxisFault.makeFault(e); } // If this is an anonymous type, just make the type element a child // of containingElement. If not, set the "type" attribute of // containingElement to the right QName, and make sure the type is // correctly written into the appropriate <schema> element. if (anonymous) { if (typeEl == null) { containingElement.setAttribute("type", getQNameString(getTypeQName(type))); } else { containingElement.appendChild(typeEl); } } else { if (typeEl != null) { typeEl.setAttribute("name", qName.getLocalPart()); // Write the type in the appropriate <schema> writeSchemaTypeDecl(qName, typeEl); } if (containingElement != null) { containingElement.setAttribute("type", getQNameString(qName)); } } // store the mapping of type qname and its correspoding java type if (emitter != null) { emitter.getQName2ClassMap().put(qName, type); } return true; } /** * return the service description * @return */ public ServiceDesc getServiceDesc() { return serviceDesc; } }
7,754
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/fromJava/Emitter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.fromJava; import com.ibm.wsdl.extensions.soap.SOAPAddressImpl; import com.ibm.wsdl.extensions.soap.SOAPBindingImpl; import com.ibm.wsdl.extensions.soap.SOAPBodyImpl; import com.ibm.wsdl.extensions.soap.SOAPHeaderImpl; import com.ibm.wsdl.extensions.soap.SOAPOperationImpl; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.InternalException; import org.apache.axis.Version; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.description.FaultDesc; import org.apache.axis.description.JavaServiceDesc; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.commons.logging.Log; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.xml.sax.SAXException; import javax.wsdl.Binding; import javax.wsdl.BindingFault; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.BindingOutput; import javax.wsdl.Definition; import javax.wsdl.Fault; import javax.wsdl.Import; import javax.wsdl.Input; import javax.wsdl.Message; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.Output; import javax.wsdl.Part; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.wsdl.WSDLException; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.soap.SOAPAddress; import javax.wsdl.extensions.soap.SOAPBinding; import javax.wsdl.extensions.soap.SOAPBody; import javax.wsdl.extensions.soap.SOAPFault; import javax.wsdl.extensions.soap.SOAPHeader; import javax.wsdl.extensions.soap.SOAPOperation; import javax.wsdl.factory.WSDLFactory; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; /** * This class emits WSDL from Java classes. It is used by the ?WSDL * Axis browser function and Java2WSDL commandline utility. * See Java2WSDL and Java2WSDLFactory for more information. * * @author Glen Daniels (gdaniels@apache.org) * @author Rich Scheuerle (scheu@us.ibm.com) */ public class Emitter { /** Field log */ protected static Log log = LogFactory.getLog(Emitter.class.getName()); // Generated WSDL Modes /** Field MODE_ALL */ public static final int MODE_ALL = 0; /** Field MODE_INTERFACE */ public static final int MODE_INTERFACE = 1; /** Field MODE_IMPLEMENTATION */ public static final int MODE_IMPLEMENTATION = 2; /** Field cls */ private Class cls; /** Field extraClasses */ private Class[] extraClasses; // Extra classes to emit WSDL for /** Field implCls */ private Class implCls; // Optional implementation class /** Field allowedMethods */ private Vector allowedMethods = null; // Names of methods to consider /** Field disallowedMethods */ private Vector disallowedMethods = null; // Names of methods to exclude /** Field stopClasses */ private ArrayList stopClasses = new ArrayList(); // class names which halt inheritace searches /** Field useInheritedMethods */ private boolean useInheritedMethods = false; /** Field intfNS */ private String intfNS; /** Field implNS */ private String implNS; /** Field inputSchema */ private String inputSchema; /** Field inputWSDL */ private String inputWSDL; /** Field locationUrl */ private String locationUrl; /** Field importUrl */ private String importUrl; /** Field servicePortName */ private String servicePortName; /** Field serviceElementName */ private String serviceElementName; /** Field targetService */ private String targetService = null; /** Field description */ private String description; /** Field style */ private Style style = Style.RPC; /** Field use */ private Use use = null; // Default depends on style setting /** Field tm */ private TypeMapping tm = null; // Registered type mapping /** Field tmr */ private TypeMappingRegistry tmr = new TypeMappingRegistryImpl(); /** Field namespaces */ private Namespaces namespaces; /** Field exceptionMsg */ private Map exceptionMsg = null; /** Global element names already in use */ private Map usedElementNames; /** Field encodingList */ private ArrayList encodingList; /** Field types */ protected Types types; /** Field clsName */ private String clsName; /** Field portTypeName */ private String portTypeName; /** Field bindingName */ private String bindingName; /** Field serviceDesc */ private ServiceDesc serviceDesc; /** Field serviceDesc2 */ private JavaServiceDesc serviceDesc2; /** Field soapAction */ private String soapAction = "DEFAULT"; /** Should we emit all mapped types in every WSDL? */ private boolean emitAllTypes = false; /** Version string to put at top of WSDL */ private String versionMessage = null; /** The mapping of generated type qname to its corresponding java type. For use with java<-->wsdl roundtripping */ private HashMap qName2ClassMap; // Style Modes /** DEPRECATED - Indicates style=rpc use=encoded */ public static final int MODE_RPC = 0; /** DEPRECATED - Indicates style=document use=literal */ public static final int MODE_DOCUMENT = 1; /** DEPRECATED - Indicates style=wrapped use=literal */ public static final int MODE_DOC_WRAPPED = 2; /** * Construct Emitter. * Set the contextual information using set* methods * Invoke emit to emit the code */ public Emitter() { createDocumentFragment(); namespaces = new Namespaces(); exceptionMsg = new HashMap(); usedElementNames = new HashMap(); qName2ClassMap = new HashMap(); } /** * Generates WSDL documents for a given <code>Class</code> * * @param filename1 interface WSDL * @param filename2 implementation WSDL * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void emit(String filename1, String filename2) throws IOException, WSDLException, SAXException, ParserConfigurationException { // Get interface and implementation defs Definition intf = getIntfWSDL(); Definition impl = getImplWSDL(); // Supply reasonable file names if not supplied if (filename1 == null) { filename1 = getServicePortName() + "_interface.wsdl"; } if (filename2 == null) { filename2 = getServicePortName() + "_implementation.wsdl"; } for (int i = 0; (extraClasses != null) && (i < extraClasses.length); i++) { types.writeTypeForPart(extraClasses[i], null); } // types.updateNamespaces(); // Write out the interface def Document doc = WSDLFactory.newInstance().newWSDLWriter().getDocument(intf); types.insertTypesFragment(doc); prettyDocumentToFile(doc, filename1); // Write out the implementation def doc = WSDLFactory.newInstance().newWSDLWriter().getDocument(impl); prettyDocumentToFile(doc, filename2); } /** * Generates a complete WSDL document for a given <code>Class</code> * * @param filename WSDL * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void emit(String filename) throws IOException, WSDLException, SAXException, ParserConfigurationException { emit(filename, MODE_ALL); } /** * Generates a WSDL document for a given <code>Class</code>. * The WSDL generated is controlled by the mode parameter * mode 0: All * mode 1: Interface * mode 2: Implementation * * @param mode generation mode - all, interface, implementation * @return Document * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public Document emit(int mode) throws IOException, WSDLException, SAXException, ParserConfigurationException { Document doc; Definition def; switch (mode) { default: case MODE_ALL: def = getWSDL(); for (int i = 0; (extraClasses != null) && (i < extraClasses.length); i++) { types.writeTypeForPart(extraClasses[i], null); } // types.updateNamespaces(); doc = WSDLFactory.newInstance().newWSDLWriter().getDocument( def); types.insertTypesFragment(doc); break; case MODE_INTERFACE: def = getIntfWSDL(); for (int i = 0; (extraClasses != null) && (i < extraClasses.length); i++) { types.writeTypeForPart(extraClasses[i], null); } // types.updateNamespaces(); doc = WSDLFactory.newInstance().newWSDLWriter().getDocument( def); types.insertTypesFragment(doc); break; case MODE_IMPLEMENTATION: def = getImplWSDL(); doc = WSDLFactory.newInstance().newWSDLWriter().getDocument( def); break; } // Add Axis version info as comment to beginnning of generated WSDL if (versionMessage == null) { versionMessage = Messages.getMessage( "wsdlCreated00", XMLUtils.xmlEncodeString(Version.getVersion())); } // If version is empty string, don't emit one if (versionMessage != null && versionMessage.length() > 0) { Comment wsdlVersion = doc.createComment(versionMessage); doc.getDocumentElement().insertBefore( wsdlVersion, doc.getDocumentElement().getFirstChild()); } // Return the document return doc; } /** * Generates a String containing the WSDL for a given <code>Class</code>. * The WSDL generated is controlled by the mode parameter * mode 0: All * mode 1: Interface * mode 2: Implementation * * @param mode generation mode - all, interface, implementation * @return String * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public String emitToString(int mode) throws IOException, WSDLException, SAXException, ParserConfigurationException { Document doc = emit(mode); StringWriter sw = new StringWriter(); XMLUtils.PrettyDocumentToWriter(doc, sw); return sw.toString(); } /** * Generates a WSDL document for a given <code>Class</code>. * The WSDL generated is controlled by the mode parameter * mode 0: All * mode 1: Interface * mode 2: Implementation * * @param filename WSDL * @param mode generation mode - all, interface, implementation * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public void emit(String filename, int mode) throws IOException, WSDLException, SAXException, ParserConfigurationException { Document doc = emit(mode); // Supply a reasonable file name if not supplied if (filename == null) { filename = getServicePortName(); switch (mode) { case MODE_ALL: filename += ".wsdl"; break; case MODE_INTERFACE: filename += "_interface.wsdl"; break; case MODE_IMPLEMENTATION: filename += "_implementation.wsdl"; break; } } prettyDocumentToFile(doc, filename); } /** * Get a Full WSDL <code>Definition</code> for the current * configuration parameters * * @return WSDL <code>Definition</code> * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public Definition getWSDL() throws IOException, WSDLException, SAXException, ParserConfigurationException { // Invoke the init() method to ensure configuration is setup init(MODE_ALL); // Create a Definition for the output wsdl Definition def = createDefinition(); // Write interface header writeDefinitions(def, intfNS); // Create Types types = createTypes(def); // Write the WSDL constructs and return full Definition Binding binding = writeBinding(def, true); writePortType(def, binding); writeService(def, binding); return def; } /** * Get a interface WSDL <code>Definition</code> for the * current configuration parameters * * @return WSDL <code>Definition</code> * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public Definition getIntfWSDL() throws IOException, WSDLException, SAXException, ParserConfigurationException { // Invoke the init() method to ensure configuration is setup init(MODE_INTERFACE); // Create a definition for the output wsdl Definition def = createDefinition(); // Write interface header writeDefinitions(def, intfNS); // Create Types types = createTypes(def); // Write the interface WSDL constructs and return the Definition Binding binding = writeBinding(def, true); writePortType(def, binding); return def; } /** * Get implementation WSDL <code>Definition</code> for the * current configuration parameters * * @return WSDL <code>Definition</code> * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ public Definition getImplWSDL() throws IOException, WSDLException, SAXException, ParserConfigurationException { // Invoke the init() method to ensure configuration is setup init(MODE_IMPLEMENTATION); // Create a Definition for the output wsdl Definition def = createDefinition(); // Write implementation header and import writeDefinitions(def, implNS); writeImport(def, intfNS, importUrl); // Write the implementation WSDL constructs and return Definition Binding binding = writeBinding(def, false); // Don't add binding to def writeService(def, binding); return def; } /** * Invoked prior to building a definition to ensure parms * and data are set up. * * @param mode */ protected void init(int mode) { // Default use depending on setting of style if (use == null) { if (style == Style.RPC) { use = Use.ENCODED; } else { use = Use.LITERAL; } } if (tm == null) { String encodingStyle = ""; if (use == Use.ENCODED) { encodingStyle = Constants.URI_SOAP11_ENC; /** TODO : Set this correctly if we do SOAP 1.2 support here */ } tm = (TypeMapping)tmr.getTypeMapping(encodingStyle); } // Set up a ServiceDesc to use to introspect the Service if (serviceDesc == null) { JavaServiceDesc javaServiceDesc = new JavaServiceDesc(); serviceDesc = javaServiceDesc; javaServiceDesc.setImplClass(cls); // Set the typeMapping to the one provided. serviceDesc.setTypeMapping(tm); javaServiceDesc.setStopClasses(stopClasses); serviceDesc.setAllowedMethods(allowedMethods); javaServiceDesc.setDisallowedMethods(disallowedMethods); serviceDesc.setStyle(style); serviceDesc.setUse(use); // If the class passed in is a portType, // there may be an implClass that is used to // obtain the method parameter names. In this case, // a serviceDesc2 is built to get the method parameter names. if ((implCls != null) && (implCls != cls) && (serviceDesc2 == null)) { serviceDesc2 = new JavaServiceDesc(); serviceDesc2.setImplClass(implCls); // Set the typeMapping to the one provided. serviceDesc2.setTypeMapping(tm); serviceDesc2.setStopClasses(stopClasses); serviceDesc2.setAllowedMethods(allowedMethods); serviceDesc2.setDisallowedMethods(disallowedMethods); serviceDesc2.setStyle(style); } } if (encodingList == null) { // if cls contains a Class object with the service implementation use the Name of the // class else use the service name if (cls != null) { clsName = cls.getName(); clsName = clsName.substring(clsName.lastIndexOf('.') + 1); } else { clsName = getServiceDesc().getName(); } // Default the portType name if (getPortTypeName() == null) { setPortTypeName(clsName); } // Default the serviceElementName if (getServiceElementName() == null) { setServiceElementName(getPortTypeName() + "Service"); } // If service port name is null, construct it from location or className if (getServicePortName() == null) { String name = getLocationUrl(); if (name != null) { if (name.lastIndexOf('/') > 0) { name = name.substring(name.lastIndexOf('/') + 1); } else if (name.lastIndexOf('\\') > 0) { name = name.substring(name.lastIndexOf('\\') + 1); } else { name = null; } // if we got the name from the location, strip .jws from it if ((name != null) && name.endsWith(".jws")) { name = name.substring(0, (name.length() - ".jws".length())); } } if ((name == null) || name.equals("")) { name = clsName; } setServicePortName(name); } // Default the bindingName if (getBindingName() == null) { setBindingName(getServicePortName() + "SoapBinding"); } encodingList = new ArrayList(); encodingList.add(Constants.URI_DEFAULT_SOAP_ENC); if (intfNS == null) { Package pkg = cls.getPackage(); intfNS = namespaces.getCreate((pkg == null) ? null : pkg.getName()); } // Default the implementation namespace to the interface // namespace if not split wsdl mode. if (implNS == null) { if (mode == MODE_ALL) { implNS = intfNS; } else { implNS = intfNS + "-impl"; } } // set the namespaces in the serviceDesc(s) serviceDesc.setDefaultNamespace(intfNS); if (serviceDesc2 != null) { serviceDesc2.setDefaultNamespace(implNS); } if (cls != null) { String clsName = cls.getName(); int idx = clsName.lastIndexOf("."); if (idx > 0) { String pkgName = clsName.substring(0, idx); namespaces.put(pkgName, intfNS, "intf"); } } namespaces.putPrefix(implNS, "impl"); } } /** * Build a Definition from the input wsdl file or create * a new Definition * * @return WSDL Definition * @throws WSDLException * @throws SAXException * @throws IOException * @throws ParserConfigurationException */ protected Definition createDefinition() throws WSDLException, SAXException, IOException, ParserConfigurationException { Definition def; if (inputWSDL == null) { def = WSDLFactory.newInstance().newDefinition(); } else { javax.wsdl.xml.WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); Document doc = XMLUtils.newDocument(inputWSDL); def = reader.readWSDL(null, doc); // The input wsdl types section is deleted. The // types will be added back in at the end of processing. def.setTypes(null); } return def; } /** Field standardTypes */ protected static TypeMapping standardTypes = (TypeMapping) new org.apache.axis.encoding.TypeMappingRegistryImpl().getTypeMapping( null); /** * Build a Types object and load the input wsdl types * * @param def Corresponding wsdl Definition * @return Types object * @throws IOException * @throws WSDLException * @throws SAXException * @throws ParserConfigurationException */ protected Types createTypes(Definition def) throws IOException, WSDLException, SAXException, ParserConfigurationException { types = new Types(def, tm, (TypeMapping)tmr.getDefaultTypeMapping(), namespaces, intfNS, stopClasses, serviceDesc, this); if (inputWSDL != null) { types.loadInputTypes(inputWSDL); } if (inputSchema != null) { StringTokenizer tokenizer = new StringTokenizer(inputSchema, ", "); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); types.loadInputSchema(token); } } // If we're supposed to emit all mapped types, do it now. if (emitAllTypes && tm != null) { Class[] mappedTypes = tm.getAllClasses(); for (int i = 0; i < mappedTypes.length; i++) { Class mappedType = mappedTypes[i]; QName name = tm.getTypeQName(mappedType); if (name.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) != -1) { // If this is an anonymous type, it doesn't need to be // written out here (and trying to do so will generate an // error). Skip it. continue; } /** * If it's a non-standard type, make sure it shows up in * our WSDL */ if (standardTypes.getSerializer(mappedType) == null) { types.writeTypeForPart(mappedType, name); } } // Don't bother checking for subtypes, since we already wrote // all the possibilities. types.mappedTypes = null; } return types; } /** * Create a documentation element * * @param documentation * @return */ protected Element createDocumentationElement(String documentation) { Element element = docHolder.createElementNS(Constants.NS_URI_WSDL11, "documentation"); element.setPrefix(Constants.NS_PREFIX_WSDL); Text textNode = docHolder.createTextNode(documentation); element.appendChild(textNode); return element; } /** * Create the definition header information. * * @param def <code>Definition</code> * @param tns target namespace */ protected void writeDefinitions(Definition def, String tns) { def.setTargetNamespace(tns); def.addNamespace("intf", intfNS); def.addNamespace("impl", implNS); def.addNamespace(Constants.NS_PREFIX_WSDL_SOAP, Constants.URI_WSDL11_SOAP); namespaces.putPrefix(Constants.URI_WSDL11_SOAP, Constants.NS_PREFIX_WSDL_SOAP); def.addNamespace(Constants.NS_PREFIX_WSDL, Constants.NS_URI_WSDL11); namespaces.putPrefix(Constants.NS_URI_WSDL11, Constants.NS_PREFIX_WSDL); if (use == Use.ENCODED) { def.addNamespace(Constants.NS_PREFIX_SOAP_ENC, Constants.URI_DEFAULT_SOAP_ENC); namespaces.putPrefix(Constants.URI_DEFAULT_SOAP_ENC, Constants.NS_PREFIX_SOAP_ENC); } def.addNamespace(Constants.NS_PREFIX_SCHEMA_XSD, Constants.URI_DEFAULT_SCHEMA_XSD); namespaces.putPrefix(Constants.URI_DEFAULT_SCHEMA_XSD, Constants.NS_PREFIX_SCHEMA_XSD); def.addNamespace(Constants.NS_PREFIX_XMLSOAP, Constants.NS_URI_XMLSOAP); namespaces.putPrefix(Constants.NS_URI_XMLSOAP, Constants.NS_PREFIX_XMLSOAP); } /** * Create and add an import * * @param def <code>Definition</code> * @param tns target namespace * @param loc target location */ protected void writeImport(Definition def, String tns, String loc) { Import imp = def.createImport(); imp.setNamespaceURI(tns); if ((loc != null) && !loc.equals("")) { imp.setLocationURI(loc); } def.addImport(imp); } /** * Create the binding. * * @param def <code>Definition</code> * @param add true if binding should be added to the def * @return */ protected Binding writeBinding(Definition def, boolean add) { QName bindingQName = new QName(intfNS, getBindingName()); // If a binding already exists, don't replace it. Binding binding = def.getBinding(bindingQName); if (binding != null) { return binding; } // Create a binding binding = def.createBinding(); binding.setUndefined(false); binding.setQName(bindingQName); SOAPBinding soapBinding = new SOAPBindingImpl(); String styleStr = (style == Style.RPC) ? "rpc" : "document"; soapBinding.setStyle(styleStr); soapBinding.setTransportURI(Constants.URI_SOAP11_HTTP); binding.addExtensibilityElement(soapBinding); if (add) { def.addBinding(binding); } return binding; } /** Field docHolder */ Document docHolder; /** * Method createDocumentFragment */ private void createDocumentFragment() { try { this.docHolder = XMLUtils.newDocument(); } catch (ParserConfigurationException e) { // This should not occur throw new InternalException(e); } } /** * Create the service. * * @param def * @param binding */ protected void writeService(Definition def, Binding binding) { QName serviceElementQName = new QName(implNS, getServiceElementName()); // Locate an existing service, or get a new service Service service = def.getService(serviceElementQName); if (service == null) { service = def.createService(); service.setQName(serviceElementQName); def.addService(service); } if (description != null) { service.setDocumentationElement( createDocumentationElement(description)); } else if (serviceDesc.getDocumentation() != null) { service.setDocumentationElement( createDocumentationElement( serviceDesc.getDocumentation())); } // Add the port Port port = def.createPort(); port.setBinding(binding); // Probably should use the end of the location Url port.setName(getServicePortName()); SOAPAddress addr = new SOAPAddressImpl(); addr.setLocationURI(locationUrl); port.addExtensibilityElement(addr); service.addPort(port); } /** * Create a PortType * * @param def * @param binding * @throws WSDLException * @throws AxisFault */ protected void writePortType(Definition def, Binding binding) throws WSDLException, AxisFault { QName portTypeQName = new QName(intfNS, getPortTypeName()); // Get or create a portType PortType portType = def.getPortType(portTypeQName); boolean newPortType = false; if (portType == null) { portType = def.createPortType(); portType.setUndefined(false); portType.setQName(portTypeQName); newPortType = true; } else if (binding.getBindingOperations().size() > 0) { // If both portType and binding already exist, // no additional processing is needed. return; } // Add the port and binding operations. ArrayList operations = serviceDesc.getOperations(); for (Iterator i = operations.iterator(); i.hasNext();) { OperationDesc thisOper = (OperationDesc) i.next(); BindingOperation bindingOper = writeOperation(def, binding, thisOper); Operation oper = bindingOper.getOperation(); OperationDesc messageOper = thisOper; // add the documentation to oper if (messageOper.getDocumentation() != null) { oper.setDocumentationElement( createDocumentationElement( messageOper.getDocumentation())); } if (serviceDesc2 != null) { // If a serviceDesc containing an impl class is provided, // try and locate the corresponding operation // (same name, same parm types and modes). If a // corresponding operation is found, it is sent // to the writeMessages method so that its parameter // names will be used in the wsdl file. OperationDesc[] operArray = serviceDesc2.getOperationsByName(thisOper.getName()); boolean found = false; if (operArray != null) { for (int j = 0; (j < operArray.length) && !found; j++) { OperationDesc tryOper = operArray[j]; if (tryOper.getParameters().size() == thisOper.getParameters().size()) { boolean parmsMatch = true; for (int k = 0; (k < thisOper.getParameters().size()) && parmsMatch; k++) { if ((tryOper.getParameter( k).getMode() != thisOper.getParameter( k).getMode()) || (!tryOper.getParameter( k).getJavaType().equals( thisOper.getParameter( k).getJavaType()))) { parmsMatch = false; } } if (parmsMatch) { messageOper = tryOper; found = true; } } } } } writeMessages(def, oper, messageOper, bindingOper); if (newPortType) { portType.addOperation(oper); } } if (newPortType) { def.addPortType(portType); } binding.setPortType(portType); } /** * Create a Message * * @param def Definition, the WSDL definition * @param oper Operation, the wsdl operation * @param desc OperationDesc, the Operation Description * @param bindingOper BindingOperation, corresponding Binding Operation * @throws WSDLException * @throws AxisFault */ protected void writeMessages(Definition def, Operation oper, OperationDesc desc, BindingOperation bindingOper) throws WSDLException, AxisFault { Input input = def.createInput(); Message msg = writeRequestMessage(def, desc, bindingOper); input.setMessage(msg); // Give the input element a name that matches the // message. This is necessary for overloading. // The msg QName is unique. String name = msg.getQName().getLocalPart(); input.setName(name); bindingOper.getBindingInput().setName(name); oper.setInput(input); def.addMessage(msg); if (OperationType.REQUEST_RESPONSE.equals(desc.getMep())) { msg = writeResponseMessage(def, desc, bindingOper); Output output = def.createOutput(); output.setMessage(msg); // Give the output element a name that matches the // message. This is necessary for overloading. // The message QName is unique. name = msg.getQName().getLocalPart(); output.setName(name); bindingOper.getBindingOutput().setName(name); oper.setOutput(output); def.addMessage(msg); } ArrayList exceptions = desc.getFaults(); for (int i = 0; (exceptions != null) && (i < exceptions.size()); i++) { FaultDesc faultDesc = (FaultDesc) exceptions.get(i); msg = writeFaultMessage(def, faultDesc); // Add the fault to the portType Fault fault = def.createFault(); fault.setMessage(msg); fault.setName(faultDesc.getName()); oper.addFault(fault); // Add the fault to the binding BindingFault bFault = def.createBindingFault(); bFault.setName(faultDesc.getName()); SOAPFault soapFault = writeSOAPFault(faultDesc); bFault.addExtensibilityElement(soapFault); bindingOper.addBindingFault(bFault); // Add the fault message if (def.getMessage(msg.getQName()) == null) { def.addMessage(msg); } } // Set the parameter ordering using the parameter names ArrayList parameters = desc.getParameters(); Vector names = new Vector(); for (int i = 0; i < parameters.size(); i++) { ParameterDesc param = (ParameterDesc) parameters.get(i); names.add(param.getName()); } if (names.size() > 0) { if (style == Style.WRAPPED) { names.clear(); } else { oper.setParameterOrdering(names); } } } /** * Create a Operation * * @param def * @param binding * @param desc * @return */ protected BindingOperation writeOperation(Definition def, Binding binding, OperationDesc desc) { Operation oper = def.createOperation(); QName elementQName = desc.getElementQName(); if(elementQName != null && elementQName.getLocalPart() != null) { oper.setName(elementQName.getLocalPart()); } else { oper.setName(desc.getName()); } oper.setUndefined(false); return writeBindingOperation(def, binding, oper, desc); } /** * Create a Binding Operation * * @param def * @param binding * @param oper * @param desc * @return */ protected BindingOperation writeBindingOperation(Definition def, Binding binding, Operation oper, OperationDesc desc) { BindingOperation bindingOper = def.createBindingOperation(); BindingInput bindingInput = def.createBindingInput(); BindingOutput bindingOutput = null; // TODO : Make this deal with all MEPs if (OperationType.REQUEST_RESPONSE.equals(desc.getMep())) bindingOutput = def.createBindingOutput(); bindingOper.setName(oper.getName()); bindingOper.setOperation(oper); SOAPOperation soapOper = new SOAPOperationImpl(); // If the soapAction option is OPERATION, force // soapAction to the name of the operation. If NONE, // force soapAction to "". // Otherwise use the information in the operationDesc. String soapAction; if (getSoapAction().equalsIgnoreCase("OPERATION")) { soapAction = oper.getName(); } else if (getSoapAction().equalsIgnoreCase("NONE")) { soapAction = ""; } else { soapAction = desc.getSoapAction(); if (soapAction == null) { soapAction = ""; } } soapOper.setSoapActionURI(soapAction); // Until we have per-operation configuration, this will always be // the same as the binding default. // soapOper.setStyle("rpc"); bindingOper.addExtensibilityElement(soapOper); // Add soap:body element to the binding <input> element ExtensibilityElement inputBody = writeSOAPBody(desc.getElementQName()); bindingInput.addExtensibilityElement(inputBody); // add soap:headers, if any, to binding <input> element // only when we write the Message and parts. // Add soap:body element to the binding <output> element if (bindingOutput != null) { ExtensibilityElement outputBody = writeSOAPBody(desc.getReturnQName()); bindingOutput.addExtensibilityElement(outputBody); bindingOper.setBindingOutput(bindingOutput); // add soap:headers, if any, to binding <output> element // only when we write the Message and parts. } // Add input to operation bindingOper.setBindingInput(bindingInput); // Faults clause // Comment out the following part // because it actually does the same thing as in writeMessages. /* ArrayList faultList = desc.getFaults(); if (faultList != null) { for (Iterator it = faultList.iterator(); it.hasNext();) { FaultDesc faultDesc = (FaultDesc) it.next(); // Get a soap:fault ExtensibilityElement soapFault = writeSOAPFault(faultDesc); // Get a wsdl:fault to put the soap:fault in BindingFault bindingFault = new BindingFaultImpl(); bindingFault.setName(faultDesc.getName()); bindingFault.addExtensibilityElement(soapFault); bindingOper.addBindingFault(bindingFault); } } */ binding.addBindingOperation(bindingOper); return bindingOper; } /** * Create a SOAPHeader element */ protected SOAPHeader writeSOAPHeader(ParameterDesc p, QName messageQName, String partName) { SOAPHeaderImpl soapHeader = new SOAPHeaderImpl(); // for now, if its document, it is literal use. if (use == Use.ENCODED) { soapHeader.setUse("encoded"); soapHeader.setEncodingStyles(encodingList); } else { soapHeader.setUse("literal"); } // Set namespace if (targetService == null) { soapHeader.setNamespaceURI(intfNS); } else { soapHeader.setNamespaceURI(targetService); } QName headerQName = p.getQName(); if ((headerQName != null) && !headerQName.getNamespaceURI().equals("")) { soapHeader.setNamespaceURI(headerQName.getNamespaceURI()); } // Set the Message and Part information soapHeader.setMessage(messageQName); soapHeader.setPart(partName); return soapHeader; } /** * Method writeSOAPBody * * @param operQName * @return */ protected ExtensibilityElement writeSOAPBody(QName operQName) { SOAPBody soapBody = new SOAPBodyImpl(); // for now, if its document, it is literal use. if (use == Use.ENCODED) { soapBody.setUse("encoded"); soapBody.setEncodingStyles(encodingList); } else { soapBody.setUse("literal"); } if (style == Style.RPC) { if (targetService == null) { soapBody.setNamespaceURI(intfNS); } else { soapBody.setNamespaceURI(targetService); } if ((operQName != null) && !operQName.getNamespaceURI().equals("")) { soapBody.setNamespaceURI(operQName.getNamespaceURI()); } } // The parts attribute will get set if we have headers. // This gets done when the Message & parts are generated // soapBody.setParts(...); return soapBody; } // writeSOAPBody /** * Method writeSOAPFault * * @param faultDesc * @return */ protected SOAPFault writeSOAPFault(FaultDesc faultDesc) { SOAPFault soapFault = new com.ibm.wsdl.extensions.soap.SOAPFaultImpl(); soapFault.setName(faultDesc.getName()); if (use != Use.ENCODED) { soapFault.setUse("literal"); // no namespace for literal, gets it from the element } else { soapFault.setUse("encoded"); soapFault.setEncodingStyles(encodingList); // Set the namespace from the fault QName if it exists // otherwise use the target (or interface) namespace QName faultQName = faultDesc.getQName(); if ((faultQName != null) && !faultQName.getNamespaceURI().equals("")) { soapFault.setNamespaceURI(faultQName.getNamespaceURI()); } else { if (targetService == null) { soapFault.setNamespaceURI(intfNS); } else { soapFault.setNamespaceURI(targetService); } } } return soapFault; } // writeSOAPFault /** * Create a Request Message * * @param def * @param oper * @return * @throws WSDLException * @throws AxisFault */ protected Message writeRequestMessage(Definition def, OperationDesc oper, BindingOperation bindop) throws WSDLException, AxisFault { String partName; ArrayList bodyParts = new ArrayList(); ArrayList parameters = oper.getAllInParams(); Message msg = def.createMessage(); QName qName = createMessageName(def, getRequestQName(oper).getLocalPart() + "Request"); msg.setQName(qName); msg.setUndefined(false); // output all the parts for headers boolean headers = writeHeaderParts(def, parameters, bindop, msg, true); if (oper.getStyle() == Style.MESSAGE) { // If this is a MESSAGE-style operation, just write out // <xsd:any> for now. // TODO: Support custom schema in WSDD for these operations QName qname = oper.getElementQName(); types.writeElementDecl(qname, Object.class, Constants.XSD_ANYTYPE, false, null); Part part = def.createPart(); part.setName("part"); part.setElementName(qname); msg.addPart(part); bodyParts.add(part.getName()); } else if (oper.getStyle() == Style.WRAPPED) { // If we're WRAPPED, write the wrapper element first, and then // fill in any params. If there aren't any params, we'll see // an empty <complexType/> for the wrapper element. partName = writeWrapperPart(def, msg, oper, true); bodyParts.add(partName); } else { //Now we're either DOCUMENT or RPC. If we're doing doc/lit, and in the //case of mulitple input params, we would warn user saying request //message's type information is being written out as multiple parts //than one single complexType and to interop with other soap stacks //that do doc/lit by default, user might want to publish his service //as a WRAPPED-LITERAL service instead. //see http://issues.apache.org/jira/browse/AXIS-2017 if(oper.getStyle() == Style.DOCUMENT && parameters.size()>1 ) { System.out.println(Messages.getMessage("warnDocLitInteropMultipleInputParts")); } // write a part for each non-header parameter for (int i = 0; i < parameters.size(); i++) { ParameterDesc parameter = (ParameterDesc) parameters.get(i); if (!parameter.isInHeader() && !parameter.isOutHeader()) { partName = writePartToMessage(def, msg, true, parameter); bodyParts.add(partName); } } } // If we have headers, we must fill in the parts attribute of soap:body // if not, we just leave it out (which means all parts) if (headers) { // Find soap:body in binding List extensibilityElements = bindop.getBindingInput().getExtensibilityElements(); for (int i = 0; i < extensibilityElements.size(); i++) { Object ele = extensibilityElements.get(i); if (ele instanceof SOAPBodyImpl) { SOAPBodyImpl soapBody = (SOAPBodyImpl) ele; soapBody.setParts(bodyParts); } } } return msg; } /** * Create parts of a Message for header parameters and write then in * to the provided Message element. Also create a soap:header element * in the binding * * @param parameters the list of parameters for the current operation * @param bindop the current bindingOperation * @param msg the message to add the parts to * @param request true if we are do an input message, false if it is output * @return true if we wrote any header parts */ private boolean writeHeaderParts(Definition def, ArrayList parameters, BindingOperation bindop, Message msg, boolean request) throws WSDLException, AxisFault { boolean wroteHeaderParts = false; String partName; // Loop over all the parameters for this operation for (int i = 0; i < parameters.size(); i++) { ParameterDesc parameter = (ParameterDesc) parameters.get(i); // write the input or output header parts in to the Message if (request && parameter.isInHeader()) { // put part in message partName = writePartToMessage(def, msg, request, parameter); // Create a soap:header element SOAPHeader hdr = writeSOAPHeader(parameter, msg.getQName(), partName); // put it in the binding <input> element bindop.getBindingInput().addExtensibilityElement(hdr); wroteHeaderParts = true; } else if (!request && parameter.isOutHeader()) { // put part in message partName = writePartToMessage(def, msg, request, parameter); // Create a soap:header element SOAPHeader hdr = writeSOAPHeader(parameter, msg.getQName(), partName); // put it in the binding <output> element bindop.getBindingOutput().addExtensibilityElement(hdr); wroteHeaderParts = true; } else { continue; // body part } } return wroteHeaderParts; } /** * Method getRequestQName * * @param oper * @return */ protected QName getRequestQName(OperationDesc oper) { qualifyOperation(oper); QName qname = oper.getElementQName(); if (qname == null) { qname = new QName(oper.getName()); } return qname; } /** * Method qualifyOperation * * @param oper */ private void qualifyOperation(OperationDesc oper) { if ((style == Style.WRAPPED) && (use == Use.LITERAL)) { QName qname = oper.getElementQName(); if (qname == null) { qname = new QName(intfNS, oper.getName()); } else if (qname.getNamespaceURI().equals("")) { qname = new QName(intfNS, qname.getLocalPart()); } oper.setElementQName(qname); } } /** * Method getResponseQName * * @param oper * @return */ protected QName getResponseQName(OperationDesc oper) { qualifyOperation(oper); QName qname = oper.getElementQName(); if (qname == null) { return new QName(oper.getName() + "Response"); } return new QName(qname.getNamespaceURI(), qname.getLocalPart() + "Response"); } /** * Write out the schema definition for a WRAPPED operation request or * response. * * @param def * @param msg * @param oper * @param request * @return the name of the part the was written * @throws AxisFault */ public String writeWrapperPart( Definition def, Message msg, OperationDesc oper, boolean request) throws AxisFault { QName qname = request ? getRequestQName(oper) : getResponseQName(oper); boolean hasParams; if (request) { hasParams = (oper.getNumInParams() > 0); } else { if (oper.getReturnClass() != void.class) { hasParams = true; } else { hasParams = (oper.getNumOutParams() > 0); } } // First write the wrapper element itself. Element sequence = types.writeWrapperElement(qname, request, hasParams); // If we got anything back above, there must be parameters in the // operation, and it's a <sequence> node in which to write them... if (sequence != null) { ArrayList parameters = request ? oper.getAllInParams() : oper.getAllOutParams(); if (!request) { String retName; if (oper.getReturnQName() == null) { retName = oper.getName() + "Return"; } else { retName = oper.getReturnQName().getLocalPart(); } types.writeWrappedParameter(sequence, retName, oper.getReturnType(), oper.getReturnClass()); } for (int i = 0; i < parameters.size(); i++) { ParameterDesc parameter = (ParameterDesc) parameters.get(i); // avoid headers if (!parameter.isInHeader() && !parameter.isOutHeader()) { types.writeWrappedParameter(sequence, parameter.getName(), parameter.getTypeQName(), parameter.getJavaType()); } } } // Finally write the part itself Part part = def.createPart(); part.setName("parameters"); // We always use "parameters" part.setElementName(qname); msg.addPart(part); return part.getName(); } /** * Create a Response Message * * @param def * @param desc * @return * @throws WSDLException * @throws AxisFault */ protected Message writeResponseMessage(Definition def, OperationDesc desc, BindingOperation bindop) throws WSDLException, AxisFault { String partName; ArrayList bodyParts = new ArrayList(); ArrayList parameters = desc.getAllOutParams(); Message msg = def.createMessage(); QName qName = createMessageName(def, getResponseQName(desc).getLocalPart()); msg.setQName(qName); msg.setUndefined(false); // output all the parts for headers boolean headers = writeHeaderParts(def, parameters, bindop, msg, false); if (desc.getStyle() == Style.WRAPPED) { partName = writeWrapperPart(def, msg, desc, false); bodyParts.add(partName); } else { // Write the return value part ParameterDesc retParam = new ParameterDesc(); if (desc.getReturnQName() == null) { String ns = ""; if (desc.getStyle() != Style.RPC) { ns = getServiceDesc().getDefaultNamespace(); if ((ns == null) || "".equals(ns)) { ns = "http://ws.apache.org/axis/defaultNS"; } } retParam.setQName(new QName(ns, desc.getName() + "Return")); } else { retParam.setQName(desc.getReturnQName()); } retParam.setTypeQName(desc.getReturnType()); retParam.setMode(ParameterDesc.OUT); retParam.setIsReturn(true); retParam.setJavaType(desc.getReturnClass()); String returnPartName = writePartToMessage(def, msg, false, retParam); bodyParts.add(returnPartName); // write a part for each non-header parameter for (int i = 0; i < parameters.size(); i++) { ParameterDesc parameter = (ParameterDesc) parameters.get(i); if (!parameter.isInHeader() && !parameter.isOutHeader()) { partName = writePartToMessage(def, msg, false, parameter); bodyParts.add(partName); } } } // If we have headers, we must fill in the parts attribute of soap:body // if not, we just leave it out (which means all parts) if (headers) { // Find soap:body in binding List extensibilityElements = bindop.getBindingOutput().getExtensibilityElements(); for (int i = 0; i < extensibilityElements.size(); i++) { Object ele = extensibilityElements.get(i); if (ele instanceof SOAPBodyImpl) { SOAPBodyImpl soapBody = (SOAPBodyImpl) ele; soapBody.setParts(bodyParts); } } } return msg; } /** * Create a Fault Message * * @param def * @param exception (an ExceptionRep object) * @return * @throws WSDLException * @throws AxisFault */ protected Message writeFaultMessage(Definition def, FaultDesc exception) throws WSDLException, AxisFault { String pkgAndClsName = exception.getClassName(); String clsName = pkgAndClsName.substring(pkgAndClsName.lastIndexOf('.') + 1, pkgAndClsName.length()); // Do this to cover the complex type case with no meta data exception.setName(clsName); // The following code uses the class name for both the name= attribute // and the message= attribute. Message msg = (Message) exceptionMsg.get(pkgAndClsName); if (msg == null) { msg = def.createMessage(); QName qName = createMessageName(def, clsName); msg.setQName(qName); msg.setUndefined(false); ArrayList parameters = exception.getParameters(); if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterDesc parameter = (ParameterDesc) parameters.get(i); writePartToMessage(def, msg, true, parameter); } } exceptionMsg.put(pkgAndClsName, msg); } return msg; } /** * Create a Part * * @param def * @param msg * @param request message is for a request * @param param ParamRep object * @return The parameter name added or null * @throws WSDLException * @throws AxisFault */ public String writePartToMessage( Definition def, Message msg, boolean request, ParameterDesc param) throws WSDLException, AxisFault { // Return if this is a void type if ((param == null) || (param.getJavaType() == java.lang.Void.TYPE)) { return null; } // If Request message, only continue if IN or INOUT // If Response message, only continue if OUT or INOUT if (request && (param.getMode() == ParameterDesc.OUT)) { return null; } if (!request && (param.getMode() == ParameterDesc.IN)) { return null; } // Create the Part Part part = def.createPart(); if (param.getDocumentation() != null) { part.setDocumentationElement( createDocumentationElement( param.getDocumentation())); } // Get the java type to represent in the wsdl // (if the mode is OUT or INOUT and this // parameter does not represent the return type, // the type held in the Holder is the one that should // be written.) Class javaType = param.getJavaType(); if ((param.getMode() != ParameterDesc.IN) && (param.getIsReturn() == false)) { javaType = JavaUtils.getHolderValueType(javaType); } if ((use == Use.ENCODED) || (style == Style.RPC)) { // Add the type representing the param // Write <part name=param_name type=param_type> QName typeQName = param.getTypeQName(); if (javaType != null) { typeQName = types.writeTypeAndSubTypeForPart(javaType, typeQName); } // types.writeElementForPart(javaType, param.getTypeQName()); if (typeQName != null) { part.setName(param.getName()); part.setTypeName(typeQName); msg.addPart(part); } } else if (use == Use.LITERAL) { // This is doc/lit. So we should write out an element // declaration whose name and type may be found in the // ParameterDesc. QName qname = param.getQName(); if (param.getTypeQName() == null) { log.warn(Messages.getMessage("registerTypeMappingFor01", param.getJavaType().getName())); QName qName = types.writeTypeForPart(param.getJavaType(),null); if (qName != null) { param.setTypeQName(qName); } else { param.setTypeQName(Constants.XSD_ANYTYPE); } } if (param.getTypeQName().getNamespaceURI().equals("")) { param.setTypeQName( new QName(intfNS, param.getTypeQName().getLocalPart())); } if (param.getQName().getNamespaceURI().equals("")) { qname = new QName(intfNS, param.getQName().getLocalPart()); param.setQName(qname); } // Make sure qname's value is unique. ArrayList names = (ArrayList) usedElementNames.get(qname.getNamespaceURI()); if (names == null) { names = new ArrayList(1); usedElementNames.put(qname.getNamespaceURI(), names); } else if (names.contains(qname.getLocalPart())) { qname = new QName(qname.getNamespaceURI(), JavaUtils.getUniqueValue(names, qname.getLocalPart())); } names.add(qname.getLocalPart()); types.writeElementDecl(qname, param.getJavaType(), param.getTypeQName(), false, param.getItemQName()); part.setName(param.getName()); part.setElementName(qname); msg.addPart(part); } // return the name of the parameter added return param.getName(); } /* * Return a message QName which has not already been defined in the WSDL */ /** * Method createMessageName * * @param def * @param methodName * @return */ protected QName createMessageName(Definition def, String methodName) { QName qName = new QName(intfNS, methodName); // Check the make sure there isn't a message with this name already int messageNumber = 1; while (def.getMessage(qName) != null) { StringBuffer namebuf = new StringBuffer(methodName); namebuf.append(messageNumber); qName = new QName(intfNS, namebuf.toString()); messageNumber++; } return qName; } /** * Write a prettified document to a file. * * @param doc the Document to write * @param filename the name of the file to be written * @throws IOException various file i/o exceptions */ protected void prettyDocumentToFile(Document doc, String filename) throws IOException { FileOutputStream fos = new FileOutputStream(new File(filename)); XMLUtils.PrettyDocumentToStream(doc, fos); fos.close(); } // -------------------- Parameter Query Methods ----------------------------// /** * Returns the <code>Class</code> to export * * @return the <code>Class</code> to export */ public Class getCls() { return cls; } /** * Sets the <code>Class</code> to export * * @param cls the <code>Class</code> to export */ public void setCls(Class cls) { this.cls = cls; } /** * Sets the <code>Class</code> to export. * * @param cls the <code>Class</code> to export * @param location */ public void setClsSmart(Class cls, String location) { if ((cls == null) || (location == null)) { return; } // Strip off \ and / from location if (location.lastIndexOf('/') > 0) { location = location.substring(location.lastIndexOf('/') + 1); } else if (location.lastIndexOf('\\') > 0) { location = location.substring(location.lastIndexOf('\\') + 1); } // Get the constructors of the class java.lang.reflect.Constructor[] constructors = cls.getDeclaredConstructors(); Class intf = null; for (int i = 0; (i < constructors.length) && (intf == null); i++) { Class[] parms = constructors[i].getParameterTypes(); // If the constructor has a single parameter // that is an interface which // matches the location, then use this as the interface class. if ((parms.length == 1) && parms[0].isInterface() && (parms[0].getName() != null) && Types.getLocalNameFromFullName( parms[0].getName()).equals(location)) { intf = parms[0]; } } if (intf != null) { setCls(intf); if (implCls == null) { setImplCls(cls); } } else { setCls(cls); } } /** * Returns the implementation <code>Class</code> if set * * @return the implementation Class or null */ public Class getImplCls() { return implCls; } /** * Sets the implementation <code>Class</code> * * @param implCls the <code>Class</code> to export */ public void setImplCls(Class implCls) { this.implCls = implCls; } /** * Returns the interface namespace * * @return interface target namespace */ public String getIntfNamespace() { return intfNS; } /** * Set the interface namespace * * @param ns interface target namespace */ public void setIntfNamespace(String ns) { this.intfNS = ns; } /** * Returns the implementation namespace * * @return implementation target namespace */ public String getImplNamespace() { return implNS; } /** * Set the implementation namespace * * @param ns implementation target namespace */ public void setImplNamespace(String ns) { this.implNS = ns; } /** * Returns a vector of methods to export * * @return a space separated list of methods to export */ public Vector getAllowedMethods() { return allowedMethods; } /** * Add a list of methods to export * * @param text */ public void setAllowedMethods(String text) { if (text != null) { StringTokenizer tokenizer = new StringTokenizer(text, " ,+"); if (allowedMethods == null) { allowedMethods = new Vector(); } while (tokenizer.hasMoreTokens()) { allowedMethods.add(tokenizer.nextToken()); } } } /** * Add a Vector of methods to export * * @param allowedMethods a vector of methods to export */ public void setAllowedMethods(Vector allowedMethods) { if (this.allowedMethods == null) { this.allowedMethods = new Vector(); } this.allowedMethods.addAll(allowedMethods); } /** * Indicates if the emitter will search classes for inherited methods * * @return */ public boolean getUseInheritedMethods() { return useInheritedMethods; } /** * Turn on or off inherited method WSDL generation. * * @param useInheritedMethods */ public void setUseInheritedMethods(boolean useInheritedMethods) { this.useInheritedMethods = useInheritedMethods; } /** * Add a list of methods NOT to export * * @param disallowedMethods vector of method name strings */ public void setDisallowedMethods(Vector disallowedMethods) { if (this.disallowedMethods == null) { this.disallowedMethods = new Vector(); } this.disallowedMethods.addAll(disallowedMethods); } /** * Add a list of methods NOT to export * * @param text space separated list of method names */ public void setDisallowedMethods(String text) { if (text != null) { StringTokenizer tokenizer = new StringTokenizer(text, " ,+"); if (disallowedMethods == null) { disallowedMethods = new Vector(); } disallowedMethods = new Vector(); while (tokenizer.hasMoreTokens()) { disallowedMethods.add(tokenizer.nextToken()); } } } /** * Return list of methods that should not be exported * * @return */ public Vector getDisallowedMethods() { return disallowedMethods; } /** * Adds a list of classes (fully qualified) that will stop the traversal * of the inheritance tree if encounter in method or complex type generation * * @param stopClasses vector of class name strings */ public void setStopClasses(ArrayList stopClasses) { if (this.stopClasses == null) { this.stopClasses = new ArrayList(); } this.stopClasses.addAll(stopClasses); } /** * Add a list of classes (fully qualified) that will stop the traversal * of the inheritance tree if encounter in method or complex type generation * * @param text space separated list of class names */ public void setStopClasses(String text) { if (text != null) { StringTokenizer tokenizer = new StringTokenizer(text, " ,+"); if (stopClasses == null) { stopClasses = new ArrayList(); } while (tokenizer.hasMoreTokens()) { stopClasses.add(tokenizer.nextToken()); } } } /** * Return the list of classes which stop inhertance searches * * @return */ public ArrayList getStopClasses() { return stopClasses; } /** * get the packagename to namespace map * * @return <code>Map</code> */ public Map getNamespaceMap() { return namespaces; } /** * Set the packagename to namespace map with the given map * * @param map packagename/namespace <code>Map</code> */ public void setNamespaceMap(Map map) { if (map != null) { namespaces.putAll(map); } } /** * Get the name of the input WSDL * * @return name of the input wsdl or null */ public String getInputWSDL() { return inputWSDL; } /** * Set the name of the input WSDL * * @param inputWSDL the name of the input WSDL */ public void setInputWSDL(String inputWSDL) { this.inputWSDL = inputWSDL; } /** * @return the name of the input schema, or null */ public String getInputSchema() { return inputSchema; } /** * Set the name of the input schema * * @param inputSchema the name of the input schema */ public void setInputSchema(String inputSchema) { this.inputSchema = inputSchema; } /** * Returns the String representation of the service endpoint URL * * @return String representation of the service endpoint URL */ public String getLocationUrl() { return locationUrl; } /** * Set the String representation of the service endpoint URL * * @param locationUrl the String representation of the service endpoint URL */ public void setLocationUrl(String locationUrl) { this.locationUrl = locationUrl; } /** * Returns the String representation of the interface import location URL * * @return String representation of the interface import location URL */ public String getImportUrl() { return importUrl; } /** * Set the String representation of the interface location URL * for importing * * @param importUrl the String representation of the interface * location URL for importing */ public void setImportUrl(String importUrl) { this.importUrl = importUrl; } /** * Returns the String representation of the service port name * * @return String representation of the service port name */ public String getServicePortName() { return servicePortName; } /** * Set the String representation of the service port name * * @param servicePortName the String representation of the service port name */ public void setServicePortName(String servicePortName) { this.servicePortName = servicePortName; } /** * Returns the String representation of the service element name * * @return String representation of the service element name */ public String getServiceElementName() { return serviceElementName; } /** * Set the String representation of the service element name * * @param serviceElementName the String representation of the service element name */ public void setServiceElementName(String serviceElementName) { this.serviceElementName = serviceElementName; } /** * Returns the String representation of the portType name * * @return String representation of the portType name */ public String getPortTypeName() { return portTypeName; } /** * Set the String representation of the portType name * * @param portTypeName the String representation of the portType name */ public void setPortTypeName(String portTypeName) { this.portTypeName = portTypeName; } /** * Returns the String representation of the binding name * * @return String representation of the binding name */ public String getBindingName() { return bindingName; } /** * Set the String representation of the binding name * * @param bindingName the String representation of the binding name */ public void setBindingName(String bindingName) { this.bindingName = bindingName; } /** * Returns the target service name * * @return the target service name */ public String getTargetService() { return targetService; } /** * Set the target service name * * @param targetService the target service name */ public void setTargetService(String targetService) { this.targetService = targetService; } /** * Returns the service description * * @return service description String */ public String getDescription() { return description; } /** * Set the service description * * @param description service description String */ public void setDescription(String description) { this.description = description; } /** * Returns the soapAction option value * * @return the String DEFAULT, NONE or OPERATION */ public String getSoapAction() { return soapAction; } /** * Sets the soapAction option value * * @param value must be DEFAULT, NONE, or OPERATION */ public void setSoapAction(String value) { soapAction = value; } /** * Returns the <code>TypeMapping</code> used by the service * * @return the <code>TypeMapping</code> used by the service */ public TypeMapping getTypeMapping() { return tm; } /** * Sets the <code>TypeMapping</code> used by the service * * @param tm the <code>TypeMapping</code> used by the service */ public void setTypeMapping(TypeMapping tm) { this.tm = tm; } /** * Returns the <code>defaultTypeMapping</code> used by the service * @return the <code>defaultTypeMapping</code> used by the service * @deprecated Use getTypeMappingRegistry instead */ public TypeMapping getDefaultTypeMapping() { return (TypeMapping) tmr.getDefaultTypeMapping(); } /** * Sets the <code>defaultTypeMapping</code> used by the service * @param tm the <code>defaultTypeMapping</code> used by the service * @deprecated Use setTypeMappingRegistry instead */ public void setDefaultTypeMapping(TypeMapping tm) { tmr.registerDefault(tm); } /** * Set the TypeMappingRegistry for this Emitter. */ public void setTypeMappingRegistry(TypeMappingRegistry tmr) { this.tmr = tmr; } /** * getStyle * * @return Style setting (Style.RPC, Style.DOCUMENT, Style.WRAPPED, etc.) */ public Style getStyle() { return style; } /** * setStyle * * @param value String representing a style ("document", "rpc", "wrapped") * Note that the case of the string is not important. "document" and "DOCUMENT" * are both treated as document style. * If the value is not a know style, the default setting is used. * See org.apache.axis.constants.Style for a description of the interaction between * Style/Use * <br>NOTE: If style is specified as "wrapped", use is set to literal. */ public void setStyle(String value) { setStyle(Style.getStyle(value)); } /** * setStyle * * @param value Style setting */ public void setStyle(Style value) { style = value; if (style.equals(Style.WRAPPED)) { setUse(Use.LITERAL); } } /** * getUse * * @return Use setting (Use.ENCODED, Use.LITERAL) */ public Use getUse() { return use; } /** * setUse * * @param value String representing a use ("literal", "encoded") * Note that the case of the string is not important. "literal" and "LITERAL" * are both treated as literal use. * If the value is not a know use, the default setting is used. * See org.apache.axis.constants.Style for a description of the interaction between * Style/Use */ public void setUse(String value) { use = Use.getUse(value); } /** * setUse * * @param value Use setting */ public void setUse(Use value) { use = value; } /** * setMode (sets style and use) * * @param mode * @deprecated (use setStyle and setUse) */ public void setMode(int mode) { if (mode == MODE_RPC) { setStyle(Style.RPC); setUse(Use.ENCODED); } else if (mode == MODE_DOCUMENT) { setStyle(Style.DOCUMENT); setUse(Use.LITERAL); } else if (mode == MODE_DOC_WRAPPED) { setStyle(Style.WRAPPED); setUse(Use.LITERAL); } } /** * getMode (gets the mode based on the style setting) * * @return returns the mode (-1 if invalid) * @deprecated (use getStyle and getUse) */ public int getMode() { if (style == Style.RPC) { return MODE_RPC; } else if (style == Style.DOCUMENT) { return MODE_DOCUMENT; } else if (style == Style.WRAPPED) { return MODE_DOC_WRAPPED; } return -1; } /** * Method getServiceDesc * * @return */ public ServiceDesc getServiceDesc() { return serviceDesc; } /** * Method setServiceDesc * * @param serviceDesc */ public void setServiceDesc(ServiceDesc serviceDesc) { this.serviceDesc = serviceDesc; } /** * Return the list of extra classes that the emitter will produce WSDL for. * * @return */ public Class[] getExtraClasses() { return extraClasses; } /** * Provide a list of classes which the emitter will produce WSDL * type definitions for. * * @param extraClasses */ public void setExtraClasses(Class[] extraClasses) { this.extraClasses = extraClasses; } /** * Convenience method that processes a comma or space separated list of classes which the * emitter will produce WSDL type definitions for. The classes will be added to the current * list. * * @param text * a comma or space separated list of class names * @param classLoader * the class loader that should be used to load the classes * @throws ClassNotFoundException */ public void setExtraClasses(String text, ClassLoader classLoader) throws ClassNotFoundException { ArrayList clsList = new ArrayList(); if (text != null) { StringTokenizer tokenizer = new StringTokenizer(text, " ,"); while (tokenizer.hasMoreTokens()) { String clsName = tokenizer.nextToken(); // Let the caller handler ClassNotFoundException Class cls = classLoader.loadClass(clsName); clsList.add(cls); } } // Allocate the new array Class[] ec; int startOffset = 0; if (extraClasses != null) { ec = new Class[clsList.size() + extraClasses.length]; // copy existing elements for (int i = 0; i < extraClasses.length; i++) { Class c = extraClasses[i]; ec[i] = c; } startOffset = extraClasses.length; } else { ec = new Class[clsList.size()]; } // copy the new classes for (int i = 0; i < clsList.size(); i++) { Class c = (Class) clsList.get(i); ec[startOffset + i] = c; } // set the member variable this.extraClasses = ec; } public void setEmitAllTypes(boolean emitAllTypes) { this.emitAllTypes = emitAllTypes; } /** * Return the version message * @return message or null if emitter will use the default */ public String getVersionMessage() { return versionMessage; } /** * Set the version message that appears at the top of the WSDL * If not set, we use the default version message. * If set to an empty string, no version message will be emitted * @param versionMessage the message to emit */ public void setVersionMessage(String versionMessage) { this.versionMessage = versionMessage; } /** * Return the type qname to java type mapping * @return mapping of type qname to its corresponding java type */ public HashMap getQName2ClassMap() { return qName2ClassMap; } }
7,755
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/gen/Parser.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.gen; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.CollectionElement; import org.apache.axis.wsdl.symbolTable.MessageEntry; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.Type; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.axis.wsdl.symbolTable.Utils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.SAXException; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.WSDLException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * This is a class with no documentation. */ public class Parser { private static final Log log = LogFactory.getLog(Parser.class.getName()); /** Field debug */ protected boolean debug = false; /** Field quiet */ protected boolean quiet = false; /** Field imports */ protected boolean imports = true; /** Field verbose */ protected boolean verbose = false; /** Field nowrap */ protected boolean nowrap = false; // Username and password for Authentication /** Field username */ protected String username = null; /** Field password */ protected String password = null; /** If this is false, we'll prefer "String[]" to "ArrayOfString" for literal wrapped arrays */ protected boolean wrapArrays = false; protected EntityResolver entityResolver; // Timeout, in milliseconds, to let the Emitter do its work /** Field timeoutms */ private long timeoutms = 45000; // 45 sec default /** Field genFactory */ private GeneratorFactory genFactory = null; /** Field symbolTable */ private SymbolTable symbolTable = null; /** * Method isDebug * * @return */ public boolean isDebug() { return debug; } // isDebug /** * Method setDebug * * @param debug */ public void setDebug(boolean debug) { this.debug = debug; } // setDebug /** * Method isQuiet * * @return */ public boolean isQuiet() { return quiet; } /** * Method setQuiet * * @param quiet */ public void setQuiet(boolean quiet) { this.quiet = quiet; } /** * Method isImports * * @return */ public boolean isImports() { return imports; } // isImports /** * Method setImports * * @param imports */ public void setImports(boolean imports) { this.imports = imports; } // setImports /** * Method isVerbose * * @return */ public boolean isVerbose() { return verbose; } // isVerbose /** * Method setVerbose * * @param verbose */ public void setVerbose(boolean verbose) { this.verbose = verbose; } // setVerbose /** * Method isNowrap * * @return */ public boolean isNowrap() { return nowrap; } /** * Method setNowrap * * @param nowrap */ public void setNowrap(boolean nowrap) { this.nowrap = nowrap; } /** * Get the entity resolver configured for this parser. * * @return the entity resolver, or <code>null</code> if no entity resolver is configured */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Set the entity resolver for this parser. This is used to load the WSDL file (unless it is * supplied as a {@link Document}) and all imported WSDL and schema documents. * * @param entityResolver * the entity resolver, or <code>null</code> to use a default entity resolver */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * Return the current timeout setting * * @return */ public long getTimeout() { return timeoutms; } /** * Set the timeout, in milliseconds * * @param timeout */ public void setTimeout(long timeout) { this.timeoutms = timeout; } /** * Method getUsername * * @return */ public String getUsername() { return username; } // getUsername /** * Method setUsername * * @param username */ public void setUsername(String username) { this.username = username; } // setUsername /** * Method getPassword * * @return */ public String getPassword() { return password; } // getPassword /** * Method setPassword * * @param password */ public void setPassword(String password) { this.password = password; } // setPassword /** * Method getFactory * * @return */ public GeneratorFactory getFactory() { return genFactory; } // getFactory /** * Method setFactory * * @param factory */ public void setFactory(GeneratorFactory factory) { this.genFactory = factory; } // setFactory /** * Get the symbol table. The symbol table is null until * run is called. * * @return */ public SymbolTable getSymbolTable() { return symbolTable; } // getSymbolTable /** * Return the current definition. The current definition is * null until run is called. * * @return */ public Definition getCurrentDefinition() { return (symbolTable == null) ? null : symbolTable.getDefinition(); } // getCurrentDefinition /** * Get the current WSDL URI. The WSDL URI is null until * run is called. * * @return */ public String getWSDLURI() { return (symbolTable == null) ? null : symbolTable.getWSDLURI(); } // getWSDLURI /** * Parse a WSDL at a given URL. * <p> * This method will time out after the number of milliseconds specified * by our timeoutms member. * * @param wsdlURI * @throws Exception */ public void run(String wsdlURI) throws Exception { if (getFactory() == null) { setFactory(new NoopFactory()); } symbolTable = new SymbolTable(genFactory.getBaseTypeMapping(), imports, verbose, nowrap); symbolTable.setQuiet(quiet); symbolTable.setWrapArrays(wrapArrays); symbolTable.setEntityResolver(entityResolver); // We run the actual Emitter in a thread that we can kill WSDLRunnable runnable = new WSDLRunnable(symbolTable, wsdlURI); Thread wsdlThread = new Thread(runnable); wsdlThread.start(); try { if (timeoutms > 0) { wsdlThread.join(timeoutms); } else { wsdlThread.join(); } } catch (InterruptedException e) { } if (wsdlThread.isAlive()) { wsdlThread.interrupt(); throw new IOException(Messages.getMessage("timedOut")); } if (runnable.getFailure() != null) { Throwable failure = runnable.getFailure(); if (failure instanceof Exception) { throw (Exception)failure; } else if (failure instanceof Error){ throw (Error)failure; } else { throw new Error(failure); } } } // run /** * Class WSDLRunnable * * @version %I%, %G% */ private class WSDLRunnable implements Runnable { /** Field symbolTable */ private SymbolTable symbolTable; /** Field wsdlURI */ private String wsdlURI; /** Field failure */ private Throwable failure = null; /** * Constructor WSDLRunnable * * @param symbolTable * @param wsdlURI */ public WSDLRunnable(SymbolTable symbolTable, String wsdlURI) { this.symbolTable = symbolTable; this.wsdlURI = wsdlURI; } // ctor /** * Method run */ public void run() { try { symbolTable.populate(wsdlURI, username, password); generate(symbolTable); } catch (Throwable e) { failure = e; } } // run /** * Method getFailure * * @return */ public Throwable getFailure() { return failure; } // getFailure } // WSDLRunnable /** * Call this method if your WSDL document has already been parsed as an XML DOM document. * * @param context context This is directory context for the Document. If the Document were from file "/x/y/z.wsdl" then the context could be "/x/y" (even "/x/y/z.wsdl" would work). If context is null, then the context becomes the current directory. * @param doc doc This is the XML Document containing the WSDL. * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException */ public void run(String context, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { if (getFactory() == null) { setFactory(new NoopFactory()); } symbolTable = new SymbolTable(genFactory.getBaseTypeMapping(), imports, verbose, nowrap); symbolTable.setEntityResolver(entityResolver); symbolTable.populate(context, doc); generate(symbolTable); } // run /** * Method sanityCheck * * @param symbolTable */ protected void sanityCheck(SymbolTable symbolTable) { // do nothing. } private static void generate(Generator gen) throws IOException { if (log.isDebugEnabled()) { log.debug("Invoking generator " + gen); } gen.generate(); } /** * Method generate * * @param symbolTable * @throws IOException */ private void generate(SymbolTable symbolTable) throws IOException { sanityCheck(symbolTable); Definition def = symbolTable.getDefinition(); genFactory.generatorPass(def, symbolTable); if (isDebug()) { symbolTable.dump(System.out); } // Generate bindings for types generateTypes(symbolTable); Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); Generator gen = null; if (entry instanceof MessageEntry) { gen = genFactory.getGenerator( ((MessageEntry) entry).getMessage(), symbolTable); } else if (entry instanceof PortTypeEntry) { PortTypeEntry pEntry = (PortTypeEntry) entry; // If the portType is undefined, then we're parsing a Definition // that didn't contain a portType, merely a binding that referred // to a non-existent port type. Don't bother writing it. if (pEntry.getPortType().isUndefined()) { continue; } gen = genFactory.getGenerator(pEntry.getPortType(), symbolTable); } else if (entry instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) entry; Binding binding = bEntry.getBinding(); // If the binding is undefined, then we're parsing a Definition // that didn't contain a binding, merely a service that referred // to a non-existent binding. Don't bother writing it. if (binding.isUndefined() || !bEntry.isReferenced()) { continue; } gen = genFactory.getGenerator(binding, symbolTable); } else if (entry instanceof ServiceEntry) { gen = genFactory.getGenerator( ((ServiceEntry) entry).getService(), symbolTable); } if (gen != null) { generate(gen); } } } // Output extra stuff (deployment files and faults) // outside of the recursive emit method. Generator gen = genFactory.getGenerator(def, symbolTable); generate(gen); } // generate /** * Generate bindings (classes and class holders) for the complex types. * If generating serverside (skeleton) spit out beanmappings * * @param symbolTable * @throws IOException */ private void generateTypes(SymbolTable symbolTable) throws IOException { Map elements = symbolTable.getElementIndex(); Collection elementCollection = elements.values(); for (Iterator i = elementCollection.iterator(); i.hasNext(); ) { TypeEntry type = (TypeEntry) i.next(); // Write out the type if and only if: // - we found its definition (getNode()) // - it is referenced // - it is not a base type or an attributeGroup or xs:group // - it is a Type (not an Element) or a CollectionElement // (Note that types that are arrays are passed to getGenerator // because they may require a Holder) // A CollectionElement is an array that might need a holder boolean isType = ((type instanceof Type) || (type instanceof CollectionElement)); if ((type.getNode() != null) && !Utils.isXsNode(type.getNode(), "attributeGroup") && !Utils.isXsNode(type.getNode(), "group") && type.isReferenced() && isType && (type.getBaseType() == null)) { Generator gen = genFactory.getGenerator(type, symbolTable); generate(gen); } } Map types = symbolTable.getTypeIndex(); Collection typeCollection = types.values(); for (Iterator i = typeCollection.iterator(); i.hasNext(); ) { TypeEntry type = (TypeEntry) i.next(); // Write out the type if and only if: // - we found its definition (getNode()) // - it is referenced // - it is not a base type or an attributeGroup or xs:group // - it is a Type (not an Element) or a CollectionElement // (Note that types that are arrays are passed to getGenerator // because they may require a Holder) // A CollectionElement is an array that might need a holder boolean isType = ((type instanceof Type) || (type instanceof CollectionElement)); if ((type.getNode() != null) && !Utils.isXsNode(type.getNode(), "attributeGroup") && !Utils.isXsNode(type.getNode(), "group") && type.isReferenced() && isType && (type.getBaseType() == null)) { Generator gen = genFactory.getGenerator(type, symbolTable); generate(gen); } } } // generateTypes } // class Parser
7,756
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/gen/NoopGenerator.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.gen; import java.io.IOException; /** * This generator doesn't do anything. */ public class NoopGenerator implements Generator { /** * Do a whole lot of nothing. * * @throws IOException */ public void generate() throws IOException { } // generate } // class NoopGenerator
7,757
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/gen/NoopFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.gen; import org.apache.axis.encoding.DefaultSOAPEncodingTypeMappingImpl; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.symbolTable.BaseTypeMapping; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Message; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.xml.namespace.QName; /** * This factory returns a bunch of NoopGenerators */ public class NoopFactory implements GeneratorFactory { /** * Method generatorPass * * @param def * @param symbolTable */ public void generatorPass(Definition def, SymbolTable symbolTable) { } // generatorPass /** * Method getGenerator * * @param message * @param symbolTable * @return */ public Generator getGenerator(Message message, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** * Method getGenerator * * @param portType * @param symbolTable * @return */ public Generator getGenerator(PortType portType, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** * Method getGenerator * * @param binding * @param symbolTable * @return */ public Generator getGenerator(Binding binding, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** * Method getGenerator * * @param service * @param symbolTable * @return */ public Generator getGenerator(Service service, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** * Method getGenerator * * @param type * @param symbolTable * @return */ public Generator getGenerator(TypeEntry type, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** * Method getGenerator * * @param definition * @param symbolTable * @return */ public Generator getGenerator(Definition definition, SymbolTable symbolTable) { return new NoopGenerator(); } // getGenerator /** Field btm */ private BaseTypeMapping btm = null; /** * Method setBaseTypeMapping * * @param btm */ public void setBaseTypeMapping(BaseTypeMapping btm) { this.btm = btm; } // setBaseTypeMapping /** * Method getBaseTypeMapping * * @return */ public BaseTypeMapping getBaseTypeMapping() { if (btm == null) { btm = new BaseTypeMapping() { TypeMapping defaultTM = DefaultSOAPEncodingTypeMappingImpl.createWithDelegate(); public String getBaseName(QName qNameIn) { javax.xml.namespace.QName qName = new javax.xml.namespace.QName(qNameIn.getNamespaceURI(), qNameIn.getLocalPart()); Class cls = defaultTM.getClassForQName(qName); if (cls == null) { return null; } else { // RJB NOTE: Javaism - bad bad bad return JavaUtils.getTextClassName(cls.getName()); } } }; } return btm; } // getBaseTypeMapping } // class NoopFactory
7,758
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/gen/GeneratorFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.gen; import org.apache.axis.wsdl.symbolTable.BaseTypeMapping; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Message; import javax.wsdl.PortType; import javax.wsdl.Service; /** * Generator and Generatoractory are part of the generator framework. * Folks who want to use the emitter to generate stuff from WSDL should * do 3 things: * 1. Write implementations of the Generator interface, one each fo * Message, PortType, Binding, Service, and Type. These * implementations generate the stuff for each of these WSDL types. * 2. Write an implementation of the GeneratorFactory interface that * returns instantiations of these Generator implementations as * appropriate. * 3. Implement a class with a main method (like WSDL2Java) that * instantiates an Emitter and passes it the GeneratorFactory * implementation. */ public interface GeneratorFactory { /** * Allow the Generator extension to make a pass through the * symbol table doing any pre-generation logic, like creating * the Java names for each object and constructing signature * strings. * * @param def * @param symbolTable */ public void generatorPass(Definition def, SymbolTable symbolTable); /** * Get a Generator implementation that will generate bindings for the given Message. * * @param message * @param symbolTable * @return */ public Generator getGenerator(Message message, SymbolTable symbolTable); /** * Get a Generator implementation that will generate bindings for the given PortType. * * @param portType * @param symbolTable * @return */ public Generator getGenerator(PortType portType, SymbolTable symbolTable); /** * Get a Generator implementation that will generate bindings for the given Binding. * * @param binding * @param symbolTable * @return */ public Generator getGenerator(Binding binding, SymbolTable symbolTable); /** * Get a Generator implementation that will generate bindings for the given Service. * * @param service * @param symbolTable * @return */ public Generator getGenerator(Service service, SymbolTable symbolTable); /** * Get a Generator implementation that will generate bindings for the given Type. * * @param type * @param symbolTable * @return */ public Generator getGenerator(TypeEntry type, SymbolTable symbolTable); /** * Get a Generator implementation that will generate anything that doesn't * fit into the scope of any of the other Generators. * * @param definition * @param symbolTable * @return */ public Generator getGenerator(Definition definition, SymbolTable symbolTable); /** * Get TypeMapping to use for translating * QNames to base types * * @param btm */ public void setBaseTypeMapping(BaseTypeMapping btm); /** * Method getBaseTypeMapping * * @return */ public BaseTypeMapping getBaseTypeMapping(); }
7,759
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/wsdl/gen/Generator.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.gen; import java.io.IOException; /** * This is the interface for all writers. All writers, very simply, must * support a write method. * <p> * Writer and WriterFactory are part of the Writer framework. Folks who want * to use the emitter to generate stuff from WSDL should do 3 things: * 1. Write implementations of the Writer interface, one each for PortType, * Binding, Service, and Type. These implementations generate the stuff * for each of these WSDL types. * 2. Write an implementation of the WriterFactory interface that returns * instantiations of these Writer implementations as appropriate. * 3. Implement a class with a main method (like Wsdl2java) that instantiates * an emitter and passes it the WriterFactory implementation */ public interface Generator { /** * Generate something. * * @throws IOException */ public void generate() throws IOException; }
7,760
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/i18n/MessagesConstants.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.i18n; import java.util.Locale; import java.util.ResourceBundle; /** * @author Richard A. Sitze (rsitze@us.ibm.com) */ public class MessagesConstants { public static final String projectName = "org.apache.axis".intern(); public static final String resourceName = "resource".intern(); public static final Locale locale = null; public static final String rootPackageName = "org.apache.axis.i18n".intern(); public static final ResourceBundle rootBundle = ProjectResourceBundle.getBundle(projectName, rootPackageName, resourceName, locale, MessagesConstants.class.getClassLoader(), null); }
7,761
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/i18n/RB.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.i18n; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.MissingResourceException; import java.util.Properties; /** * CURRENTLY NOT USED * KEEPING FOR REFERENCE 9/19/2002 * * <p>Wrapper class for resource bundles. Property files are used to store * resource strings, which are the only types of resources available. * Property files can inherit properties from other files so that * a base property file can be used and a small number of properties * can be over-ridden by another property file. For example you may * create an english version of a resource file named "resource.properties". * You then decide that the British English version of all of the properties * except one are the same, so there is no need to redefine all of the * properties in "resource_en_GB", just the one that is different.</p> * <p>The property file lookup searches for classes with various suffixes * on the basis if the desired local and the current default local * (as returned by Local.getDefault()). As property files are found the * property values are merged so that inheritance is preserved.</p> * <p>The order of searching is:</p> * <pre> * basename + "_" + langage + "_" + country + "_" + variant * basename + "_" + langage + "_" + country * basename + "_" + langage * basename + "_" + defaultLanguage + "_" + defaultCountry + "_" + defaultVariant * basename + "_" + defaultLanguage + "_" + defaultCountry * basename + "_" + defaultLanguage * basename * </pre> * <p>The basename is the name of the property file without the ".properties" * extension.</p> * <p>Properties will be cached for performance.<p> * <p>Property values stored in the property files can also contain dynamic * variables. Any dynamic variable defined in PropertiesUtil.getVariableValue() * can be used (such as {date}), as well as arguments in the form {0}, {1}, etc. * Argument values are specified in the various overloaded getString() methods.</p> * * @author Karl Moss (kmoss@macromedia.com) * @author Glen Daniels (gdaniels@apache.org) */ public class RB { // The static cache of properties. The key is the basename + the local + // the default local and the element is the Properties object containing // the resources static Hashtable propertyCache = new Hashtable(); // The default base name public static final String BASE_NAME = "resource"; // The property file extension public static final String PROPERTY_EXT = ".properties"; // The name of the current base property file (with extension) protected String basePropertyFileName; // The properties for the current resource bundle protected Properties resourceProperties; /** * Construct a new RB * @param name The name of the property file without the ".properties" extension */ public RB(String name) throws MissingResourceException { this(null, name, null); } /** * Construct a new RB * @param caller The calling object. This is used to get the package name * to further construct the basename as well as to get the proper ClassLoader * @param name The name of the property file without the ".properties" extension */ public RB(Object caller, String name) throws MissingResourceException { this(caller, name, null); } /** * Construct a new RB * @param caller The calling object. This is used to get the package name * to further construct the basename as well as to get the proper ClassLoader * @param name The name of the property file without the ".properties" extension * @param locale The locale */ public RB(Object caller, String name, Locale locale) throws MissingResourceException { ClassLoader cl = null; if (caller != null) { Class c; if (caller instanceof Class) { c = (Class) caller; } else { c = caller.getClass(); } // Get the appropriate class loader cl = c.getClassLoader(); if (name.indexOf("/") == -1) { // Create the full basename only if not given String fullName = c.getName(); int pos = fullName.lastIndexOf("."); if (pos > 0) { name = fullName.substring(0, pos + 1).replace('.', '/') + name; } } } else { // Try the shared default properties file... if (name.indexOf("/") == -1) { name = "org/apache/axis/default-resource"; } } Locale defaultLocale = Locale.getDefault(); // If the locale given is the same as the default locale, ignore it if (locale != null) { if (locale.equals(defaultLocale)) { locale = null; } } // Load the properties. If no property files exist then a // MissingResourceException will be thrown loadProperties(name, cl, locale, defaultLocale); } /** * Gets a string message from the resource bundle for the given key * @param key The resource key * @return The message */ public String getString(String key) throws MissingResourceException { return getString(key, (Object[]) null); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The message */ public String getString(String key, Object arg0) throws MissingResourceException { Object[] o = new Object[1]; o[0] = arg0; return getString(key, o); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The message */ public String getString(String key, Object arg0, Object arg1) throws MissingResourceException { Object[] o = new Object[2]; o[0] = arg0; o[1] = arg1; return getString(key, o); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {1} * @return The message */ public String getString(String key, Object arg0, Object arg1, Object arg2) throws MissingResourceException { Object[] o = new Object[3]; o[0] = arg0; o[1] = arg1; o[2] = arg2; return getString(key, o); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param array An array of objects to place in corresponding variables * @return The message */ public String getString(String key, Object[] array) throws MissingResourceException { String msg = null; if (resourceProperties != null) { msg = resourceProperties.getProperty(key); } if (msg == null) { throw new MissingResourceException("Cannot find resource key \"" + key + "\" in base name " + basePropertyFileName, basePropertyFileName, key); } msg = MessageFormat.format(msg, array); return msg; } protected void loadProperties(String basename, ClassLoader loader, Locale locale, Locale defaultLocale) throws MissingResourceException { // Check the cache first String loaderName = ""; if (loader != null) { loaderName = ":" + loader.hashCode(); } String cacheKey = basename + ":" + locale + ":" + defaultLocale + loaderName; Properties p = (Properties) propertyCache.get(cacheKey); basePropertyFileName = basename + PROPERTY_EXT; if (p == null) { // The properties were not found in the cache. Search the given locale // first if (locale != null) { p = loadProperties(basename, loader, locale, p); } // Search the default locale if (defaultLocale != null) { p = loadProperties(basename, loader, defaultLocale, p); } // Search for the basename p = merge(p, loadProperties(basePropertyFileName, loader)); if (p == null) { throw new MissingResourceException("Cannot find resource for base name " + basePropertyFileName, basePropertyFileName, ""); } // Cache the properties propertyCache.put(cacheKey, p); } resourceProperties = p; } protected Properties loadProperties(String basename, ClassLoader loader, Locale locale, Properties props) { String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (variant != null) { if (variant.trim().length() == 0) { variant = null; } } if (language != null) { if (country != null) { if (variant != null) { props = merge(props, loadProperties(basename + "_" + language +"_" + country + "_" + variant + PROPERTY_EXT, loader)); } props = merge(props, loadProperties(basename + "_" + language +"_" + country + PROPERTY_EXT, loader)); } props = merge(props, loadProperties(basename + "_" + language + PROPERTY_EXT, loader)); } return props; } protected Properties loadProperties(String resname, ClassLoader loader) { Properties props = null; // Attempt to open and load the properties InputStream in = null; try { if (loader != null) { in = loader.getResourceAsStream(resname); } // Either we're using the system class loader or we didn't find the // resource using the given class loader if (in == null) { in = ClassLoader.getSystemResourceAsStream(resname); } if (in != null) { props = new Properties(); try { props.load(in); } catch (IOException ex) { // On error, clear the props props = null; } } } finally { if (in != null) { try { in.close(); } catch (Exception ex) { // Ignore error on close } } } return props; } /** * Merge two Properties objects */ protected Properties merge(Properties p1, Properties p2) { if ((p1 == null) && (p2 == null)) { return null; } else if (p1 == null) { return p2; } else if (p2 == null) { return p1; } // Now merge. p1 takes precedence Enumeration enumeration = p2.keys(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); if (p1.getProperty(key) == null) { p1.put(key, p2.getProperty(key)); } } return p1; } /** * Get the underlying properties */ public Properties getProperties() { return resourceProperties; } // STATIC ACCESSORS /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @return The formatted message */ public static String getString(Object caller, String key) throws MissingResourceException { return getMessage(caller, BASE_NAME, null, key, null); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The formatted message */ public static String getString(Object caller, String key, Object arg0) throws MissingResourceException { Object[] o = new Object[1]; o[0] = arg0; return getMessage(caller, BASE_NAME, null, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The formatted message */ public static String getString(Object caller, String key, Object arg0, Object arg1) throws MissingResourceException { Object[] o = new Object[2]; o[0] = arg0; o[1] = arg1; return getMessage(caller, BASE_NAME, null, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @return The formatted message */ public static String getString(Object caller, String key, Object arg0, Object arg1, Object arg2) throws MissingResourceException { Object[] o = new Object[3]; o[0] = arg0; o[1] = arg1; o[2] = arg2; return getMessage(caller, BASE_NAME, null, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The formatted message */ public static String getString(Object caller, String key, Object arg0, Object arg1, Object arg2, Object arg3) throws MissingResourceException { Object[] o = new Object[4]; o[0] = arg0; o[1] = arg1; o[2] = arg2; o[3] = arg3; return getMessage(caller, BASE_NAME, null, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @param arg4 The argument to place in variable {4} * @return The formatted message */ public static String getString(Object caller, String key, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4) throws MissingResourceException { Object[] o = new Object[5]; o[0] = arg0; o[1] = arg1; o[2] = arg2; o[3] = arg3; o[4] = arg4; return getMessage(caller, BASE_NAME, null, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param key The resource key * @param args An array of objects to place in corresponding variables * @return The formatted message */ public static String getString(Object caller, String key, Object[] args) throws MissingResourceException { return getMessage(caller, BASE_NAME, null, key, args); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @return The formatted message */ public static String getString(Object caller, Locale locale, String key) throws MissingResourceException { return getMessage(caller, BASE_NAME, locale, key, null); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object arg0) throws MissingResourceException { Object[] o = new Object[1]; o[0] = arg0; return getMessage(caller, BASE_NAME, locale, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object arg0, Object arg1) throws MissingResourceException { Object[] o = new Object[2]; o[0] = arg0; o[1] = arg1; return getMessage(caller, BASE_NAME, locale, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object arg0, Object arg1, Object arg2) throws MissingResourceException { Object[] o = new Object[3]; o[0] = arg0; o[1] = arg1; o[2] = arg2; return getMessage(caller, BASE_NAME, locale, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object arg0, Object arg1, Object arg2, Object arg3) throws MissingResourceException { Object[] o = new Object[4]; o[0] = arg0; o[1] = arg1; o[2] = arg2; o[3] = arg3; return getMessage(caller, BASE_NAME, locale, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4) throws MissingResourceException { Object[] o = new Object[5]; o[0] = arg0; o[1] = arg1; o[2] = arg2; o[3] = arg3; o[4] = arg4; return getMessage(caller, BASE_NAME, locale, key, o); } /** * Get a message from resource.properties from the package of the given object. * @param caller The calling object, used to get the package name and class loader * @param locale The locale * @param key The resource key * @param args An array of objects to place in corresponding variables * @return The formatted message */ public static String getString(Object caller, Locale locale, String key, Object[] args) throws MissingResourceException { return getMessage(caller, BASE_NAME, locale, key, args); } // Workhorse that does the resource loading and key lookup public static String getMessage(Object caller, String basename, Locale locale, String key, Object[] args) throws MissingResourceException { String msg = null; MissingResourceException firstEx = null; String fullName = null; Class curClass = null; boolean didNull = false; if (caller != null) { if(caller instanceof Class) curClass = (Class) caller; else curClass = caller.getClass(); } while (msg == null) { // Get the full name of the resource if (curClass != null) { // Create the full basename String pkgName = curClass.getName(); int pos = pkgName.lastIndexOf("."); if (pos > 0) { fullName = pkgName.substring(0, pos + 1).replace('.', '/') + basename; } else { fullName = basename; } } else { fullName = basename; } try { RB rb = new RB(caller, fullName, locale); msg = rb.getString(key, args); } catch (MissingResourceException ex) { if (curClass == null) { throw ex; } // Save the first exception if (firstEx == null) { firstEx = ex; } // Get the superclass curClass = curClass.getSuperclass(); if (curClass == null) { if (didNull) throw firstEx; didNull = true; caller = null; } else { String cname = curClass.getName(); if (cname.startsWith("java.") || cname.startsWith("javax.")) { if (didNull) throw firstEx; didNull = true; caller = null; curClass = null; } } } } return msg; } /** * Clears the internal cache */ public static void clearCache() { propertyCache.clear(); } }
7,762
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/i18n/Messages.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.i18n; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @see org.apache.axis.i18n.Messages * * FUNCTIONAL TEMPLATE for Messages classes. * * Copy this template to your package. * * For subpackages of org.apache.axis.*, the internal constants * are set appropriately. To adapt this scheme to an extension project * (package prefix differs from org.apache.axis.*), edit the projectName * attribute. The others shouldn't need to be changed unless this is * being adapted to a non-AXIS related project.. * * @author Richard A. Sitze (rsitze@us.ibm.com) * @author Karl Moss (kmoss@macromedia.com) * @author Glen Daniels (gdaniels@apache.org) */ public class Messages { private static final Class thisClass = Messages.class; private static final String projectName = MessagesConstants.projectName; private static final String resourceName = MessagesConstants.resourceName; private static final Locale locale = MessagesConstants.locale; private static final String packageName = getPackage(thisClass.getName()); private static final ClassLoader classLoader = thisClass.getClassLoader(); private static final ResourceBundle parent = (MessagesConstants.rootPackageName == packageName) ? null : MessagesConstants.rootBundle; /***** NO NEED TO CHANGE ANYTHING BELOW *****/ private static final MessageBundle messageBundle = new MessageBundle(projectName, packageName, resourceName, locale, classLoader, parent); /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @return The formatted message */ public static String getMessage(String key) throws MissingResourceException { return messageBundle.getMessage(key); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The formatted message */ public static String getMessage(String key, String arg0) throws MissingResourceException { return messageBundle.getMessage(key, arg0); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2, arg3); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @param arg4 The argument to place in variable {4} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3, String arg4) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2, arg3, arg4); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param args An array of objects to place in corresponding variables * @return The formatted message */ public static String getMessage(String key, String[] args) throws MissingResourceException { return messageBundle.getMessage(key, args); } public static ResourceBundle getResourceBundle() { return messageBundle.getResourceBundle(); } public static MessageBundle getMessageBundle() { return messageBundle; } private static final String getPackage(String name) { return name.substring(0, name.lastIndexOf('.')).intern(); } }
7,763
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/i18n/MessageBundle.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.i18n; import java.text.MessageFormat; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Accept parameters for ProjectResourceBundle, * but defer object instantiation (and therefore * resource bundle loading) until required. * * @author Richard A. Sitze (rsitze@us.ibm.com) * @author Karl Moss (kmoss@macromedia.com) * @author Glen Daniels (gdaniels@apache.org) */ public class MessageBundle { private boolean loaded = false; private ProjectResourceBundle _resourceBundle = null; private final String projectName; private final String packageName; private final String resourceName; private final Locale locale; private final ClassLoader classLoader; private final ResourceBundle parent; public final ProjectResourceBundle getResourceBundle() { if (!loaded) { _resourceBundle = ProjectResourceBundle.getBundle(projectName, packageName, resourceName, locale, classLoader, parent); loaded = true; } return _resourceBundle; } /** * Construct a new ExtendMessages */ public MessageBundle(String projectName, String packageName, String resourceName, Locale locale, ClassLoader classLoader, ResourceBundle parent) throws MissingResourceException { this.projectName = projectName; this.packageName = packageName; this.resourceName = resourceName; this.locale = locale; this.classLoader = classLoader; this.parent = parent; } /** * Gets a string message from the resource bundle for the given key * @param key The resource key * @return The message */ public String getMessage(String key) throws MissingResourceException { return getMessage(key, (String[]) null); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The message */ public String getMessage(String key, String arg0) throws MissingResourceException { return getMessage(key, new String[] { arg0 }); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The message */ public String getMessage(String key, String arg0, String arg1) throws MissingResourceException { return getMessage(key, new String[] { arg0, arg1 }); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @return The message */ public String getMessage(String key, String arg0, String arg1, String arg2) throws MissingResourceException { return getMessage(key, new String[] { arg0, arg1, arg2 }); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The message */ public String getMessage(String key, String arg0, String arg1, String arg2, String arg3) throws MissingResourceException { return getMessage(key, new String[] { arg0, arg1, arg2, arg3 }); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @param arg4 The argument to place in variable {4} * @return The message */ public String getMessage(String key, String arg0, String arg1, String arg2, String arg3, String arg4) throws MissingResourceException { return getMessage(key, new String[] { arg0, arg1, arg2, arg3, arg4 }); } /** * <p>Gets a string message from the resource bundle for the given key. The * message may contain variables that will be substituted with the given * arguments. Variables have the format:</p> * <pre> * This message has two variables: {0} and {1} * </pre> * @param key The resource key * @param array An array of objects to place in corresponding variables * @return The message */ public String getMessage(String key, String[] array) throws MissingResourceException { String msg = null; if (getResourceBundle() != null) { msg = getResourceBundle().getString(key); } if (msg == null) { throw new MissingResourceException("Cannot find resource key \"" + key + "\" in base name " + getResourceBundle().getResourceName(), getResourceBundle().getResourceName(), key); } return MessageFormat.format(msg, array); } }
7,764
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/i18n/ProjectResourceBundle.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.i18n; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * <p>Wrapper class for resource bundles. Property files are used to store * resource strings, which are the only types of resources available. * Property files can inherit properties from other files so that * a base property file can be used and a small number of properties * can be over-ridden by another property file. For example you may * create an english version of a resource file named "resource.properties". * You then decide that the British English version of all of the properties * except one are the same, so there is no need to redefine all of the * properties in "resource_en_GB", just the one that is different.</p> * <p>The basename is the name of the property file without the ".properties" * extension.</p> * <p>Properties will be cached for performance.<p> * <p>Property values stored in the property files can also contain dynamic * variables. Any dynamic variable defined in PropertiesUtil.getVariableValue() * can be used (such as {date}), as well as arguments in the form {0}, {1}, etc. * Argument values are specified in the various overloaded getString() methods.</p> * * @author Richard A. Sitze (rsitze@us.ibm.com) * @author Karl Moss (kmoss@macromedia.com) * @author Glen Daniels (gdaniels@apache.org) */ public class ProjectResourceBundle extends ResourceBundle { protected static Log log = LogFactory.getLog(ProjectResourceBundle.class.getName()); // The static cache of ResourceBundles. // The key is the 'basename + locale + default locale' // The element is a ResourceBundle object private static final Hashtable bundleCache = new Hashtable(); private static final Locale defaultLocale = Locale.getDefault(); private final ResourceBundle resourceBundle; private final String resourceName; protected Object handleGetObject(String key) throws MissingResourceException { if (log.isDebugEnabled()) { log.debug(this.toString() + "::handleGetObject(" + key + ")"); } // return resourceBundle.handleGetObject(key); Object obj; try { obj = resourceBundle.getObject(key); } catch (MissingResourceException e) { /* catch missing resource, ignore, & return null * if this method doesn't return null, then parents * are not searched */ obj = null; } return obj; } public Enumeration getKeys() { Enumeration myKeys = resourceBundle.getKeys(); if (parent == null) { return myKeys; } else { final HashSet set = new HashSet(); while (myKeys.hasMoreElements()) { set.add(myKeys.nextElement()); } Enumeration pKeys = parent.getKeys(); while (pKeys.hasMoreElements()) { set.add(pKeys.nextElement()); } return new Enumeration() { private Iterator it = set.iterator(); public boolean hasMoreElements() { return it.hasNext(); } public Object nextElement() { return it.next(); } }; } } /** * Construct a new ProjectResourceBundle * * @param projectName The name of the project to which the class belongs. * It must be a proper prefix of the caller's package. * * @param resourceName The name of the resource without the * ".properties" extension * * @throws MissingResourceException if projectName is not a prefix of * the caller's package name, or if the resource could not be * found/loaded. */ public static ProjectResourceBundle getBundle(String projectName, String packageName, String resourceName) throws MissingResourceException { return getBundle(projectName, packageName, resourceName, null, null, null); } /** * Construct a new ProjectResourceBundle * * @param projectName The name of the project to which the class belongs. * It must be a proper prefix of the caller's package. * * @param caller The calling class. * This is used to get the package name to further construct * the basename as well as to get the proper ClassLoader. * * @param resourceName The name of the resource without the * ".properties" extension * * @throws MissingResourceException if projectName is not a prefix of * the caller's package name, or if the resource could not be * found/loaded. */ public static ProjectResourceBundle getBundle(String projectName, Class caller, String resourceName, Locale locale) throws MissingResourceException { return getBundle(projectName, caller, resourceName, locale, null); } /** * Construct a new ProjectResourceBundle * * @param projectName The name of the project to which the class belongs. * It must be a proper prefix of the caller's package. * * @param resourceName The name of the resource without the * ".properties" extension * * @param locale The locale * * @throws MissingResourceException if projectName is not a prefix of * the caller's package name, or if the resource could not be * found/loaded. */ public static ProjectResourceBundle getBundle(String projectName, String packageName, String resourceName, Locale locale, ClassLoader loader) throws MissingResourceException { return getBundle(projectName, packageName, resourceName, locale, loader, null); } /** * Construct a new ProjectResourceBundle * * @param projectName The name of the project to which the class belongs. * It must be a proper prefix of the caller's package. * * @param caller The calling class. * This is used to get the package name to further construct * the basename as well as to get the proper ClassLoader. * * @param resourceName The name of the resource without the * ".properties" extension * * @param locale The locale * * @param extendsBundle If non-null, then this ExtendMessages will * default to extendsBundle. * * @throws MissingResourceException if projectName is not a prefix of * the caller's package name, or if the resource could not be * found/loaded. */ public static ProjectResourceBundle getBundle(String projectName, Class caller, String resourceName, Locale locale, ResourceBundle extendsBundle) throws MissingResourceException { return getBundle(projectName, getPackage(caller.getClass().getName()), resourceName, locale, caller.getClass().getClassLoader(), extendsBundle); } /** * Construct a new ProjectResourceBundle * * @param projectName The name of the project to which the class belongs. * It must be a proper prefix of the caller's package. * * @param resourceName The name of the resource without the * ".properties" extension * * @param locale The locale * * @param extendsBundle If non-null, then this ExtendMessages will * default to extendsBundle. * * @throws MissingResourceException if projectName is not a prefix of * the caller's package name, or if the resource could not be * found/loaded. */ public static ProjectResourceBundle getBundle(String projectName, String packageName, String resourceName, Locale locale, ClassLoader loader, ResourceBundle extendsBundle) throws MissingResourceException { if (log.isDebugEnabled()) { log.debug("getBundle(" + projectName + "," + packageName + "," + resourceName + "," + String.valueOf(locale) + ",...)"); } Context context = new Context(); context.setLocale(locale); context.setLoader(loader); context.setProjectName(projectName); context.setResourceName(resourceName); context.setParentBundle(extendsBundle); packageName = context.validate(packageName); ProjectResourceBundle bundle = null; try { bundle = getBundle(context, packageName); } catch (RuntimeException e) { log.debug("Exception: ", e); throw e; } if (bundle == null) { throw new MissingResourceException("Cannot find resource '" + packageName + '.' + resourceName + "'", resourceName, ""); } return bundle; } /** * get bundle... * - check cache * - try up hierarchy * - if at top of hierarchy, use (link to) context.getParentBundle() */ private static synchronized ProjectResourceBundle getBundle(Context context, String packageName) throws MissingResourceException { String cacheKey = context.getCacheKey(packageName); ProjectResourceBundle prb = (ProjectResourceBundle)bundleCache.get(cacheKey); if (prb == null) { String name = packageName + '.' + context.getResourceName(); ResourceBundle rb = context.loadBundle(packageName); ResourceBundle parent = context.getParentBundle(packageName); if (rb != null) { prb = new ProjectResourceBundle(name, rb); prb.setParent(parent); if (log.isDebugEnabled()) { log.debug("Created " + prb + ", linked to parent " + String.valueOf(parent)); } } else { if (parent != null) { if (parent instanceof ProjectResourceBundle) { prb = (ProjectResourceBundle)parent; } else { prb = new ProjectResourceBundle(name, parent); } if (log.isDebugEnabled()) { log.debug("Root package not found, cross link to " + parent); } } } if (prb != null) { // Cache the resource bundleCache.put(cacheKey, prb); } } return prb; } private static final String getPackage(String name) { return name.substring(0, name.lastIndexOf('.')).intern(); } /** * Construct a new ProjectResourceBundle */ private ProjectResourceBundle(String name, ResourceBundle bundle) throws MissingResourceException { this.resourceBundle = bundle; this.resourceName = name; } public String getResourceName() { return resourceName; } /** * Clears the internal cache. * <p> * Note: In Axis 1.4 this method was named <code>clearCache</code>. However, that name conflicts * with a method in the base class introduced in Java 1.6. */ public static void clearBundleCache() { bundleCache.clear(); } public String toString() { return resourceName; } private static class Context { private Locale _locale; private ClassLoader _loader; private String _projectName; private String _resourceName; private ResourceBundle _parent; void setLocale(Locale l) { /* 1. Docs indicate that if locale is not specified, * then the default local is used in it's place. * 2. A null value for locale is invalid. * * Therefore, default... */ _locale = (l == null) ? defaultLocale : l; } void setLoader(ClassLoader l) { _loader = (l != null) ? l : this.getClass().getClassLoader(); // START FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16868 if (_loader == null) { _loader = ClassLoader.getSystemClassLoader(); } // END FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16868 } void setProjectName(String name) { _projectName = name.intern(); } void setResourceName(String name) { _resourceName = name.intern(); } void setParentBundle(ResourceBundle b) { _parent = b; } Locale getLocale() { return _locale; } ClassLoader getLoader() { return _loader; } String getProjectName() { return _projectName; } String getResourceName() { return _resourceName; } ResourceBundle getParentBundle() { return _parent; } String getCacheKey(String packageName) { String loaderName = (_loader == null) ? "" : (":" + _loader.hashCode()); return packageName + "." + _resourceName + ":" + _locale + ":" + defaultLocale + loaderName; } ResourceBundle loadBundle(String packageName) { try { return ResourceBundle.getBundle(packageName + '.' + _resourceName, _locale, _loader); } catch (MissingResourceException e) { // Deliberately surpressing print stack.. just the string for info. log.debug("loadBundle: Ignoring MissingResourceException: " + e.getMessage()); } return null; } ResourceBundle getParentBundle(String packageName) { ResourceBundle p; if (packageName != _projectName) { p = getBundle(this, getPackage(packageName)); } else { p = _parent; _parent = null; } return p; } String validate(String packageName) throws MissingResourceException { if (_projectName == null || _projectName.length() == 0) { log.debug("Project name not specified"); throw new MissingResourceException("Project name not specified", "", ""); } if (packageName == null || packageName.length() == 0) { log.debug("Package name not specified"); throw new MissingResourceException("Package not specified", packageName, ""); } packageName = packageName.intern(); /* Ensure that project is a proper prefix of class. * Terminate project name with '.' to ensure proper match. */ if (packageName != _projectName && !packageName.startsWith(_projectName + '.')) { log.debug("Project not a prefix of Package"); throw new MissingResourceException("Project '" + _projectName + "' must be a prefix of Package '" + packageName + "'", packageName + '.' + _resourceName, ""); } return packageName; } } }
7,765
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MultiPartRelatedInputStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.Part; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.utils.IOUtils; import org.apache.commons.logging.Log; import javax.activation.DataHandler; import javax.mail.internet.MimeUtility; import java.io.IOException; import java.io.BufferedInputStream; /** * This simulates the multipart stream. * * @author Rick Rineholt */ public class MultiPartRelatedInputStream extends MultiPartInputStream{ /** Field log */ protected static Log log = LogFactory.getLog(MultiPartRelatedInputStream.class.getName()); /** Field MIME_MULTIPART_RELATED */ public static final String MIME_MULTIPART_RELATED = "multipart/related"; /** Field parts */ protected java.util.HashMap parts = new java.util.HashMap(); /** Field orderedParts */ protected java.util.LinkedList orderedParts = new java.util.LinkedList(); /** Field rootPartLength */ protected int rootPartLength = 0; /** Field closed */ protected boolean closed = false; // If true the stream has been closed. /** Field eos */ protected boolean eos = false; // This is set once the SOAP packet has reached the end of stream. // protected java.io.InputStream is = null; //The orginal multipart/related stream. // This stream controls and manages the boundary. /** Field boundaryDelimitedStream */ protected org.apache.axis.attachments.BoundaryDelimitedStream boundaryDelimitedStream = null; /** Field soapStream */ protected java.io.InputStream soapStream = null; // Set the soap stream once found. /** Field soapStreamBDS */ protected java.io.InputStream soapStreamBDS = null; // Set to the boundary delimited stream assoc. with soap stream once found. /** Field boundary */ protected byte[] boundary = null; /** Field cachedSOAPEnvelope */ protected java.io.ByteArrayInputStream cachedSOAPEnvelope = null; // Caches the soap stream if it is // Still open and a reference to read data in a later attachment occurs. /** Field contentLocation */ protected String contentLocation = null; /** Field contentId */ protected String contentId = null; /** Field MAX_CACHED */ private static final int MAX_CACHED = 16 * 1024; /** * Create a new Multipart stream. * @param contentType the string that holds the contentType * @param stream the true input stream from where the source * * @throws org.apache.axis.AxisFault if the stream could not be created */ public MultiPartRelatedInputStream( String contentType, java.io.InputStream stream) throws org.apache.axis.AxisFault { super(null); // don't cache this stream. if(!(stream instanceof BufferedInputStream)) { stream = new BufferedInputStream(stream); } try { // First find the start and boundary parameters. There are real weird rules regard what // can be in real headers what needs to be escaped etc let mail parse it. javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(contentType); String rootPartContentId = ct.getParameter("start"); // Get the root part content. if (rootPartContentId != null) { rootPartContentId = rootPartContentId.trim(); if (rootPartContentId.startsWith("<")) { rootPartContentId = rootPartContentId.substring(1); } if (rootPartContentId.endsWith(">")) { rootPartContentId = rootPartContentId.substring(0, rootPartContentId.length() - 1); } } if(ct.getParameter("boundary") != null) { String boundaryStr = "--" + ct.getParameter( "boundary"); // The boundary with -- add as always the case. // if start is null then the first attachment is the rootpart // First read the start boundary -- this is done with brute force since the servlet may swallow the crlf between headers. // after this we use the more efficient boundarydelimeted stream. There should never be any data here anyway. byte[][] boundaryMarker = new byte[2][boundaryStr.length() + 2]; IOUtils.readFully(stream, boundaryMarker[0]); boundary = (boundaryStr + "\r\n").getBytes("US-ASCII"); int current = 0; // This just goes brute force one byte at a time to find the first boundary. // in most cases this just a crlf. for (boolean found = false; !found; ++current) { if (!(found = java.util.Arrays.equals(boundaryMarker[current & 0x1], boundary))) { System.arraycopy(boundaryMarker[current & 0x1], 1, boundaryMarker[(current + 1) & 0x1], 0, boundaryMarker[0].length - 1); if (stream.read( boundaryMarker[(current + 1) & 0x1], boundaryMarker[0].length - 1, 1) < 1) { throw new org.apache.axis.AxisFault( Messages.getMessage( "mimeErrorNoBoundary", new String(boundary))); } } } // after the first boundary each boundary will have a cr lf at the beginning since after the data in any part there // is a cr lf added to put the boundary at the begining of a line. boundaryStr = "\r\n" + boundaryStr; boundary = boundaryStr.getBytes("US-ASCII"); } else { // Since boundary is not specified, we try to find one. for (boolean found = false; !found;) { boundary= readLine(stream); if( boundary == null) throw new org.apache.axis.AxisFault( Messages.getMessage( "mimeErrorNoBoundary", "--")); found = boundary.length >4 && boundary[2] == '-' && boundary[3]== '-'; } } // create the boundary delmited stream. boundaryDelimitedStream = new org.apache.axis.attachments.BoundaryDelimitedStream(stream, boundary, 1024); // Now read through all potential streams until we have found the root part. String contentTransferEncoding = null; do { contentId = null; contentLocation = null; contentTransferEncoding = null; // Read this attachments headers from the stream. javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders( boundaryDelimitedStream); // Use java mail utility to read through the headers. contentId = headers.getHeader(HTTPConstants.HEADER_CONTENT_ID, null); // Clean up the headers and remove any < > if (contentId != null) { contentId = contentId.trim(); if (contentId.startsWith("<")) { contentId = contentId.substring(1); } if (contentId.endsWith(">")) { contentId = contentId.substring(0, contentId.length() - 1); } contentId = contentId.trim(); // if (!contentId.startsWith("cid:")) { // contentId = // "cid:" // + contentId; // make sure its identified as cid // } } contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null); if (contentLocation != null) { contentLocation = contentLocation.trim(); if (contentLocation.startsWith("<")) { contentLocation = contentLocation.substring(1); } if (contentLocation.endsWith(">")) { contentLocation = contentLocation.substring( 0, contentLocation.length() - 1); } contentLocation = contentLocation.trim(); } contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null); if (contentType != null) { contentType = contentType.trim(); } contentTransferEncoding = headers.getHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null); if (contentTransferEncoding != null) { contentTransferEncoding = contentTransferEncoding.trim(); } java.io.InputStream decodedStream = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding); } if ((rootPartContentId != null) && !rootPartContentId.equals( contentId)) { // This is a part that has come in prior to the root part. Need to buffer it up. javax.activation.DataHandler dh = new javax.activation.DataHandler( new org.apache.axis.attachments.ManagedMemoryDataSource( decodedStream, MAX_CACHED, contentType, true)); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } if (contentLocation != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation); } for (java.util.Enumeration en = headers.getNonMatchingHeaders(new String[]{ HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION, HTTPConstants.HEADER_CONTENT_TYPE}); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); String name = header.getName(); String value = header.getValue(); if ((name != null) && (value != null)) { name = name.trim(); if (name.length() != 0) { ap.addMimeHeader(name, value); } } } addPart(contentId, contentLocation, ap); boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); // Gets the next stream. } } while ((null != boundaryDelimitedStream) && (rootPartContentId != null) && !rootPartContentId.equals(contentId)); if (boundaryDelimitedStream == null) { throw new org.apache.axis.AxisFault( Messages.getMessage("noRoot", rootPartContentId)); } soapStreamBDS = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { soapStream = MimeUtility.decode(boundaryDelimitedStream, contentTransferEncoding); } else { soapStream = boundaryDelimitedStream; // This should be the SOAP part } // Read from the input stream all attachments prior to the root part. } catch (javax.mail.internet.ParseException e) { throw new org.apache.axis.AxisFault( Messages.getMessage("mimeErrorParsing", e.getMessage())); } catch (java.io.IOException e) { throw new org.apache.axis.AxisFault( Messages.getMessage("readError", e.getMessage())); } catch (javax.mail.MessagingException e) { throw new org.apache.axis.AxisFault( Messages.getMessage("readError", e.getMessage())); } } //when searching for a MIME boundary it MUST be terminated with CR LF. LF alone is NOT sufficient. private final byte[] readLine(java.io.InputStream is) throws IOException { java.io.ByteArrayOutputStream input = new java.io.ByteArrayOutputStream(1024); int c = 0; input.write('\r'); input.write('\n'); int next = -1; for (;c != -1;) { c = -1 != next ? next : is.read(); next = -1; switch (c) { case -1: break; case '\r': next = is.read(); if(next == '\n') //found a line. return input.toByteArray(); if(next == -1) return null; //fall through default: input.write((byte)c); break; } } //even if there is stuff in buffer if EOF then this can't be a boundary. return null; } public Part getAttachmentByReference(final String[] id) throws org.apache.axis.AxisFault { // First see if we have read it in yet. Part ret = null; for (int i = id.length - 1; (ret == null) && (i > -1); --i) { ret = (AttachmentPart) parts.get(id[i]); } if (null == ret) { ret = readTillFound(id); } log.debug(Messages.getMessage("return02", "getAttachmentByReference(\"" + id + "\"", ((ret == null) ? "null" : ret.toString()))); return ret; } /** * Add an <code>AttachmentPart</code> together with its content and location * IDs. * * @param contentId the content ID * @param locationId the location ID * @param ap the <code>AttachmentPart</code> */ protected void addPart(String contentId, String locationId, AttachmentPart ap) { if ((contentId != null) && (contentId.trim().length() != 0)) { parts.put(contentId, ap); } if ((locationId != null) && (locationId.trim().length() != 0)) { parts.put(locationId, ap); } orderedParts.add(ap); } /** Field READ_ALL */ protected static final String[] READ_ALL = { " * \0 ".intern()}; // Shouldn't never match /** * Read all data. * * @throws org.apache.axis.AxisFault if there was a problem reading all the * data */ protected void readAll() throws org.apache.axis.AxisFault { readTillFound(READ_ALL); } public java.util.Collection getAttachments() throws org.apache.axis.AxisFault { readAll(); return orderedParts; } /** * This will read streams in till the one that is needed is found. * * @param id id is the stream being sought. * * @return the part for the id * * @throws org.apache.axis.AxisFault */ protected Part readTillFound(final String[] id) throws org.apache.axis.AxisFault { if (boundaryDelimitedStream == null) { return null; // The whole stream has been consumed already } Part ret = null; try { if (soapStreamBDS == boundaryDelimitedStream) { // Still on the SOAP stream. if (!eos) { // The SOAP packet has not been fully read yet. Need to store it away. java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8); byte[] buf = new byte[1024 * 16]; int byteread = 0; do { byteread = soapStream.read(buf); if (byteread > 0) { soapdata.write(buf, 0, byteread); } } while (byteread > -1); soapdata.close(); soapStream = new java.io.ByteArrayInputStream( soapdata.toByteArray()); } boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); } // Now start searching for the data. if (null != boundaryDelimitedStream) { do { String contentType = null; String contentId = null; String contentTransferEncoding = null; String contentLocation = null; // Read this attachments headers from the stream. javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders( boundaryDelimitedStream); contentId = headers.getHeader("Content-Id", null); if (contentId != null) { contentId = contentId.trim(); if (contentId.startsWith("<")) { contentId = contentId.substring(1); } if (contentId.endsWith(">")) { contentId = contentId.substring(0, contentId.length() - 1); } // if (!contentId.startsWith("cid:")) { // contentId = "cid:" + contentId; // } contentId = contentId.trim(); } contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null); if (contentType != null) { contentType = contentType.trim(); } contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null); if (contentLocation != null) { contentLocation = contentLocation.trim(); } contentTransferEncoding = headers.getHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null); if (contentTransferEncoding != null) { contentTransferEncoding = contentTransferEncoding.trim(); } java.io.InputStream decodedStream = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding); } ManagedMemoryDataSource source = new ManagedMemoryDataSource( decodedStream, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); DataHandler dh = new DataHandler(source); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } if (contentLocation != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation); } for (java.util.Enumeration en = headers.getNonMatchingHeaders(new String[]{ HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION, HTTPConstants.HEADER_CONTENT_TYPE}); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); String name = header.getName(); String value = header.getValue(); if ((name != null) && (value != null)) { name = name.trim(); if (name.length() != 0) { ap.addMimeHeader(name, value); } } } addPart(contentId, contentLocation, ap); for (int i = id.length - 1; (ret == null) && (i > -1); --i) { if ((contentId != null) && id[i].equals( contentId)) { // This is the part being sought ret = ap; } else if ((contentLocation != null) && id[i].equals(contentLocation)) { ret = ap; } } boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); } while ((null == ret) && (null != boundaryDelimitedStream)); } } catch (Exception e) { throw org.apache.axis.AxisFault.makeFault(e); } return ret; } public String getContentLocation() { return contentLocation; } public String getContentId() { return contentId; } public int read(byte[] b, int off, int len) throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage("streamClosed")); } if (eos) { return -1; } int read = soapStream.read(b, off, len); if (read < 0) { eos = true; } return read; } public int read(byte[] b) throws java.io.IOException { return read(b, 0, b.length); } public int read() throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage("streamClosed")); } if (eos) { return -1; } int ret = soapStream.read(); if (ret < 0) { eos = true; } return ret; } public void close() throws java.io.IOException { closed = true; soapStream.close(); } public int available() throws java.io.IOException { return (closed || eos) ? 0 : soapStream.available(); } }
7,766
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/ImageDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.activation.DataSource; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; public class ImageDataSource implements DataSource { protected static Log log = LogFactory.getLog(ImageDataSource.class.getName()); public static final String CONTENT_TYPE = "image/png"; private final String name; private final String contentType; private byte[] data; private ByteArrayOutputStream os; public ImageDataSource(String name, Image data) { this(name, CONTENT_TYPE, data); } // ctor public ImageDataSource(String name, String contentType, Image data) { this.name = name; this.contentType = contentType == null ? CONTENT_TYPE : contentType; os = new ByteArrayOutputStream(); try { if (data != null) { ImageWriter writer = null; Iterator iter = ImageIO.getImageWritersByMIMEType(contentType); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } writer.setOutput(ImageIO.createImageOutputStream(os)); BufferedImage rendImage = null; if (data instanceof BufferedImage) { rendImage = (BufferedImage) data; } else { MediaTracker tracker = new MediaTracker(new Component() {}); tracker.addImage(data, 0); tracker.waitForAll(); rendImage = new BufferedImage(data.getWidth(null), data.getHeight(null), 1); Graphics g = rendImage.createGraphics(); g.drawImage(data, 0, 0, null); } writer.write(new IIOImage(rendImage, null, null)); writer.dispose(); } } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } } // ctor public String getName() { return name; } // getName public String getContentType() { return contentType; } // getContentType public InputStream getInputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return new ByteArrayInputStream(data == null ? new byte[0] : data); } // getInputStream public OutputStream getOutputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return os; } // getOutputStream } // class ImageDataSource
7,767
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/PlainTextDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import javax.activation.DataSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class PlainTextDataSource implements DataSource { public static final String CONTENT_TYPE = "text/plain"; private final String name; private byte[] data; private ByteArrayOutputStream os; public PlainTextDataSource(String name, String data) { this.name = name; this.data = data == null ? null : data.getBytes(); os = new ByteArrayOutputStream(); } // ctor public String getName() { return name; } // getName public String getContentType() { return CONTENT_TYPE; } // getContentType public InputStream getInputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); } return new ByteArrayInputStream(data == null ? new byte[0] : data); } // getInputStream public OutputStream getOutputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); } return new ByteArrayOutputStream(); } // getOutputStream } // class PlainTextDataSource
7,768
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/AttachmentUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.AxisFault; import org.apache.axis.Part; import org.apache.axis.utils.Messages; import javax.activation.DataHandler; /** * This class allow access to the Jaf data handler in AttachmentPart. * * @author Rick Rineholt */ public class AttachmentUtils { private AttachmentUtils() { } // no one should create. /** * Obtain the DataHandler from the part. * @param part the part containing the Java Activiation Framework data source. * @return The Java activation data handler. * * @throws AxisFault */ public static DataHandler getActivationDataHandler(Part part) throws AxisFault { if (null == part) { throw new AxisFault(Messages.getMessage("gotNullPart")); } if (!(part instanceof AttachmentPart)) { throw new AxisFault( Messages.getMessage( "unsupportedAttach", part.getClass().getName(), AttachmentPart.class.getName())); } return ((AttachmentPart) part).getActivationDataHandler(); } /** * Determine if an object is to be treated as an attchment. * * @param value the value that is to be determined if * its an attachment. * * @return True if value should be treated as an attchment. */ public static boolean isAttachment(Object value) { if (null == value) { return false; } return value instanceof javax.activation.DataHandler; } }
7,769
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/OctetStreamDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import javax.activation.DataSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class OctetStreamDataSource implements DataSource { public static final String CONTENT_TYPE = "application/octet-stream"; private final String name; private byte[] data; private ByteArrayOutputStream os; public OctetStreamDataSource(String name, OctetStream data) { this.name = name; this.data = data == null ? null : data.getBytes(); os = new ByteArrayOutputStream(); } // ctor public String getName() { return name; } // getName public String getContentType() { return CONTENT_TYPE; } // getContentType public InputStream getInputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); } return new ByteArrayInputStream(data == null ? new byte[0] : data); } // getInputStream public OutputStream getOutputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); } return new ByteArrayOutputStream(); } // getOutputStream } // class OctetStreamDataSource
7,770
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/ManagedMemoryDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.InternalException; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.File; import java.io.BufferedInputStream; /** * This class allows small attachments to be cached in memory, while large ones are * cached out. It implements a Java Activiation Data source interface. * * @author Rick Rineholt */ public class ManagedMemoryDataSource implements javax.activation.DataSource { /** Field log */ protected static Log log = LogFactory.getLog(ManagedMemoryDataSource.class.getName()); /** * The content type. This defaults to * <code>application/octet-stream</code>. */ protected String contentType = "application/octet-stream"; /** The incoming source stream. */ java.io.InputStream ss = null; /** Field MIN_MEMORY_DISK_CACHED */ public static final int MIN_MEMORY_DISK_CACHED = -1; /** Field MAX_MEMORY_DISK_CACHED */ public static final int MAX_MEMORY_DISK_CACHED = 16 * 1024; /** Field maxCached */ protected int maxCached = MAX_MEMORY_DISK_CACHED; // max in memory cached. Default. // If set the file the disk is cached to. /** Field diskCacheFile */ protected java.io.File diskCacheFile = null; // A list of open input Streams. /** Field readers */ protected java.util.WeakHashMap readers = new java.util.WeakHashMap(); /** * Flag to show if the resources behind this have been deleted. */ protected boolean deleted = false; // Memory is allocated in these size chunks. /** Field READ_CHUNK_SZ */ public static final int READ_CHUNK_SZ = 32 * 1024; /** Field debugEnabled */ protected boolean debugEnabled = false; // Log debugging if true. // Should not be called; /** * Constructor ManagedMemoryDataSource. */ protected ManagedMemoryDataSource() { } /** * Create a new boundary stream. * * @param ss is the source input stream that is used to create this data source. * @param maxCached This is the max memory that is to be used to cache the data. * @param contentType the mime type for this data stream. * by buffering you can some effiency in searching. * * @throws java.io.IOException */ public ManagedMemoryDataSource( java.io.InputStream ss, int maxCached, String contentType) throws java.io.IOException { this(ss, maxCached, contentType, false); } /** * Create a new boundary stream. * * @param ss is the source input stream that is used to create this data source. * @param maxCached This is the max memory that is to be used to cache the data. * @param contentType the mime type for this data stream. * by buffering you can some effiency in searching. * @param readall if true will read in the whole source. * * @throws java.io.IOException */ public ManagedMemoryDataSource( java.io.InputStream ss, int maxCached, String contentType, boolean readall) throws java.io.IOException { if(ss instanceof BufferedInputStream) { this.ss = ss; } else { this.ss = new BufferedInputStream(ss); } this.maxCached = maxCached; if ((null != contentType) && (contentType.length() != 0)) { this.contentType = contentType; } if (maxCached < MIN_MEMORY_DISK_CACHED) { throw new IllegalArgumentException( Messages.getMessage("badMaxCached", "" + maxCached)); } if (log.isDebugEnabled()) { debugEnabled = true; // Logging should be initialized by time; } // for now read all in to disk. if (readall) { byte[] readbuffer = new byte[READ_CHUNK_SZ]; int read = 0; do { read = ss.read(readbuffer); if (read > 0) { write(readbuffer, read); } } while (read > -1); close(); } } /* javax.activation.Interface DataSource implementation */ /** * This method returns the MIME type of the data in the form of a string. * @return The mime type. */ public java.lang.String getContentType() { return contentType; } /** * This method returns an InputStream representing the the data and throws the appropriate exception if it can not do so. * @return the java.io.InputStream for the data source. * * @throws java.io.IOException */ public synchronized java.io.InputStream getInputStream() throws java.io.IOException { /* * if (memorybuflist == null) { * return new java.io.FileInputStream(diskCacheFile); * } * else */ return new Instream(); // Return the memory held stream. } /** * This will flush any memory source to disk and * provide the name of the file if desired. * * @return the name of the file of the stream */ public java.lang.String getName() { String ret = null; try { flushToDisk(); if (diskCacheFile != null) { ret = diskCacheFile.getAbsolutePath(); } } catch (Exception e) { diskCacheFile = null; } return ret; } /** * This method returns an OutputStream where the data can be written and * throws the appropriate exception if it can not do so. * NOT SUPPORTED, not need for axis, data sources are create by constructors. * * * @return always <code>null</code> * * @throws java.io.IOException */ public java.io.OutputStream getOutputStream() throws java.io.IOException { return null; } /** The linked list to hold the in memory buffers. */ protected java.util.LinkedList memorybuflist = new java.util.LinkedList(); /** Hold the last memory buffer. */ protected byte[] currentMemoryBuf = null; /** The number of bytes written to the above buffer. */ protected int currentMemoryBufSz = 0; /** The total size in bytes in this data source. */ protected long totalsz = 0; /** This is the cached disk stream. */ protected java.io.BufferedOutputStream cachediskstream = null; /** If true the source input stream is now closed. */ protected boolean closed = false; /** * Write bytes to the stream. * * @param data all bytes of this array are written to the stream * @throws java.io.IOException if there was a problem writing the data */ protected void write(byte[] data) throws java.io.IOException { write(data, data.length); } /** * This method is a low level write. * Note it is designed to in the future to allow streaming to both memory * AND to disk simultaneously. * * @param data * @param length * * @throws java.io.IOException */ protected synchronized void write(byte[] data, int length) throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage("streamClosed")); } int writesz = length; int byteswritten = 0; if ((null != memorybuflist) && (totalsz + writesz > maxCached)) { // Cache to disk. if (null == cachediskstream) { // Need to create a disk cache flushToDisk(); } } if (memorybuflist != null) { // Can write to memory. do { if (null == currentMemoryBuf) { currentMemoryBuf = new byte[READ_CHUNK_SZ]; currentMemoryBufSz = 0; memorybuflist.add(currentMemoryBuf); } // bytes to write is the min. between the remaining bytes and what is left in this buffer. int bytes2write = Math.min((writesz - byteswritten), (currentMemoryBuf.length - currentMemoryBufSz)); // copy the data. System.arraycopy(data, byteswritten, currentMemoryBuf, currentMemoryBufSz, bytes2write); byteswritten += bytes2write; currentMemoryBufSz += bytes2write; if (byteswritten < writesz) { // only get more if we really need it. currentMemoryBuf = new byte[READ_CHUNK_SZ]; currentMemoryBufSz = 0; memorybuflist.add(currentMemoryBuf); // add it to the chain. } } while (byteswritten < writesz); } if (null != cachediskstream) { // Write to the out going stream. cachediskstream.write(data, 0, length); } totalsz += writesz; return; } /** * This method is a low level write. * Close the stream. * * @throws java.io.IOException */ protected synchronized void close() throws java.io.IOException { if (!closed) { closed = true; // Markit as closed. if (null != cachediskstream) { // close the disk cache. cachediskstream.close(); cachediskstream = null; } if (null != memorybuflist) { // There is a memory buffer. if (currentMemoryBufSz > 0) { byte[] tmp = new byte[currentMemoryBufSz]; // Get the last buffer and make it the sizeof the actual data. System.arraycopy(currentMemoryBuf, 0, tmp, 0, currentMemoryBufSz); memorybuflist.set( memorybuflist.size() - 1, tmp); // Now replace the last buffer with this size. } currentMemoryBuf = null; // No need for this anymore. } } } protected void finalize() throws Throwable { if (null != cachediskstream) { // close the disk cache. cachediskstream.close(); cachediskstream = null; } } /** * Routine to flush data to disk if is in memory. * * @throws java.io.IOException * @throws java.io.FileNotFoundException */ protected void flushToDisk() throws java.io.IOException, java.io.FileNotFoundException { java.util.LinkedList ml = memorybuflist; log.debug(Messages.getMessage("maxCached", "" + maxCached, "" + totalsz)); if (ml != null) { if (null == cachediskstream) { // Need to create a disk cache try { MessageContext mc = MessageContext.getCurrentContext(); String attdir = (mc == null) ? null : mc.getStrProp( MessageContext.ATTACHMENTS_DIR); diskCacheFile = java.io.File.createTempFile("Axis", ".att", (attdir == null) ? null : new File( attdir)); if(log.isDebugEnabled()) { log.debug( Messages.getMessage( "diskCache", diskCacheFile.getAbsolutePath())); } cachediskstream = new java.io.BufferedOutputStream( new java.io.FileOutputStream(diskCacheFile)); int listsz = ml.size(); // Write out the entire memory held store to disk. for (java.util.Iterator it = ml.iterator(); it.hasNext();) { byte[] rbuf = (byte[]) it.next(); int bwrite = (listsz-- == 0) ? currentMemoryBufSz : rbuf.length; cachediskstream.write(rbuf, 0, bwrite); if (closed) { cachediskstream.close(); cachediskstream = null; } } memorybuflist = null; } catch (java.lang.SecurityException se) { diskCacheFile = null; cachediskstream = null; maxCached = java.lang.Integer.MAX_VALUE; log.info(Messages.getMessage("nodisk00"), se); } } } } public synchronized boolean delete() { boolean ret = false; deleted = true; memorybuflist = null; if (diskCacheFile != null) { if (cachediskstream != null) { try { cachediskstream.close(); } catch (Exception e) { } cachediskstream = null; } Object[] array = readers.keySet().toArray(); for (int i = 0; i < array.length; i++) { Instream stream = (Instream) array[i]; if (null != stream) { try { stream.close(); } catch (Exception e) { } } } readers.clear(); try { diskCacheFile.delete(); ret = true; } catch (Exception e) { // Give it our best shot. diskCacheFile.deleteOnExit(); } } return ret; } // inner classes cannot have static declarations... /** Field is_log */ protected static Log is_log = LogFactory.getLog(Instream.class.getName()); /** * Inner class to handle getting an input stream to this data source * Handles creating an input stream to the source. */ private class Instream extends java.io.InputStream { /** bytes read. */ protected long bread = 0; /** The real stream. */ java.io.FileInputStream fin = null; /** The position in the list were we are reading from. */ int currentIndex = 0; /** the buffer we are currently reading from. */ byte[] currentBuf = null; /** The current position in there. */ int currentBufPos = 0; /** The read stream has been closed. */ boolean readClosed = false; /** * Constructor Instream. * * @throws java.io.IOException if the Instream could not be created or * if the data source has been deleted */ protected Instream() throws java.io.IOException { if (deleted) { throw new java.io.IOException( Messages.getMessage("resourceDeleted")); } readers.put(this, null); } /** * Query for the number of bytes available for reading. * * @return the number of bytes left * * @throws java.io.IOException if this stream is not in a state that * supports reading */ public int available() throws java.io.IOException { if (deleted) { throw new java.io.IOException( Messages.getMessage("resourceDeleted")); } if (readClosed) { throw new java.io.IOException( Messages.getMessage("streamClosed")); } int ret = new Long(Math.min(Integer.MAX_VALUE, totalsz - bread)).intValue(); if (debugEnabled) { is_log.debug("available() = " + ret + "."); } return ret; } /** * Read a byte from the stream. * * @return byte read or -1 if no more data. * * @throws java.io.IOException */ public int read() throws java.io.IOException { synchronized (ManagedMemoryDataSource.this) { byte[] retb = new byte[1]; int br = read(retb, 0, 1); if (br == -1) { return -1; } return 0xFF & retb[0]; } } /** * Not supported. * * @return */ public boolean markSupported() { if (debugEnabled) { is_log.debug("markSupported() = " + false + "."); } return false; } /** * Not supported. * * @param readlimit */ public void mark(int readlimit) { if (debugEnabled) { is_log.debug("mark()"); } } /** * Not supported. * * @throws java.io.IOException */ public void reset() throws java.io.IOException { if (debugEnabled) { is_log.debug("reset()"); } throw new java.io.IOException(Messages.getMessage("noResetMark")); } public long skip(long skipped) throws java.io.IOException { if (debugEnabled) { is_log.debug("skip(" + skipped + ")."); } if (deleted) { throw new java.io.IOException( Messages.getMessage("resourceDeleted")); } if (readClosed) { throw new java.io.IOException( Messages.getMessage("streamClosed")); } if (skipped < 1) { return 0; // nothing to skip. } synchronized (ManagedMemoryDataSource.this) { skipped = Math.min(skipped, totalsz - bread); // only skip what we've read. if (skipped == 0) { return 0; } java.util.List ml = memorybuflist; // hold the memory list. int bwritten = 0; if (ml != null) { if (null == currentBuf) { // get the buffer we need to read from. currentBuf = (byte[]) ml.get(currentIndex); currentBufPos = 0; // start reading from the begining. } do { long bcopy = Math.min(currentBuf.length - currentBufPos, skipped - bwritten); bwritten += bcopy; currentBufPos += bcopy; if (bwritten < skipped) { currentBuf = (byte[]) ml.get(++currentIndex); currentBufPos = 0; } } while (bwritten < skipped); } if (null != fin) { fin.skip(skipped); } bread += skipped; } if (debugEnabled) { is_log.debug("skipped " + skipped + "."); } return skipped; } public int read(byte[] b, int off, int len) throws java.io.IOException { if (debugEnabled) { is_log.debug(this.hashCode() + " read(" + off + ", " + len + ")"); } if (deleted) { throw new java.io.IOException( Messages.getMessage("resourceDeleted")); } if (readClosed) { throw new java.io.IOException( Messages.getMessage("streamClosed")); } if (b == null) { throw new InternalException(Messages.getMessage("nullInput")); } if (off < 0) { throw new IndexOutOfBoundsException( Messages.getMessage("negOffset", "" + off)); } if (len < 0) { throw new IndexOutOfBoundsException( Messages.getMessage("length", "" + len)); } if (len + off > b.length) { throw new IndexOutOfBoundsException( Messages.getMessage("writeBeyond")); } if (len == 0) { return 0; } int bwritten = 0; synchronized (ManagedMemoryDataSource.this) { if (bread == totalsz) { return -1; } java.util.List ml = memorybuflist; long longlen = len; longlen = Math.min( longlen, totalsz - bread); // Only return the number of bytes in the data store that is left. len = new Long(longlen).intValue(); if (debugEnabled) { is_log.debug("len = " + len); } if (ml != null) { if (null == currentBuf) { // Get the buffer we need to read from. currentBuf = (byte[]) ml.get(currentIndex); currentBufPos = 0; // New buffer start from the begining. } do { // The bytes to copy, the minimum of the bytes left in this buffer or bytes remaining. int bcopy = Math.min(currentBuf.length - currentBufPos, len - bwritten); // Copy the data. System.arraycopy(currentBuf, currentBufPos, b, off + bwritten, bcopy); bwritten += bcopy; currentBufPos += bcopy; if (bwritten < len) { // Get the next buffer. currentBuf = (byte[]) ml.get(++currentIndex); currentBufPos = 0; } } while (bwritten < len); } if ((bwritten == 0) && (null != diskCacheFile)) { if (debugEnabled) { is_log.debug(Messages.getMessage("reading", "" + len)); } if (null == fin) { // we are now reading from disk. if (debugEnabled) { is_log.debug( Messages.getMessage( "openBread", diskCacheFile.getCanonicalPath())); } if (debugEnabled) { is_log.debug(Messages.getMessage("openBread", "" + bread)); } fin = new java.io.FileInputStream(diskCacheFile); if (bread > 0) { fin.skip(bread); // Skip what we've read so far. } } if (cachediskstream != null) { if (debugEnabled) { is_log.debug(Messages.getMessage("flushing")); } cachediskstream.flush(); } if (debugEnabled) { is_log.debug(Messages.getMessage("flushing")); is_log.debug("len=" + len); is_log.debug("off=" + off); is_log.debug("b.length=" + b.length); } bwritten = fin.read(b, off, len); } if (bwritten > 0) { bread += bwritten; } } if (debugEnabled) { is_log.debug(this.hashCode() + Messages.getMessage("read", "" + bwritten)); } return bwritten; } /** * close the stream. * * @throws java.io.IOException */ public synchronized void close() throws java.io.IOException { if (debugEnabled) { is_log.debug("close()"); } if (!readClosed) { readers.remove(this); readClosed = true; if (fin != null) { fin.close(); } fin = null; } } protected void finalize() throws Throwable { close(); } } // endof innerclass Instream // Used to test. /** * Method main * * @param arg */ public static void main(String arg[]) { // test try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } } /** * get the filename of the content if it is cached to disk. * @return file object pointing to file, or null for memory-stored content */ public File getDiskCacheFile() { return diskCacheFile; } }
7,771
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/AttachmentsImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* @author Rob Jellinghaus (robj@unrealities.com) */ /* @author Rick Rineholt */ package org.apache.axis.attachments; import org.apache.axis.AxisFault; import org.apache.axis.Part; import org.apache.axis.SOAPPart; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.activation.DataHandler; import javax.activation.DataSource; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; /** * Implements the Attachment interface, via an actual Hashmap of actual * AttachmentParts. */ public class AttachmentsImpl implements Attachments { protected static Log log = LogFactory.getLog(AttachmentsImpl.class.getName()); /** Field attachments. */ private HashMap attachments = new java.util.HashMap(); /** Field orderedAttachments. */ private LinkedList orderedAttachments = new LinkedList(); /** Field soapPart. */ protected SOAPPart soapPart = null; /** * The actual stream to manage the multi-related input stream. */ protected MultiPartInputStream mpartStream = null; /** * The form of the attachments, whether MIME or DIME. */ protected int sendtype= Attachments.SEND_TYPE_NOTSET; /** * This is the content location as specified in SOAP with Attachments. * This maybe null if the message had no Content-Location specifed. */ protected String contentLocation = null; /** * The HashMap for DataHandler Managements. */ private HashMap stackDataHandler = new HashMap(); /** * Used to distribute attachment streams without caching them. */ private IncomingAttachmentStreams _streams = null; private boolean _askedForAttachments = false; private boolean _askedForStreams = false; /** * Construct one of these on a parent Message. * Should only ever be called by Message constructor! * * @param intialContents should be anything but today only a stream is * supported. * @param contentType The mime content type of the stream for transports * that provide it. * @param contentLocation * * @throws org.apache.axis.AxisFault */ public AttachmentsImpl( Object intialContents, String contentType, String contentLocation) throws org.apache.axis.AxisFault { if (contentLocation != null) { contentLocation = contentLocation.trim(); if (contentLocation.length() == 0) { contentLocation = null; } } this.contentLocation = contentLocation; if (contentType != null) { if (contentType.equals(org.apache.axis.Message.MIME_UNKNOWN)) { } else { java.util.StringTokenizer st = new java.util.StringTokenizer(contentType, " \t;"); if (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equalsIgnoreCase( org.apache.axis.Message.MIME_MULTIPART_RELATED)) { sendtype= SEND_TYPE_MIME; mpartStream = new org.apache.axis.attachments.MultiPartRelatedInputStream( contentType, (java.io.InputStream) intialContents); if (null == contentLocation) { // If the content location is not specified as // of the main message use the SOAP content location. contentLocation = mpartStream.getContentLocation(); if (contentLocation != null) { contentLocation = contentLocation.trim(); if (contentLocation.length() == 0) { contentLocation = null; } } } soapPart = new org.apache.axis.SOAPPart(null, mpartStream, false); MultiPartRelatedInputStream specificType = (MultiPartRelatedInputStream) mpartStream; _streams = new MultipartAttachmentStreams(specificType.boundaryDelimitedStream, specificType.orderedParts); } else if (token.equalsIgnoreCase(org.apache.axis.Message.MIME_APPLICATION_DIME)) { try{ mpartStream= new MultiPartDimeInputStream( (java.io.InputStream) intialContents); soapPart = new org.apache.axis.SOAPPart(null, mpartStream, false); }catch(Exception e){ throw org.apache.axis.AxisFault.makeFault(e);} sendtype= SEND_TYPE_DIME; MultiPartDimeInputStream specificType = (MultiPartDimeInputStream) mpartStream; _streams = new DimeAttachmentStreams(specificType.dimeDelimitedStream); } else if (token.indexOf(org.apache.axis.Message.CONTENT_TYPE_MTOM)!=-1){ sendtype = SEND_TYPE_MTOM; } } } } } /** * Copies attachment references from the multipartStream to local list. * Done only once per object creation. * * @throws AxisFault */ private void mergeinAttachments() throws AxisFault { if (mpartStream != null) { Collection atts = mpartStream.getAttachments(); if(contentLocation == null) contentLocation= mpartStream.getContentLocation(); mpartStream = null; setAttachmentParts(atts); } } /** * This method uses getAttacmentByReference() to look for attachment. * If attachment has been found, it will be removed from the list, and * returned to the user. * @param reference The reference that referers to an attachment. * * @return The part associated with the removed attachment, or null. * * @throws org.apache.axis.AxisFault */ public Part removeAttachmentPart(String reference) throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } multipart = null; dimemultipart = null; mergeinAttachments(); Part removedPart = getAttachmentByReference(reference); if (removedPart != null) { attachments.remove(removedPart.getContentId()); attachments.remove(removedPart.getContentLocation()); orderedAttachments.remove(removedPart); } return removedPart; } /** * Adds an existing attachment to this list. * Note: Passed part will be bound to this message. * @param newPart new part to add * @return Part old attachment with the same Content-ID, or null. * * @throws org.apache.axis.AxisFault */ public Part addAttachmentPart(Part newPart) throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } multipart = null; dimemultipart = null; mergeinAttachments(); Part oldPart = (Part) attachments.put(newPart.getContentId(), newPart); if (oldPart != null) { orderedAttachments.remove(oldPart); attachments.remove(oldPart.getContentLocation()); } orderedAttachments.add(newPart); if (newPart.getContentLocation() != null) { attachments.put(newPart.getContentLocation(), newPart); } return oldPart; } public Part createAttachmentPart(Object datahandler) throws org.apache.axis.AxisFault { // Searching for the same attachements Integer key = new Integer(datahandler.hashCode()); if (stackDataHandler.containsKey(key)) { return (Part)stackDataHandler.get(key); } multipart = null; dimemultipart = null; mergeinAttachments(); if (!(datahandler instanceof javax.activation.DataHandler)) { throw new org.apache.axis.AxisFault( Messages.getMessage( "unsupportedAttach", datahandler.getClass().getName(), javax.activation.DataHandler.class.getName())); } Part ret = new AttachmentPart((javax.activation.DataHandler) datahandler); addAttachmentPart(ret); // Store the current DataHandler with its key stackDataHandler.put(key, ret); return ret; } /** * Add the collection of parts. * * @param parts * * @throws org.apache.axis.AxisFault */ public void setAttachmentParts(java.util.Collection parts) throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } removeAllAttachments(); if ((parts != null) && !parts.isEmpty()) { for (java.util.Iterator i = parts.iterator(); i.hasNext();) { Object part = i.next(); if (null != part) { if(part instanceof Part) addAttachmentPart((Part)part); else createAttachmentPart(part); } } } } /** * This method should look at a refernce and determine if it is a CID: or * url to look for attachment. * <br> * Note: if Content-Id or Content-Location headers have changed by outside * code, lookup will not return proper values. In order to change these * values attachment should be removed, then added again. * @param reference The reference in the xml that referers to an attachment. * * @return The part associated with the attachment. * * @throws org.apache.axis.AxisFault */ public Part getAttachmentByReference(String reference) throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } if (null == reference) { return null; } reference = reference.trim(); if (0 == reference.length()) { return null; } mergeinAttachments(); //This search will pickit up if its fully qualified location or if it's a content-id // that is not prefixed by the cid. Part ret = (Part) attachments.get(reference); if( null != ret) return ret; if (!reference.startsWith(Attachments.CIDprefix) && (null != contentLocation)) { //Not a content-id check to see if its a relative location id. String fqreference = contentLocation; if (!fqreference.endsWith("/")) { fqreference += "/"; } if (reference.startsWith("/")) { fqreference += reference.substring(1); } else { fqreference += reference; } // lets see if we can get it as Content-Location ret = (AttachmentPart) attachments.get(fqreference); } if( null == ret && reference.startsWith(Attachments.CIDprefix)){ //This is a content-id lets see if we have it. ret = (Part) attachments.get( reference.substring(4)); } return ret; } /** * This method will return all attachments as a collection. * * @return A collection of attachments. * * @throws org.apache.axis.AxisFault */ public java.util.Collection getAttachments() throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } mergeinAttachments(); return new LinkedList(orderedAttachments); } /** * From the complex stream return the root part. * Today this is SOAP. * * @return the root <code>Part</code> */ public Part getRootPart() { return soapPart; } public void setRootPart(Part newRoot) { try { this.soapPart = (SOAPPart) newRoot; multipart = null; dimemultipart = null; } catch (ClassCastException e) { throw new ClassCastException(Messages.getMessage("onlySOAPParts")); } } /** multipart , cached entries for the stream of attachment that are going to be sent. */ javax.mail.internet.MimeMultipart multipart = null; DimeMultiPart dimemultipart = null; /** * Get the content length of the stream. * * @return the content length of the stream * * @throws org.apache.axis.AxisFault */ public long getContentLength() throws org.apache.axis.AxisFault { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } mergeinAttachments(); int sendtype= this.sendtype == SEND_TYPE_NOTSET ? SEND_TYPE_DEFAULT : this.sendtype; try { if(sendtype == SEND_TYPE_MIME || sendtype == SEND_TYPE_MTOM) return org.apache.axis.attachments.MimeUtils.getContentLength( multipart != null ? multipart : (multipart = org.apache.axis.attachments.MimeUtils.createMP(soapPart.getAsString(), orderedAttachments, getSendType()))); else if (sendtype == SEND_TYPE_DIME)return createDimeMessage().getTransmissionSize(); } catch (Exception e) { throw AxisFault.makeFault(e); } return 0; } /** * Creates the DIME message * * @return a DIME part * * @throws org.apache.axis.AxisFault if the part could not be built */ protected DimeMultiPart createDimeMessage() throws org.apache.axis.AxisFault{ int sendtype= this.sendtype == SEND_TYPE_NOTSET ? SEND_TYPE_DEFAULT : this.sendtype; if (sendtype == SEND_TYPE_DIME){ if(dimemultipart== null){ dimemultipart= new DimeMultiPart(); dimemultipart.addBodyPart(new DimeBodyPart( soapPart.getAsBytes(), DimeTypeNameFormat.URI, "http://schemas.xmlsoap.org/soap/envelope/", "uuid:714C6C40-4531-442E-A498-3AC614200295")); for( java.util.Iterator i= orderedAttachments.iterator(); i.hasNext(); ){ AttachmentPart part= (AttachmentPart)i.next(); DataHandler dh= AttachmentUtils. getActivationDataHandler(part); dimemultipart.addBodyPart(new DimeBodyPart(dh,part.getContentId())); } } } return dimemultipart; } /** * Write the content to the stream. * * @param os * * @throws org.apache.axis.AxisFault */ public void writeContentToStream(java.io.OutputStream os) throws org.apache.axis.AxisFault { int sendtype= this.sendtype == SEND_TYPE_NOTSET ? SEND_TYPE_DEFAULT : this.sendtype; try{ mergeinAttachments(); if(sendtype == SEND_TYPE_MIME || sendtype == SEND_TYPE_MTOM){ org.apache.axis.attachments.MimeUtils.writeToMultiPartStream(os, (multipart != null) ? multipart : (multipart = org.apache.axis.attachments.MimeUtils.createMP( soapPart.getAsString(), orderedAttachments, getSendType()))); for (java.util.Iterator i = orderedAttachments.iterator(); i.hasNext();) { AttachmentPart part = (AttachmentPart) i.next(); DataHandler dh = AttachmentUtils.getActivationDataHandler(part); DataSource ds = dh.getDataSource(); if ((ds != null) && (ds instanceof ManagedMemoryDataSource)) { ((ManagedMemoryDataSource) ds).delete(); } } }else if (sendtype == SEND_TYPE_DIME)createDimeMessage().write(os); }catch(Exception e){ throw org.apache.axis.AxisFault.makeFault(e);} } /** * Gets the content type for the whole stream. * * @return the content type for the whole stream * * @throws org.apache.axis.AxisFault */ public String getContentType() throws org.apache.axis.AxisFault { mergeinAttachments(); int sendtype= this.sendtype == SEND_TYPE_NOTSET ? SEND_TYPE_DEFAULT : this.sendtype; if(sendtype == SEND_TYPE_MIME || sendtype == SEND_TYPE_MTOM) return org.apache.axis.attachments.MimeUtils.getContentType((multipart != null) ? multipart : (multipart = org.apache.axis.attachments.MimeUtils.createMP( soapPart.getAsString(), orderedAttachments, getSendType()))); else return org.apache.axis.Message.MIME_APPLICATION_DIME; } /** * This is the number of attachments. * * @return the number of attachments */ public int getAttachmentCount() { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } try { mergeinAttachments(); // force a serialization of the message so that // any attachments will be added soapPart.saveChanges(); return orderedAttachments.size(); } catch (AxisFault e) { log.warn(Messages.getMessage("exception00"),e); } return 0; } /** * Determine if an object is to be treated as an attchment. * * @param value the value that is to be determined if * its an attachment. * * @return True if value should be treated as an attchment. */ public boolean isAttachment(Object value) { return AttachmentUtils.isAttachment(value); } /** * Removes all <CODE>AttachmentPart</CODE> objects that have * been added to this <CODE>SOAPMessage</CODE> object. * * <P>This method does not touch the SOAP part.</P> */ public void removeAllAttachments() { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } try { multipart = null; dimemultipart = null; mergeinAttachments(); attachments.clear(); orderedAttachments.clear(); stackDataHandler.clear(); } catch (AxisFault af){ log.warn(Messages.getMessage("exception00"),af); } } /** * Retrieves all the <CODE>AttachmentPart</CODE> objects * that have header entries that match the specified headers. * Note that a returned attachment could have headers in * addition to those specified. * @param headers a <CODE>MimeHeaders</CODE> * object containing the MIME headers for which to * search * @return an iterator over all attachments that have a header * that matches one of the given headers */ public java.util.Iterator getAttachments( javax.xml.soap.MimeHeaders headers) { if (_askedForStreams) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } java.util.Vector vecParts = new java.util.Vector(); java.util.Iterator iterator = GetAttachmentsIterator(); while(iterator.hasNext()){ Part part = (Part) iterator.next(); if(part instanceof AttachmentPart){ if(((AttachmentPart)part).matches(headers)){ vecParts.add(part); } } } return vecParts.iterator(); } /** * get an iterator over all attachments. This * @return iterator of Part Objects; some of which may be * AttachmentPart instances * @see org.apache.axis.Part * @see AttachmentPart */ private java.util.Iterator GetAttachmentsIterator() { java.util.Iterator iterator = attachments.values().iterator(); return iterator; } /** * Create a new attachment Part in this Message. * Will actually, and always, return an AttachmentPart. * * @return a new attachment Part * * @throws org.apache.axis.AxisFault */ public Part createAttachmentPart() throws org.apache.axis.AxisFault { return new AttachmentPart(); } public void setSendType( int sendtype){ if( sendtype < 1) throw new IllegalArgumentException(""); if( sendtype > SEND_TYPE_MAX ) throw new IllegalArgumentException(""); this.sendtype= sendtype; } public int getSendType(){ return sendtype; } /** * dispose of the attachments and their files; do not use the object * after making this call. */ public void dispose() { java.util.Iterator iterator = GetAttachmentsIterator(); while (iterator.hasNext()) { Part part = (Part) iterator.next(); if (part instanceof AttachmentPart) { AttachmentPart apart=(AttachmentPart)part; apart.dispose(); } } } // consider type-safe e-num here? /** * Determine how an object typically sent as attachments are to * be represented. Currently, MIME DIME and NONE are reccognised. * * @param value a String representing a sending type, treated in a * case-insensetive manner * @return an <code>int</code> send type code */ public static int getSendType(String value) { if (value.equalsIgnoreCase("MTOM")) return SEND_TYPE_MTOM; if (value.equalsIgnoreCase("MIME")) return SEND_TYPE_MIME; if (value.equalsIgnoreCase("DIME")) return SEND_TYPE_DIME; if (value.equalsIgnoreCase("NONE")) return SEND_TYPE_NONE; return SEND_TYPE_NOTSET; } /** * For a given sendType value, return a string representation. * * @param value a type code integer * @return a <code>String</code> representation of <code>value</code> */ public static String getSendTypeString(int value) { if (value == SEND_TYPE_MTOM) { return "MTOM"; } if (value == SEND_TYPE_MIME) { return "MIME"; } if (value == SEND_TYPE_DIME) { return "DIME"; } if (value == SEND_TYPE_NONE) { return "NONE"; } return null; } /** * Once this method is called, attachments can only be accessed via the InputStreams. * Any other access to the attachments collection (e.g. via getAttachments()) is * prohibited and will cause a IllegalStateException to be thrown. * * @return All of the attachment streams. */ public IncomingAttachmentStreams getIncomingAttachmentStreams() { if (_askedForAttachments) { throw new IllegalStateException(Messages.getMessage("concurrentModificationOfStream")); } _askedForStreams = true; mpartStream = null; // todo: comment return _streams; } }
7,772
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MimeMultipartDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import javax.activation.DataSource; import javax.mail.internet.MimeMultipart; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MimeMultipartDataSource implements DataSource { public static final String CONTENT_TYPE = "multipart/mixed"; private final String name; private final String contentType; private byte[] data; private ByteArrayOutputStream os; public MimeMultipartDataSource(String name, MimeMultipart data) { this.name = name; this.contentType = data == null ? CONTENT_TYPE : data.getContentType(); os = new ByteArrayOutputStream(); try { if (data != null) { data.writeTo(os); } } catch (Exception e) { // Is this sufficient? } } // ctor public String getName() { return name; } // getName public String getContentType() { return contentType; } // getContentType public InputStream getInputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return new ByteArrayInputStream(data == null ? new byte[0] : data); } // getInputStream public OutputStream getOutputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return os; } // getOutputStream } // class MimeMultipartDataSource
7,773
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DimeMultiPart.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Rick Rineholt */ package org.apache.axis.attachments; /** * This class hold all parts of a DIME multipart message. */ public final class DimeMultiPart { static final long transSize = Integer.MAX_VALUE; static final byte CURRENT_VERSION = 1; //Anything above this we don't support. protected java.util.Vector parts = new java.util.Vector(); public DimeMultiPart() {} public void addBodyPart(DimeBodyPart part) { parts.add(part); } public void write(java.io.OutputStream os) throws java.io.IOException { int size = parts.size(); int last = size - 1; for (int i = 0; i < size; ++i) ((DimeBodyPart) parts.elementAt(i)).write(os, (byte) ((i == 0 ? DimeBodyPart.POSITION_FIRST : (byte) 0) | (i == last ? DimeBodyPart.POSITION_LAST : (byte) 0)), transSize); } public long getTransmissionSize() { long size = 0; for (int i = parts.size() - 1; i > -1; --i) size += ((DimeBodyPart) parts.elementAt(i)).getTransmissionSize( transSize); return size; } }
7,774
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DimeBodyPart.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Rick Rineholt */ package org.apache.axis.attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.activation.DataHandler; import javax.activation.DataSource; import java.io.BufferedInputStream; import java.io.IOException; import java.util.StringTokenizer; /** * This class is a single part for DIME mulitpart message. <pre> DIME 1.0 format 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | VERSION |B|E|C| TYPE_T| OPT_T | OPTIONS_LENGTH | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ID_LENGTH | TYPE_LENGTH | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | DATA_LENGTH | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / OPTIONS + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / ID + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / TYPE + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / DATA + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> */ /** * Holds one attachment DIME part. */ public class DimeBodyPart { protected static Log log = LogFactory.getLog(DimeBodyPart.class.getName()); protected Object data = null; protected DimeTypeNameFormat dtnf = null; protected byte[] type = null; protected byte[] id = null; static final byte POSITION_FIRST = (byte) 0x04; static final byte POSITION_LAST = (byte) 0x02; private static final byte CHUNK = 0x01; //Means set the chunk bit private static final byte CHUNK_NEXT = 0x2; //Means this was part of a CHUNK private static final byte ONLY_CHUNK = -1;//Means only one chunk was sent private static final byte LAST_CHUNK = (byte)0;//Means many chunks were sent private static int MAX_TYPE_LENGTH = (1 << 16) - 1; private static int MAX_ID_LENGTH = (1 << 16) - 1; static final long MAX_DWORD = 0xffffffffL; // fixme: don't use? is this for inheritance only? I can't find any // classes that extend this protected DimeBodyPart() {} //do not use. /** * Create a DIME Attachment Part. * @param data a byte array containing the data as the attachment. * @param format the type format for the data. * @param type the type of the data * @param id the ID for the DIME part. * */ public DimeBodyPart(byte[] data, DimeTypeNameFormat format, String type, String id) { System.arraycopy(data, 0, this.data = new byte[ data.length], 0, data.length); this.dtnf = format; this.type = type.getBytes(); if (this.type.length > MAX_TYPE_LENGTH) throw new IllegalArgumentException(Messages.getMessage ("attach.dimetypeexceedsmax", "" + this.type.length, "" + MAX_TYPE_LENGTH)); this.id = id.getBytes(); if (this.id.length > MAX_ID_LENGTH) throw new IllegalArgumentException( Messages.getMessage("attach.dimelengthexceedsmax", "" + this.id.length, "" + MAX_ID_LENGTH)); } /** * Create a DIME Attachment Part. * @param dh the data for the attachment as a JAF datahadler. * @param format the type format for the data. * @param type the type of the data * @param id the ID for the DIME part. * */ public DimeBodyPart(DataHandler dh, DimeTypeNameFormat format, String type, String id) { this.data = dh; this.dtnf = format; if (type == null || type.length() == 0) type = "application/octet-stream"; this.type = type.getBytes(); if (this.type.length > MAX_TYPE_LENGTH) throw new IllegalArgumentException(Messages.getMessage( "attach.dimetypeexceedsmax", "" + this.type.length, "" + MAX_TYPE_LENGTH)); this.id = id.getBytes(); if (this.id.length > MAX_ID_LENGTH) throw new IllegalArgumentException(Messages.getMessage( "attach.dimelengthexceedsmax", "" + this.id.length, "" + MAX_ID_LENGTH)); } /** * Create a DIME Attachment Part. * @param dh the data for the attachment as a JAF datahadler. * The type and foramt is derived from the DataHandler. * @param id the ID for the DIME part. * */ public DimeBodyPart(DataHandler dh, String id) { this(dh, DimeTypeNameFormat.MIME, dh.getContentType(), id); String ct = dh.getContentType(); if (ct != null) { ct = ct.trim(); if (ct.toLowerCase().startsWith("application/uri")) { StringTokenizer st = new StringTokenizer(ct, " \t;"); String t = st.nextToken(" \t;"); if (t.equalsIgnoreCase("application/uri")) { for (; st.hasMoreTokens();) { t = st.nextToken(" \t;"); if (t.equalsIgnoreCase("uri")) { t = st.nextToken("="); if (t != null) { t = t.trim(); if (t.startsWith("\"")) t = t.substring(1); if (t.endsWith("\"")) t = t.substring(0, t.length() - 1); this.type = t.getBytes(); this.dtnf = DimeTypeNameFormat.URI; } return; } else if (t.equalsIgnoreCase("uri=")) { t = st.nextToken(" \t;"); if (null != t && t.length() != 0) { t = t.trim(); if (t.startsWith("\"")) t= t.substring(1); if (t.endsWith("\"")) t= t.substring(0, t.length() - 1); this.type = t.getBytes(); this.dtnf = DimeTypeNameFormat.URI; return; } } else if (t.toLowerCase().startsWith("uri=")) { if (-1 != t.indexOf('=')) { t = t.substring(t.indexOf('=')).trim(); if (t.length() != 0) { t = t.trim(); if (t.startsWith("\"")) t = t.substring(1); if (t.endsWith("\"")) t = t.substring(0, t.length() - 1); this.type = t.getBytes(); this.dtnf = DimeTypeNameFormat.URI; return; } } } } } } } } /** * Write to stream the data using maxchunk for the largest junk. * * @param os the <code>OutputStream</code> to write to * @param position the position to write * @param maxchunk the maximum length of any one chunk * @throws IOException if there was a problem writing data to the stream */ void write(java.io.OutputStream os, byte position, long maxchunk) throws java.io.IOException { if (maxchunk < 1) throw new IllegalArgumentException( Messages.getMessage("attach.dimeMaxChunkSize0", "" + maxchunk)); if (maxchunk > MAX_DWORD) throw new IllegalArgumentException( Messages.getMessage("attach.dimeMaxChunkSize1", "" + maxchunk)); if (data instanceof byte[]) { send(os, position, (byte[]) data, maxchunk); } else if (data instanceof DynamicContentDataHandler) { send(os, position, (DynamicContentDataHandler) data, maxchunk); } else if (data instanceof DataHandler) { DataSource source = ((DataHandler)data).getDataSource(); DynamicContentDataHandler dh2 = new DynamicContentDataHandler(source); send(os, position, dh2, maxchunk); } } /** * Write to stream the data using the default largest chunk size. * * @param os the <code>OutputStream</code> to write to * @param position the position to write * @throws IOException if there was a problem writing data to the stream */ void write(java.io.OutputStream os, byte position) throws java.io.IOException { write(os, position, MAX_DWORD); } private static final byte[] pad = new byte[4]; void send(java.io.OutputStream os, byte position, byte[] data, final long maxchunk)throws java.io.IOException { send(os, position, data, 0, data.length, maxchunk); } void send(java.io.OutputStream os, byte position, byte[] data, int offset, final int length, final long maxchunk) throws java.io.IOException { byte chunknext = 0; do { int sendlength = (int) Math.min(maxchunk, length - offset); sendChunk(os, position, data, offset, sendlength, (byte) ((sendlength < (length - offset) ? CHUNK : 0) | chunknext)); offset += sendlength; chunknext = CHUNK_NEXT; } while (offset < length); } void send(java.io.OutputStream os, byte position, DataHandler dh, final long maxchunk) throws java.io.IOException { java.io.InputStream in = null; try { long dataSize = getDataSize(); in = dh.getInputStream(); byte[] readbuf = new byte[64 * 1024]; int bytesread; sendHeader(os, position, dataSize, (byte) 0); long totalsent = 0; do { bytesread = in.read(readbuf); if (bytesread > 0) { os.write(readbuf, 0, bytesread); totalsent += bytesread; } } while (bytesread > -1); os.write(pad, 0, dimePadding(totalsent)); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } } } /** * Special case for dynamically generated content. * maxchunk is currently ignored since the default is 2GB. * The chunk size is retrieved from the DynamicContentDataHandler * * @param os * @param position * @param dh * @param maxchunk * @throws java.io.IOException */ void send(java.io.OutputStream os, byte position, DynamicContentDataHandler dh, final long maxchunk) throws java.io.IOException { BufferedInputStream in = new BufferedInputStream(dh.getInputStream()); try { final int myChunkSize = dh.getChunkSize(); byte[] buffer1 = new byte[myChunkSize]; byte[] buffer2 = new byte[myChunkSize]; int bytesRead1 = 0 , bytesRead2 = 0; bytesRead1 = in.read(buffer1); if(bytesRead1 < 0) { sendHeader(os, position, 0, ONLY_CHUNK); os.write(pad, 0, dimePadding(0)); return; } byte chunkbyte = CHUNK; do { bytesRead2 = in.read(buffer2); if(bytesRead2 < 0) { //last record...do not set the chunk bit. //buffer1 contains the last chunked record!! //Need to distinguish if this is the first //chunk to ensure the TYPE and ID are sent if ( chunkbyte == CHUNK ){ chunkbyte = ONLY_CHUNK; } else { chunkbyte = LAST_CHUNK; } sendChunk(os, position, buffer1, 0, bytesRead1, chunkbyte); break; } sendChunk(os, position, buffer1, 0, bytesRead1, chunkbyte); //set chunk byte to next chunk flag to avoid //sending TYPE and ID on subsequent chunks chunkbyte = CHUNK_NEXT; //now that we have written out buffer1, copy buffer2 into to buffer1 System.arraycopy(buffer2,0,buffer1,0,myChunkSize); bytesRead1 = bytesRead2; }while(bytesRead2 > 0); } finally { try { in.close(); } catch (IOException e) { // ignore } } } protected void sendChunk(java.io.OutputStream os, final byte position, byte[] data, byte chunk) throws java.io.IOException { sendChunk(os, position, data, 0, data.length, chunk); } protected void sendChunk(java.io.OutputStream os, final byte position, byte[] data, int offset, int length, byte chunk) throws java.io.IOException { sendHeader(os, position, length, chunk); os.write(data, offset, length); os.write(pad, 0, dimePadding(length)); } static final byte CURRENT_OPT_T = (byte) 0; protected void sendHeader(java.io.OutputStream os, final byte position, long length, byte chunk) throws java.io.IOException { byte[] fixedHeader = new byte[12]; //If first chunk then send TYPE and ID boolean isFirstChunk = ((chunk == CHUNK) || (chunk == ONLY_CHUNK)); //If chunk is ONLY_NEXT then //reset to CHUNK so CF is set. //If chunk is ONLY_CHUNK (first and last chunk) //then do not set CF since this is the only chunk if ( chunk == CHUNK_NEXT ){ chunk = CHUNK; } else if ( chunk == ONLY_CHUNK ){ chunk = LAST_CHUNK; } //VERSION fixedHeader[0] = (byte)((DimeMultiPart.CURRENT_VERSION << 3) & 0xf8); // B, E fixedHeader[0] |= (byte) ((position & (byte) 0x6) & ((chunk & CHUNK) != 0 ? ~POSITION_LAST : ~0) & ((chunk & CHUNK_NEXT) != 0 ? ~POSITION_FIRST : ~0)); fixedHeader[0] |= (chunk & CHUNK); boolean MB = 0 != (0x4 & fixedHeader[0]); //TYPE_T if ( MB || isFirstChunk ){ //If this is a follow on chunk dont send id again. fixedHeader[1] = (byte) ((dtnf.toByte() << 4) & 0xf0); } else { fixedHeader[1] = (byte) 0x00; } //OPT_T fixedHeader[1] |= (byte) (CURRENT_OPT_T & 0xf); //OPTION_LENGTH fixedHeader[2] = (byte) 0; fixedHeader[3] = (byte) 0; //ID_LENGTH if ( (MB || isFirstChunk) && (id != null && id.length > 0)) { //If this is a follow on chunk dont send id again. fixedHeader[4] = (byte) ((id.length >>> 8) & 0xff); fixedHeader[5] = (byte) ((id.length) & 0xff); } else { fixedHeader[4] = (byte) 0; fixedHeader[5] = (byte) 0; } //TYPE_LENGTH if ( MB || isFirstChunk ) { fixedHeader[6] = (byte) ((type.length >>> 8) & 0xff); fixedHeader[7] = (byte) ((type.length) & 0xff); } else { fixedHeader[6] = (byte) 0; fixedHeader[7] = (byte) 0; } //DATA_LENGTH fixedHeader[8] = (byte) ((length >>> 24) & 0xff); fixedHeader[9] = (byte) ((length >>> 16) & 0xff); fixedHeader[10] = (byte) ((length >>> 8) & 0xff); fixedHeader[11] = (byte) (length & 0xff); os.write(fixedHeader); //OPTIONS + PADDING // (NONE) //ID + PADDING if ( (MB || isFirstChunk) && (id != null && id.length > 0)) { os.write(id); os.write(pad, 0, dimePadding(id.length)); } //TYPE + PADDING if ( MB || isFirstChunk ) { os.write(type); os.write(pad, 0, dimePadding(type.length)); } } static final int dimePadding(long l) { return (int) ((4L - (l & 0x3L)) & 0x03L); } long getTransmissionSize(long chunkSize) { long size = 0; size += id.length; size += dimePadding(id.length); size += type.length; size += dimePadding(type.length); //no options. long dataSize = getDataSize(); if(0 == dataSize){ size+=12; //header size. }else{ long fullChunks = dataSize / chunkSize; long lastChunkSize = dataSize % chunkSize; if (0 != lastChunkSize) size += 12; //12 bytes for fixed header size += 12 * fullChunks; //add additional header size for each chunk. size += fullChunks * dimePadding(chunkSize); size += dimePadding(lastChunkSize); size += dataSize; } return size; } long getTransmissionSize() { return getTransmissionSize(MAX_DWORD); } protected long getDataSize() { if (data instanceof byte[]) return ((byte[]) (data)).length; if (data instanceof DataHandler) return getDataSize((DataHandler) data); return -1; } protected long getDataSize(DataHandler dh) { long dataSize = -1L; try { DataSource ds = dh.getDataSource(); //Do files our selfs since this is costly to read in. Ask the file system. // This is 90% of the use of attachments. if (ds instanceof javax.activation.FileDataSource) { javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds; java.io.File df = fdh.getFile(); if (!df.exists()) { throw new RuntimeException( Messages.getMessage("noFile", df.getAbsolutePath())); } dataSize = df.length(); } else { dataSize = 0; java.io.InputStream in = ds.getInputStream(); byte[] readbuf = new byte[64 * 1024]; int bytesread; do { bytesread = in.read(readbuf); if (bytesread > 0) dataSize += bytesread; } while (bytesread > -1); if (in.markSupported()) { //Leave the stream open for future reading // and reset the stream pointer to the first byte in.reset(); } else { //FIXME: bug http://nagoya.apache.org/jira/secure/ViewIssue.jspa?key=AXIS-1126 //if we close this then how can we read the file? eh? in.close(); } } } catch (Exception e) { //TODO: why are exceptions swallowed here? log.error(Messages.getMessage("exception00"), e); } return dataSize; } }
7,775
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MultiPartInputStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.Part; /** * This simulates the multipart stream. * * @author Rick Rineholt */ public abstract class MultiPartInputStream extends java.io.FilterInputStream { MultiPartInputStream(java.io.InputStream is) { super(is); } public abstract Part getAttachmentByReference(final String[] id) throws org.apache.axis.AxisFault; public abstract java.util.Collection getAttachments() throws org.apache.axis.AxisFault; /** * Return the content location. * @return the Content-Location of the stream. * Null if no content-location specified. */ public abstract String getContentLocation(); /** * Return the content id of the stream. * * @return the Content-Location of the stream. * Null if no content-location specified. */ public abstract String getContentId(); }
7,776
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/SourceDataSource.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import javax.activation.DataSource; import javax.xml.transform.stream.StreamSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.BufferedReader; import java.io.BufferedInputStream; import java.net.URL; public class SourceDataSource implements DataSource { public static final String CONTENT_TYPE = "text/xml"; private final String name; private final String contentType; private byte[] data; private ByteArrayOutputStream os; public SourceDataSource(String name, StreamSource data) { this(name, CONTENT_TYPE, data); } // ctor public SourceDataSource(String name, String contentType, StreamSource data) { this.name = name; this.contentType = contentType == null ? CONTENT_TYPE : contentType; os = new ByteArrayOutputStream(); try { if (data != null) { // Try the Reader first Reader reader = data.getReader(); if (reader != null) { reader = new BufferedReader(reader); int ch; while ((ch = reader.read())!=-1) { os.write(ch); } } else { // Try the InputStream InputStream is = data.getInputStream(); if (is == null) { // Try the URL String id = data.getSystemId(); if (id != null) { URL url = new URL(id); is = url.openStream(); } } if (is != null) { is = new BufferedInputStream(is); // If reading from a socket or URL, we could get a partial read. byte[] bytes = null; int avail; while ((avail = is.available()) > 0) { if (bytes == null || avail > bytes.length) bytes = new byte[avail]; is.read(bytes, 0, avail); os.write(bytes, 0, avail); } } } } } catch (Exception e) { // Is this sufficient? } } // ctor public String getName() { return name; } // getName public String getContentType() { return contentType; } // getContentType public InputStream getInputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return new ByteArrayInputStream(data == null ? new byte[0] : data); } // getInputStream public OutputStream getOutputStream() throws IOException { if (os.size() != 0) { data = os.toByteArray(); os.reset(); } return os; } // getOutputStream } // class SourceDataSource
7,777
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/OctetStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; // fixme: this is completely undocumented public class OctetStream { private byte[] bytes = null; public OctetStream() { } public OctetStream(byte[] bytes) { this.bytes = bytes; } public byte[] getBytes() { return this.bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } }
7,778
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DimeDelimitedInputStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.IOException; /** * This class takes the input stream and turns it multiple streams. DIME version 0 format <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ --- | VERSION |B|E|C| TYPE_T| OPT_T | OPTIONS_LENGTH | A +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ID_LENGTH | TYPE_LENGTH | Always present 12 bytes +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ even on chunked data. | DATA_LENGTH | V +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ --- | / / OPTIONS + PADDING / / (absent for version 0) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / ID + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / TYPE + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / DATA + PADDING / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> * This implementation of input stream does not support marking operations. * * @author Rick Rineholt */ public class DimeDelimitedInputStream extends java.io.FilterInputStream { protected static Log log = LogFactory.getLog(DimeDelimitedInputStream.class.getName()); java.io.InputStream is = null; //The source input stream. volatile boolean closed = true; //The stream has been closed. boolean theEnd = false; //There are no more streams left. boolean moreChunks = false; //More chunks are a coming! boolean MB = false; //First part of the stream. MUST be SOAP. boolean ME = false; //Last part of stream. DimeTypeNameFormat tnf = null; String type = null; String id = null; long recordLength = 0L; //length of the record. long bytesRead = 0; //How many bytes of the record have been read. int dataPadLength = 0; //How many pad bytes there are. private static byte[] trash = new byte[4]; protected int streamNo = 0; protected IOException streamInError = null; protected static int streamCount = 0; //number of streams produced. protected static synchronized int newStreamNo() { log.debug(Messages.getMessage("streamNo", "" + (streamCount + 1))); return ++streamCount; } static boolean isDebugEnabled = false; /** * Gets the next stream. From the previous using new buffer reading size. * * @return the dime delmited stream, null if there are no more streams * @throws IOException if there was an error loading the data for the next * stream */ synchronized DimeDelimitedInputStream getNextStream() throws IOException { if (null != streamInError) throw streamInError; if (theEnd) return null; if (bytesRead < recordLength || moreChunks) //Stream must be read in succession throw new RuntimeException(Messages.getMessage( "attach.dimeReadFullyError")); dataPadLength -= readPad(dataPadLength); //Create an new dime stream that comes after this one. return new DimeDelimitedInputStream(this.is); } /** * Create a new dime stream. * * @param is the <code>InputStream</code> to wrap * @throws IOException if anything goes wrong */ DimeDelimitedInputStream(java.io.InputStream is) throws IOException { super(null); //we handle everything so this is not necessary, don't won't to hang on to a reference. isDebugEnabled = log.isDebugEnabled(); streamNo = newStreamNo(); closed = false; this.is = is; readHeader(false); } private final int readPad(final int size) throws IOException { if (0 == size) return 0; int read = readFromStream(trash, 0, size); if (size != read) { streamInError = new IOException(Messages.getMessage( "attach.dimeNotPaddedCorrectly")); throw streamInError; } return read; } private final int readFromStream(final byte[] b) throws IOException { return readFromStream(b, 0, b.length); } private final int readFromStream(final byte[] b, final int start, final int length) throws IOException { if (length == 0) return 0; int br = 0; int brTotal = 0; do { try { br = is.read(b, brTotal + start, length - brTotal); } catch (IOException e) { streamInError = e; throw e; } if (br > 0) brTotal += br; } while (br > -1 && brTotal < length); return br > -1 ? brTotal : br; } /** * Get the id for this stream part. * @return the id; */ public String getContentId() { return id; } public DimeTypeNameFormat getDimeTypeNameFormat() { return tnf; } /** * Get the type, as read from the header. * * @return the type of this dime */ public String getType() { return type; } /** * Read from the DIME stream. * * @param b is the array to read into. * @param off is the offset * @return the number of bytes read. -1 if endof stream * @throws IOException if data could not be read from the stream */ public synchronized int read(byte[] b, final int off, final int len) throws IOException { if (closed) { dataPadLength -= readPad(dataPadLength); throw new IOException(Messages.getMessage("streamClosed")); } return _read(b, off, len); } protected int _read(byte[] b, final int off, final int len) throws IOException { if (len < 0) throw new IllegalArgumentException (Messages.getMessage("attach.readLengthError", "" + len)); if (off < 0) throw new IllegalArgumentException (Messages.getMessage("attach.readOffsetError", "" + off)); if (b == null) throw new IllegalArgumentException (Messages.getMessage("attach.readArrayNullError")); if (b.length < off + len) throw new IllegalArgumentException (Messages.getMessage("attach.readArraySizeError", "" + b.length, "" + len, "" + off)); if (null != streamInError) throw streamInError; if (0 == len) return 0; //quick. if(recordLength == 0 && bytesRead == 0 && !moreChunks){ ++bytesRead; //odd case no data to read -- give back 0 next time -1; if(ME){ finalClose(); } return 0; } if (bytesRead >= recordLength && !moreChunks) { dataPadLength -= readPad(dataPadLength); if(ME){ finalClose(); } return -1; } int totalbytesread = 0; int bytes2read = 0; do { if (bytesRead >= recordLength && moreChunks) readHeader(true); bytes2read = (int) Math.min(recordLength - bytesRead, (long) len - totalbytesread); bytes2read = (int) Math.min(recordLength - bytesRead, (long) len - totalbytesread); try { bytes2read = is.read(b, off + totalbytesread, bytes2read); } catch (IOException e) { streamInError = e; throw e; } if (0 < bytes2read) { totalbytesread += bytes2read; bytesRead += bytes2read; } } while (bytes2read > -1 && totalbytesread < len && (bytesRead < recordLength || moreChunks)); if (0 > bytes2read) { if (moreChunks) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError0")); throw streamInError; } if (bytesRead < recordLength) { streamInError = new IOException(Messages.getMessage ("attach.DimeStreamError1", "" + (recordLength - bytesRead))); throw streamInError; } if (!ME) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError0")); throw streamInError; } //in theory the last chunk of data should also have been padded, but lets be tolerant of that. dataPadLength = 0; } else if (bytesRead >= recordLength) { //get rid of pading. try { dataPadLength -= readPad(dataPadLength); } catch (IOException e) { //in theory the last chunk of data should also have been padded, but lets be tolerant of that. if (!ME) throw e; else { dataPadLength = 0; streamInError = null; } } } if (bytesRead >= recordLength && ME) { finalClose(); } return totalbytesread >= 0 ? totalbytesread : -1; } void readHeader(boolean isChunk) throws IOException { bytesRead = 0; //How many bytes of the record have been read. if (isChunk) { if (!moreChunks) throw new RuntimeException( Messages.getMessage("attach.DimeStreamError2")); dataPadLength -= readPad(dataPadLength); //Just incase it was left over. } byte[] header = new byte[12]; if (header.length != readFromStream(header)) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError3", "" + header.length)); throw streamInError; } //VERSION byte version = (byte) ((header[0] >>> 3) & 0x1f); if (version > DimeMultiPart.CURRENT_VERSION) { streamInError = new IOException(Messages.getMessage("attach.DimeStreamError4", "" + version, "" + DimeMultiPart.CURRENT_VERSION)); throw streamInError; } //B, E, C MB = 0 != (0x4 & header[0]); ME = 0 != (0x2 & header[0]); moreChunks = 0 != (0x1 & header[0]); //TYPE_T if (!isChunk) tnf = DimeTypeNameFormat.parseByte((byte) ((header[1] >>> 4) & (byte) 0xf)); //OPTIONS_LENGTH int optionsLength = ((((int) header[2]) << 8) & 0xff00) | ((int) header[3]); //ID_LENGTH int idLength = ((((int) header[4]) << 8) & 0xff00) | ((int) header[5]); //TYPE_LENGTH int typeLength = ((((int) header[6]) << 8) & 0xff00) | ((int) header[7]); //DATA_LENGTH recordLength = ((((long) header[8]) << 24) & 0xff000000L) | ((((long) header[9]) << 16) & 0xff0000L) | ((((long) header[10]) << 8) & 0xff00L) | ((long) header[11] & 0xffL); //OPTIONS + PADDING if (0 != optionsLength) { byte[] optBytes = new byte[optionsLength]; if (optionsLength != readFromStream(optBytes)) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError5", "" + optionsLength)); throw streamInError; } optBytes = null; //Yup throw it away, don't know anything about options. int pad = DimeBodyPart.dimePadding(optionsLength); if (pad != readFromStream(header, 0, pad)) { streamInError = new IOException( Messages.getMessage("attach.DimeStreamError7")); throw streamInError; } } // ID + PADDING if (0 < idLength) { byte[] idBytes = new byte[ idLength]; if (idLength != readFromStream(idBytes)) { streamInError = new IOException( Messages.getMessage("attach.DimeStreamError8")); throw streamInError; } if (idLength != 0 && !isChunk) { id = new String(idBytes); } int pad = DimeBodyPart.dimePadding(idLength); if (pad != readFromStream(header, 0, pad)) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError9")); throw streamInError; } } //TYPE + PADDING if (0 < typeLength) { byte[] typeBytes = new byte[typeLength]; if (typeLength != readFromStream(typeBytes)) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError10")); throw streamInError; } if (typeLength != 0 && !isChunk) { type = new String(typeBytes); } int pad = DimeBodyPart.dimePadding(typeLength); if (pad != readFromStream(header, 0, pad)) { streamInError = new IOException(Messages.getMessage( "attach.DimeStreamError11")); throw streamInError; } } log.debug("MB:" + MB + ", ME:" + ME + ", CF:" + moreChunks + "Option length:" + optionsLength + ", ID length:" + idLength + ", typeLength:" + typeLength + ", TYPE_T:" + tnf); log.debug("id:\"" + id + "\""); log.debug("type:\"" + type + "\""); log.debug("recordlength:\"" + recordLength + "\""); dataPadLength = DimeBodyPart.dimePadding(recordLength); } /** * Read from the delimited stream. * @param b is the array to read into. Read as much as possible * into the size of this array. * @return the number of bytes read. -1 if endof stream * @throws IOException if data could not be read from the stream */ public int read(byte[] b) throws IOException { return read(b, 0, b.length); } // fixme: this seems a bit inefficient /** * Read from the boundary delimited stream. * * @return the byte read, or -1 if endof stream * @throws IOException if there was an error reading the data */ public int read() throws IOException { byte[] b = new byte[1]; int read = read(b, 0, 1); if (read < 0) return -1; // fixme: should we also check for read != 1? return (b[0] & 0xff); // convert byte value to a positive int } /** * Closes the stream. * <p> * This will take care of flushing any remaining data to the strea. * <p> * Multiple calls to this method will result in the stream being closed once * and then all subsequent calls being ignored. * * @throws IOException if the stream could not be closed */ public void close() throws IOException { synchronized(this){ if (closed) return; closed = true; //mark it closed. } log.debug(Messages.getMessage("bStreamClosed", "" + streamNo)); if (bytesRead < recordLength || moreChunks) { //We need get this off the stream. //Easy way to flush through the stream; byte[] readrest = new byte[1024 * 16]; int bread = 0; do { bread = _read(readrest, 0, readrest.length);//should also close the orginal stream. } while (bread > -1); } dataPadLength -= readPad(dataPadLength); } // fixme: if mark is not supported, do we throw an exception here? /** * Mark the stream. * This is not supported. */ public void mark(int readlimit) {//do nothing } public void reset() throws IOException { streamInError = new IOException(Messages.getMessage( "attach.bounday.mns")); throw streamInError; } public boolean markSupported() { return false; } public synchronized int available() throws IOException { if (null != streamInError) throw streamInError; int chunkAvail = (int) Math.min((long) Integer.MAX_VALUE, recordLength - bytesRead); int streamAvail = 0; try { streamAvail = is.available(); } catch (IOException e) { streamInError = e; throw e; } if (chunkAvail == 0 && moreChunks && (12 + dataPadLength) <= streamAvail) { dataPadLength -= readPad(dataPadLength); readHeader(true); return available(); } return Math.min(streamAvail, chunkAvail); } protected void finalClose() throws IOException { try{ theEnd = true; if(null != is) is.close(); }finally{ is= null; } } }
7,779
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/IncomingAttachmentStreams.java
package org.apache.axis.attachments; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.axis.AxisFault; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; /** * Similiar in concept to an iterator over the delimited streams inside * of the HTTP stream. One difference between this class and a full fledge * iterator is that the class is unable to tell if there are more streams until * the last one has been fully read. It will however, return null when the end * of the HTTP stream has been reached. Since the HTTP stream can contain data * in different formats (e.g. DIME or SwA), the IncomingAttachmentStreams class * will be an abstract class letting its derivatives handle the specifics to * parsing out the HTTP stream. However, the class will implement methods that * keep track of when each of the delimited streams are completely read. This is * necessary since the next stream cannot be created until the previous stream * has been fully read due to the fact that we are actually dealing with a * single stream delimited by markers. * * @author David Wong * @author Brian Husted */ public abstract class IncomingAttachmentStreams { private boolean _readyToGetNextStream = true; /** * @return The next delimited stream or null if no additional streams are * left. */ public abstract IncomingAttachmentInputStream getNextStream() throws AxisFault; /** * @return True if the next stream can be read, false otherwise. */ public final boolean isReadyToGetNextStream() { return _readyToGetNextStream; } /** * Set the ready flag. Intended for the inner class to use. * * @param ready */ protected final void setReadyToGetNextStream(boolean ready) { _readyToGetNextStream = ready; } public final class IncomingAttachmentInputStream extends InputStream { private HashMap _headers = null; private InputStream _stream = null; /** * @param in */ public IncomingAttachmentInputStream(InputStream in) { _stream = in; } /** * @return MIME headers for this attachment. May be null if no headers * were set. */ public Map getHeaders() { return _headers; } /** * Add a header. * * @param name * @param value */ public void addHeader(String name, String value) { if (_headers == null) { _headers = new HashMap(); } _headers.put(name, value); } /** * Get a header value. * * @param name * @return The header found or null if not found. */ public String getHeader(String name) { Object header = null; if (_headers == null || (header = _headers.get(name)) == null) { return null; } return header.toString(); } /** * @return The header with HTTPConstants.HEADER_CONTENT_ID as the key. */ public String getContentId() { return getHeader(HTTPConstants.HEADER_CONTENT_ID); } /** * @return The header with HTTPConstants.HEADER_CONTENT_LOCATION as the * key. */ public String getContentLocation() { return getHeader(HTTPConstants.HEADER_CONTENT_LOCATION); } /** * @return The header with HTTPConstants.HEADER_CONTENT_TYPE as the key. */ public String getContentType() { return getHeader(HTTPConstants.HEADER_CONTENT_TYPE); } /** * Don't want to support mark and reset since this may get us into * concurrency problem when different pieces of software may have a * handle to the underlying InputStream. */ public boolean markSupported() { return false; } public void reset() throws IOException { throw new IOException(Messages.getMessage("markNotSupported")); } public void mark(int readLimit) { // do nothing } public int read() throws IOException { int retval = _stream.read(); IncomingAttachmentStreams.this .setReadyToGetNextStream(retval == -1); return retval; } public int read(byte[] b) throws IOException { int retval = _stream.read(b); IncomingAttachmentStreams.this .setReadyToGetNextStream(retval == -1); return retval; } public int read(byte[] b, int off, int len) throws IOException { int retval = _stream.read(b, off, len); IncomingAttachmentStreams.this .setReadyToGetNextStream(retval == -1); return retval; } } }
7,780
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/AttachmentPart.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.Part; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.utils.SessionUtils; import org.apache.axis.utils.IOUtils; import org.apache.commons.logging.Log; import javax.activation.DataHandler; import javax.imageio.ImageIO; import javax.xml.soap.SOAPException; import javax.xml.transform.stream.StreamSource; import java.util.Iterator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; /** * An attachment part. * * */ public class AttachmentPart extends javax.xml.soap.AttachmentPart implements Part { /** Field log */ protected static Log log = LogFactory.getLog(AttachmentPart.class.getName()); /** * The data handler. * <p> * TODO: make private? * */ javax.activation.DataHandler datahandler = null; /** Field mimeHeaders. */ private javax.xml.soap.MimeHeaders mimeHeaders = new javax.xml.soap.MimeHeaders(); private Object contentObject; /** * The name of a file used to store the data. */ private String attachmentFile; /** * Bulds a new <code>AttachmentPart</code>. */ public AttachmentPart() { setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils.generateSessionId()); } /** * Bulds a new <code>AttachmentPart</code> with a <code>DataHandler</code>. * * @param dh the <code>DataHandler</code> */ public AttachmentPart(javax.activation.DataHandler dh) { setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils.generateSessionId()); datahandler = dh; if(dh != null) { setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, dh.getContentType()); javax.activation.DataSource ds = dh.getDataSource(); if (ds instanceof ManagedMemoryDataSource) { extractFilename((ManagedMemoryDataSource)ds); //and get the filename if appropriate } } } // fixme: be aware, this may never be called /** * On death, we clean up our file. * * @throws Throwable if anything went wrong during finalization */ protected void finalize() throws Throwable { dispose(); } /** * Get the data handler. * * @return the activation <code>DataHandler</code> */ public javax.activation.DataHandler getActivationDataHandler() { return datahandler; } /** * getContentType * * @return content type */ public String getContentType() { return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE); } /** * Add the specified MIME header, as per JAXM. * * @param header * @param value */ public void addMimeHeader(String header, String value) { mimeHeaders.addHeader(header, value); } /** * Get the specified MIME header. * * @param header * * @return */ public String getFirstMimeHeader(String header) { String[] values = mimeHeaders.getHeader(header.toLowerCase()); if ((values != null) && (values.length > 0)) { return values[0]; } return null; } /** * check if this Part's mimeheaders matches the one passed in. * TODO: Am not sure about the logic. * * @param headers the <code>MimeHeaders</code> to check * @return true if all header name, values in <code>headers</code> are * found, false otherwise */ public boolean matches(javax.xml.soap.MimeHeaders headers) { for (Iterator i = headers.getAllHeaders(); i.hasNext();) { javax.xml.soap.MimeHeader hdr = (javax.xml.soap.MimeHeader) i.next(); String values[] = mimeHeaders.getHeader(hdr.getName()); boolean found = false; if (values != null) { for (int j = 0; j < values.length; j++) { if (!hdr.getValue().equalsIgnoreCase(values[j])) { continue; } found = true; break; } } if (!found) { return false; } } return true; } public String getContentLocation() { return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION); } public void setContentLocation(String loc) { setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, loc); } public void setContentId(String newCid) { setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, newCid); } public String getContentId() { return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_ID); } public java.util.Iterator getMatchingMimeHeaders(final String[] match) { return mimeHeaders.getMatchingHeaders(match); } public java.util.Iterator getNonMatchingMimeHeaders(final String[] match) { return mimeHeaders.getNonMatchingHeaders(match); } public Iterator getAllMimeHeaders() { return mimeHeaders.getAllHeaders(); } /** * Changes the first header entry that matches the given name * to the given value, adding a new header if no existing * header matches. This method also removes all matching * headers but the first. * * <P>Note that RFC822 headers can only contain US-ASCII * characters.</P> * @param name a <CODE>String</CODE> giving the * name of the header for which to search * @param value a <CODE>String</CODE> giving the * value to be set for the header whose name matches the * given name * @throws java.lang.IllegalArgumentException if * there was a problem with the specified mime header name * or value */ public void setMimeHeader(String name, String value) { mimeHeaders.setHeader(name, value); } /** Removes all the MIME header entries. */ public void removeAllMimeHeaders() { mimeHeaders.removeAllHeaders(); } /** * Removes all MIME headers that match the given name. * @param header - the string name of the MIME * header/s to be removed */ public void removeMimeHeader(String header) { mimeHeaders.removeHeader(header); } /** * Gets the <CODE>DataHandler</CODE> object for this <CODE> * AttachmentPart</CODE> object. * @return the <CODE>DataHandler</CODE> object associated with * this <CODE>AttachmentPart</CODE> object * @throws SOAPException if there is * no data in this <CODE>AttachmentPart</CODE> object */ public DataHandler getDataHandler() throws SOAPException { if(datahandler == null) { throw new SOAPException(Messages.getMessage("noContent")); } return datahandler; } /** * Sets the given <CODE>DataHandler</CODE> object as the * data handler for this <CODE>AttachmentPart</CODE> object. * Typically, on an incoming message, the data handler is * automatically set. When a message is being created and * populated with content, the <CODE>setDataHandler</CODE> * method can be used to get data from various data sources into * the message. * @param datahandler <CODE>DataHandler</CODE> object to * be set * @throws java.lang.IllegalArgumentException if * there was a problem with the specified <CODE> * DataHandler</CODE> object */ public void setDataHandler(DataHandler datahandler) { if(datahandler == null) { throw new java.lang.IllegalArgumentException( Messages.getMessage("illegalArgumentException00")); } this.datahandler = datahandler; setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, datahandler.getContentType()); //now look at the source of the data javax.activation.DataSource ds = datahandler.getDataSource(); if (ds instanceof ManagedMemoryDataSource) { //and get the filename if appropriate extractFilename((ManagedMemoryDataSource)ds); } } /** * Gets the content of this <CODE>AttachmentPart</CODE> object * as a Java object. The type of the returned Java object * depends on (1) the <CODE>DataContentHandler</CODE> object * that is used to interpret the bytes and (2) the <CODE> * Content-Type</CODE> given in the header. * * <P>For the MIME content types "text/plain", "text/html" and * "text/xml", the <CODE>DataContentHandler</CODE> object does * the conversions to and from the Java types corresponding to * the MIME types. For other MIME types,the <CODE> * DataContentHandler</CODE> object can return an <CODE> * InputStream</CODE> object that contains the content data as * raw bytes.</P> * * <P>A JAXM-compliant implementation must, as a minimum, * return a <CODE>java.lang.String</CODE> object corresponding * to any content stream with a <CODE>Content-Type</CODE> * value of <CODE>text/plain</CODE> and a <CODE> * javax.xml.transform.StreamSource</CODE> object * corresponding to a content stream with a <CODE> * Content-Type</CODE> value of <CODE>text/xml</CODE>. For * those content types that an installed <CODE> * DataContentHandler</CODE> object does not understand, the * <CODE>DataContentHandler</CODE> object is required to * return a <CODE>java.io.InputStream</CODE> object with the * raw bytes.</P> * @return a Java object with the content of this <CODE> * AttachmentPart</CODE> object * @throws SOAPException if there is no content set * into this <CODE>AttachmentPart</CODE> object or if there * was a data transformation error */ public Object getContent() throws SOAPException { if(contentObject != null) { return contentObject; } if(datahandler == null) { throw new SOAPException(Messages.getMessage("noContent")); } javax.activation.DataSource ds = datahandler.getDataSource(); InputStream is = null; try { is = ds.getInputStream();; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new SOAPException(io); } if (ds.getContentType().equals("text/plain")) { try { byte[] bytes = new byte[is.available()]; IOUtils.readFully(is, bytes); return new String(bytes); } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new SOAPException(io); } } else if (ds.getContentType().equals("text/xml")) { return new StreamSource(is); } else if (ds.getContentType().equals("image/gif") || ds.getContentType().equals("image/jpeg")) { try { return ImageIO.read(is); } catch (Exception ex) { log.error(Messages.getMessage("javaIOException00"), ex); throw new SOAPException(ex); } } return is; } /** * Sets the content of this attachment part to that of the * given <CODE>Object</CODE> and sets the value of the <CODE> * Content-Type</CODE> header to the given type. The type of the * <CODE>Object</CODE> should correspond to the value given for * the <CODE>Content-Type</CODE>. This depends on the particular * set of <CODE>DataContentHandler</CODE> objects in use. * @param object the Java object that makes up * the content for this attachment part * @param contentType the MIME string that * specifies the type of the content * @throws java.lang.IllegalArgumentException if * the contentType does not match the type of the content * object, or if there was no <CODE> * DataContentHandler</CODE> object for this content * object * @see #getContent() getContent() */ public void setContent(Object object, String contentType) { ManagedMemoryDataSource source = null; setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); if (object instanceof String) { try { String s = (String) object; java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(s.getBytes()); source = new ManagedMemoryDataSource(bais, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = object; return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException( Messages.getMessage("illegalArgumentException00")); } } else if (object instanceof java.io.InputStream) { try { source = new ManagedMemoryDataSource((java.io.InputStream) object, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = null; // the stream has been consumed return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException(Messages.getMessage ("illegalArgumentException00")); } } else if (object instanceof StreamSource) { try { source = new ManagedMemoryDataSource(((StreamSource)object).getInputStream(), ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); extractFilename(source); datahandler = new DataHandler(source); contentObject = null; // the stream has been consumed return; } catch (java.io.IOException io) { log.error(Messages.getMessage("javaIOException00"), io); throw new java.lang.IllegalArgumentException(Messages.getMessage ("illegalArgumentException00")); } } else { throw new java.lang.IllegalArgumentException( Messages.getMessage("illegalArgumentException00")); } } /** * Clears out the content of this <CODE> * AttachmentPart</CODE> object. The MIME header portion is left * untouched. */ public void clearContent() { datahandler = null; contentObject = null; } /** * Returns the number of bytes in this <CODE> * AttachmentPart</CODE> object. * @return the size of this <CODE>AttachmentPart</CODE> object * in bytes or -1 if the size cannot be determined * @throws SOAPException if the content of this * attachment is corrupted of if there was an exception * while trying to determine the size. */ public int getSize() throws SOAPException { if (datahandler == null) { return 0; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { datahandler.writeTo(bout); } catch (java.io.IOException ex) { log.error(Messages.getMessage("javaIOException00"), ex); throw new SOAPException(Messages.getMessage("javaIOException01", ex.getMessage()), ex); } return bout.size(); } /** * Gets all the values of the header identified by the given * <CODE>String</CODE>. * @param name the name of the header; example: * "Content-Type" * @return a <CODE>String</CODE> array giving the value for the * specified header * @see #setMimeHeader(java.lang.String, java.lang.String) setMimeHeader(java.lang.String, java.lang.String) */ public String[] getMimeHeader(String name) { return mimeHeaders.getHeader(name); } /** * Content ID. * * @return the contentId reference value that should be used directly * as an href in a SOAP element to reference this attachment. * <B>Not part of JAX-RPC, JAX-M, SAAJ, etc. </B> */ public String getContentIdRef() { return Attachments.CIDprefix + getContentId(); } /** * Maybe add file name to the attachment. * * @param source the source of the data */ private void extractFilename(ManagedMemoryDataSource source) { //check for there being a file if(source.getDiskCacheFile()!=null) { String path = source.getDiskCacheFile().getAbsolutePath(); setAttachmentFile(path); } } /** * Set the filename of this attachment part. * * @param path the new file path */ protected void setAttachmentFile(String path) { attachmentFile=path; } /** * Detach the attachment file from this class, so it is not cleaned up. * This has the side-effect of making subsequent calls to * getAttachmentFile() return <code>null</code>. */ public void detachAttachmentFile() { attachmentFile=null; } /** * Get the filename of this attachment. * * @return the filename or null for an uncached file */ public String getAttachmentFile() { return attachmentFile; } /** * when an attachment part is disposed, any associated files * are deleted, and the datahandler itself nulled. The object * is no longer completely usable, at this point */ public synchronized void dispose() { if (attachmentFile != null) { javax.activation.DataSource ds = datahandler.getDataSource(); if (ds instanceof ManagedMemoryDataSource) { ((ManagedMemoryDataSource) ds).delete(); //and delete the file } else { File f = new File(attachmentFile); //no need to check for existence here. f.delete(); } //set the filename to null to stop repeated use setAttachmentFile(null); } //clean up the datahandler, as it will have been //invalidated if it was bound to a file; if it wasnt //we get to release memory anyway datahandler = null; } }
7,781
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MimeUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Rick Rineholt * @author Wouter Cloetens (wouter@mind.be) */ package org.apache.axis.attachments; import org.apache.axis.AxisProperties; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.utils.SessionUtils; import org.apache.commons.logging.Log; import java.util.Properties; /** * This class is defines utilities for mime. */ public class MimeUtils { /** Field log */ protected static Log log = LogFactory.getLog(MimeUtils.class.getName()); /** * Determine as efficiently as possible the content length for attachments in a mail Multipart. * @param mp is the multipart to be serarched. * @return the actual length. * * @throws javax.mail.MessagingException * @throws java.io.IOException */ public static long getContentLength(javax.mail.Multipart mp) throws javax.mail.MessagingException, java.io.IOException { int totalParts = mp.getCount(); long totalContentLength = 0; for (int i = 0; i < totalParts; ++i) { javax.mail.internet.MimeBodyPart bp = (javax.mail.internet.MimeBodyPart) mp.getBodyPart(i); totalContentLength += getContentLength(bp); } String ctype = mp.getContentType(); javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(ctype); String boundaryStr = ct.getParameter("boundary"); int boundaryStrLen = boundaryStr.length() + 4; // must add two for -- prefix and another two for crlf // there is one more boundary than parts // each parts data must have crlf after it. // last boundary has an additional --crlf return totalContentLength + boundaryStrLen * (totalParts + 1) + 2 * totalParts + +4; } /** * Determine the length for the individual part. * @param bp is the part to be searched. * @return the length in bytes. */ protected static long getContentLength( javax.mail.internet.MimeBodyPart bp) { long headerLength = -1L; long dataSize = -1L; try { headerLength = getHeaderLength(bp); javax.activation.DataHandler dh = bp.getDataHandler(); javax.activation.DataSource ds = dh.getDataSource(); // Do files our selfs since this is costly to read in. Ask the file system. // This is 90% of the use of attachments. if (ds instanceof javax.activation.FileDataSource) { javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds; java.io.File df = fdh.getFile(); if (!df.exists()) { throw new RuntimeException(Messages.getMessage("noFile", df.getAbsolutePath())); } dataSize = df.length(); } else { dataSize = bp.getSize(); if (-1 == dataSize) { // Data size is not known so read it the hard way... dataSize = 0; java.io.InputStream in = ds.getInputStream(); byte[] readbuf = new byte[64 * 1024]; int bytesread; do { bytesread = in.read(readbuf); if (bytesread > 0) { dataSize += bytesread; } } while (bytesread > -1); in.close(); } } } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } return dataSize + headerLength; } /** * Gets the header length for any part. * @param bp the part to determine the header length for. * @return the length in bytes. * * @throws javax.mail.MessagingException * @throws java.io.IOException */ private static long getHeaderLength(javax.mail.internet.MimeBodyPart bp) throws javax.mail.MessagingException, java.io.IOException { javax.mail.internet.MimeBodyPart headersOnly = new javax.mail.internet.MimeBodyPart( new javax.mail.internet.InternetHeaders(), new byte[0]); for (java.util.Enumeration en = bp.getAllHeaders(); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); headersOnly.addHeader(header.getName(), header.getValue()); } java.io.ByteArrayOutputStream bas = new java.io.ByteArrayOutputStream(1024 * 16); headersOnly.writeTo(bas); bas.close(); return (long) bas.size(); // This has header length plus the crlf part that seperates the data } // fixme: filter can be replaced as it is not final - is this intended? If // so, document // fixme: the fields in filter are not protected - they can be over-written /** Field filter */ public static String[] filter = new String[]{"Message-ID", "Mime-Version", "Content-Type"}; /** * This routine will the multi part type and write it out to a stream. * * <p>Note that is does *NOT* pass <code>AxisProperties</code> * to <code>javax.mail.Session.getInstance</code>, but instead * the System properties. * </p> * @param os is the output stream to write to. * @param mp the multipart that needs to be written to the stream. */ public static void writeToMultiPartStream( java.io.OutputStream os, javax.mail.internet.MimeMultipart mp) { try { Properties props = AxisProperties.getProperties(); props.setProperty( "mail.smtp.host", "localhost"); // this is a bogus since we will never mail it. javax.mail.Session session = javax.mail.Session.getInstance(props, null); javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); message.setContent(mp); message.saveChanges(); message.writeTo(os, filter); } catch (javax.mail.MessagingException e) { log.error(Messages.getMessage("javaxMailMessagingException00"), e); } catch (java.io.IOException e) { log.error(Messages.getMessage("javaIOException00"), e); } } /** * This routine will get the content type from a mulit-part mime message. * * @param mp the MimeMultipart * @return the content type */ public static String getContentType(javax.mail.internet.MimeMultipart mp) { StringBuffer contentType = new StringBuffer(mp.getContentType()); // TODO (dims): Commons HttpClient croaks if we don't do this. // Need to get Commons HttpClient fixed. for(int i=0;i<contentType.length();){ char ch = contentType.charAt(i); if(ch=='\r'||ch=='\n') contentType.deleteCharAt(i); else i++; } return contentType.toString(); } /** * This routine will create a multipart object from the parts and the SOAP content. * @param env should be the text for the main root part. * @param parts contain a collection of the message parts. * * @return a new MimeMultipart object * * @throws org.apache.axis.AxisFault */ public static javax.mail.internet.MimeMultipart createMP( String env, java.util.Collection parts, int sendType) throws org.apache.axis.AxisFault { javax.mail.internet.MimeMultipart multipart = null; try { String rootCID = SessionUtils.generateSessionId(); if(sendType == Attachments.SEND_TYPE_MTOM) { multipart = new javax.mail.internet.MimeMultipart( "related;type=\"application/xop+xml\"; start=\"<" + rootCID + ">\"; start-info=\"text/xml\"; charset=\"utf-8\""); } else { multipart = new javax.mail.internet.MimeMultipart( "related; type=\"text/xml\"; start=\"<" + rootCID + ">\""); } javax.mail.internet.MimeBodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setText(env, "UTF-8"); if(sendType == Attachments.SEND_TYPE_MTOM){ messageBodyPart.setHeader("Content-Type", "application/xop+xml; charset=utf-8; type=\"text/xml; charset=utf-8\""); } else { messageBodyPart.setHeader("Content-Type", "text/xml; charset=UTF-8"); } messageBodyPart.setHeader("Content-Id", "<" + rootCID + ">"); messageBodyPart.setHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); multipart.addBodyPart(messageBodyPart); for (java.util.Iterator it = parts.iterator(); it.hasNext();) { org.apache.axis.Part part = (org.apache.axis.Part) it.next(); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler( part); String contentID = part.getContentId(); messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setDataHandler(dh); String contentType = part.getContentType(); if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = dh.getContentType(); } if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = "application/octet-stream"; } messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_ID, "<" + contentID + ">"); messageBodyPart.setHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); // Safe and fastest for anything other than mail; for (java.util.Iterator i = part.getNonMatchingMimeHeaders(new String[]{ HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING}); i.hasNext();) { javax.xml.soap.MimeHeader header = (javax.xml.soap.MimeHeader) i.next(); messageBodyPart.setHeader(header.getName(), header.getValue()); } multipart.addBodyPart(messageBodyPart); } } catch (javax.mail.MessagingException e) { log.error(Messages.getMessage("javaxMailMessagingException00"), e); } return multipart; } }
7,782
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MultiPartDimeInputStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.Part; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.activation.DataHandler; /** * This simulates the multipart stream. * * @author Rick Rineholt */ public class MultiPartDimeInputStream extends MultiPartInputStream { protected static Log log = LogFactory.getLog(MultiPartDimeInputStream.class.getName()); protected java.util.HashMap parts = new java.util.HashMap(); protected java.util.LinkedList orderedParts = new java.util.LinkedList(); protected int rootPartLength = 0; protected boolean closed = false; //If true the stream has been closed. protected boolean eos = false; //This is set once the SOAP packet has reached the end of stream. //This stream controls and manages the boundary. protected DimeDelimitedInputStream dimeDelimitedStream = null; protected java.io.InputStream soapStream = null; //Set the soap stream once found. protected byte[] boundary = null; protected java.io.ByteArrayInputStream cachedSOAPEnvelope = null; //Caches the soap stream if it is //Still open and a reference to read data in a later attachment occurs. protected String contentId = null; /** * Create a new Multipart stream from an input stream. * * @param is the true input stream that is read from * @throws java.io.IOException if it was not possible to build the Multipart */ public MultiPartDimeInputStream (java.io.InputStream is) throws java.io.IOException { super(null); //don't cache this stream. soapStream = dimeDelimitedStream = new DimeDelimitedInputStream(is); //The Soap stream must always be first contentId = dimeDelimitedStream.getContentId(); } public Part getAttachmentByReference(final String[] id) throws org.apache.axis.AxisFault { //First see if we have read it in yet. Part ret = null; try { for (int i = id.length - 1; ret == null && i > -1; --i) { ret = (AttachmentPart) parts.get(id[i]); } if (null == ret) { ret = readTillFound(id); } log.debug(Messages.getMessage("return02", "getAttachmentByReference(\"" + id + "\"", (ret == null ? "null" : ret.toString()))); } catch (java.io.IOException e) { throw new org.apache.axis.AxisFault(e.getClass().getName() + e.getMessage()); } return ret; } protected void addPart(String contentId, String locationId, AttachmentPart ap) { //For DIME streams Content-Location is ignored. if (contentId != null && contentId.trim().length() != 0) parts.put(contentId, ap); orderedParts.add(ap); } //Shouldn't never match protected static final String[] READ_ALL = { " * \0 ".intern()}; protected void readAll() throws org.apache.axis.AxisFault { try { readTillFound(READ_ALL); } catch (Exception e) { throw org.apache.axis.AxisFault.makeFault(e); } } public java.util.Collection getAttachments() throws org.apache.axis.AxisFault { readAll(); return new java.util.LinkedList(orderedParts); } /** * This will read streams in till the one that is needed is found. * * @param id is the stream being sought * @return a <code>Part</code> matching the ids */ protected Part readTillFound(final String[] id) throws java.io.IOException { if (dimeDelimitedStream == null) { //The whole stream has been consumed already return null; } Part ret = null; try { if (soapStream != null) { //Still on the SOAP stream. if (!eos) { //The SOAP packet has not been fully read yet. Need to store it away. java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8); byte[] buf = new byte[1024 * 16]; int byteread = 0; do { byteread = soapStream.read(buf); if (byteread > 0) { soapdata.write(buf, 0, byteread); } } while (byteread > -1); soapdata.close(); soapStream.close(); soapStream = new java.io.ByteArrayInputStream( soapdata.toByteArray()); } dimeDelimitedStream = dimeDelimitedStream.getNextStream(); } //Now start searching for the data. if (null != dimeDelimitedStream) { do { String contentId = dimeDelimitedStream.getContentId(); String type = dimeDelimitedStream.getType(); if (type != null && !dimeDelimitedStream.getDimeTypeNameFormat().equals(DimeTypeNameFormat.MIME)) { type = "application/uri; uri=\"" + type + "\""; } ManagedMemoryDataSource source = new ManagedMemoryDataSource(dimeDelimitedStream, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, type, true); DataHandler dh = new DataHandler(source); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } addPart(contentId, "", ap); for (int i = id.length - 1; ret == null && i > -1; --i) { if (contentId != null && id[i].equals(contentId)) { //This is the part being sought ret = ap; } } dimeDelimitedStream = dimeDelimitedStream.getNextStream(); } while (null == ret && null != dimeDelimitedStream); } } catch (Exception e) { throw org.apache.axis.AxisFault.makeFault(e); } return ret; } /** * Return the content location. * @return the Content-Location of the stream. * Null if no content-location specified. */ public String getContentLocation() { return null; } /** * Return the content id of the stream. * * @return the Content-Location of the stream. * Null if no content-location specified. */ public String getContentId() { return contentId; } public int read(byte[] b, int off, int len) throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage( "streamClosed")); } if (eos) { return -1; } int read = soapStream.read(b, off, len); if (read < 0) { eos = true; } return read; } public int read(byte[] b) throws java.io.IOException { return read(b, 0, b.length); } public int read() throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage( "streamClosed")); } if (eos) { return -1; } int ret = soapStream.read(); if (ret < 0) { eos = true; } return ret; } public void close() throws java.io.IOException { closed = true; soapStream.close(); } }
7,783
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/MultipartAttachmentStreams.java
package org.apache.axis.attachments; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.StringTokenizer; import javax.mail.Header; import javax.mail.MessagingException; import javax.mail.internet.InternetHeaders; import javax.mail.internet.MimeUtility; import javax.xml.soap.SOAPException; import org.apache.axis.AxisFault; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; /** * The MultipartAttachmentStreams class is used to create * IncomingAttachmentInputStream objects when the HTTP stream shows a marked * separation between the SOAP and each attachment parts. Unlike the DIME * version, this class will use the BoundaryDelimitedStream to parse data in the * SwA format. Another difference between the two is that the * MultipartAttachmentStreams class must also provide a way to hold attachment * parts parsed prior to where the SOAP part appears in the HTTP stream (i.e. * the root part of the multipart-related message). Our DIME counterpart didn't * have to worry about this since the SOAP part is guaranteed to be the first in * the stream. But since SwA has no such guarantee, we must fall back to caching * these first parts. Afterwards, we can stream the rest of the attachments that * are after the SOAP part of the request message. * * @author David Wong * @author Brian Husted * */ public final class MultipartAttachmentStreams extends IncomingAttachmentStreams { private BoundaryDelimitedStream _delimitedStream = null; private Iterator _attachmentParts = null; public MultipartAttachmentStreams(BoundaryDelimitedStream delimitedStream) throws AxisFault { this(delimitedStream, null); } public MultipartAttachmentStreams(BoundaryDelimitedStream delimitedStream, Collection priorParts) throws AxisFault { if (delimitedStream == null) { throw new AxisFault(Messages.getMessage("nullDelimitedStream")); } _delimitedStream = delimitedStream; if (priorParts != null) { setAttachmentsPriorToSoapPart(priorParts.iterator()); } } public void setAttachmentsPriorToSoapPart(Iterator iterator) { _attachmentParts = iterator; } /** * * @see org.apache.axis.attachments.IncomingAttachmentStreams#getNextStream() */ public IncomingAttachmentInputStream getNextStream() throws AxisFault { IncomingAttachmentInputStream stream; if (!isReadyToGetNextStream()) { throw new IllegalStateException(Messages .getMessage("nextStreamNotReady")); } if (_attachmentParts != null && _attachmentParts.hasNext()) { AttachmentPart part = (AttachmentPart) _attachmentParts.next(); try { stream = new IncomingAttachmentInputStream(part .getDataHandler().getInputStream()); } catch (IOException e) { throw new AxisFault(Messages .getMessage("failedToGetAttachmentPartStream"), e); } catch (SOAPException e) { throw new AxisFault(Messages .getMessage("failedToGetAttachmentPartStream"), e); } stream.addHeader(HTTPConstants.HEADER_CONTENT_ID, part .getContentId()); stream.addHeader(HTTPConstants.HEADER_CONTENT_LOCATION, part .getContentLocation()); stream.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, part .getContentType()); } else { InternetHeaders headers; try { _delimitedStream = _delimitedStream.getNextStream(); if (_delimitedStream == null) { return null; } headers = new InternetHeaders(_delimitedStream); String delimiter = null; // null for the first header String encoding = headers.getHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, delimiter); if (encoding != null && encoding.length() > 0) { encoding = encoding.trim(); stream = new IncomingAttachmentInputStream(MimeUtility .decode(_delimitedStream, encoding)); stream.addHeader( HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, encoding); } else { stream = new IncomingAttachmentInputStream(_delimitedStream); } } catch (IOException e) { throw new AxisFault(Messages .getMessage("failedToGetDelimitedAttachmentStream"), e); } catch (MessagingException e) { throw new AxisFault(Messages .getMessage("failedToGetDelimitedAttachmentStream"), e); } Header header; String name; String value; Enumeration e = headers.getAllHeaders(); while (e != null && e.hasMoreElements()) { header = (Header) e.nextElement(); name = header.getName(); value = header.getValue(); if (HTTPConstants.HEADER_CONTENT_ID.equals(name) || HTTPConstants.HEADER_CONTENT_TYPE.equals(name) || HTTPConstants.HEADER_CONTENT_LOCATION.equals(name)) { value = value.trim(); if ((HTTPConstants.HEADER_CONTENT_ID.equals(name) || HTTPConstants.HEADER_CONTENT_LOCATION .equals(name)) && (name.indexOf('>') > 0 || name.indexOf('<') > 0)) { value = new StringTokenizer(value, "<>").nextToken(); } } stream.addHeader(name, value); } } setReadyToGetNextStream(false); return stream; } }
7,784
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/BoundaryDelimitedStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * This class takes the input stream and turns it multiple streams. * * @author Rick Rineholt */ public class BoundaryDelimitedStream extends java.io.FilterInputStream { /** The <code>Log</code> that this class should log all events to. */ protected static Log log = LogFactory.getLog(BoundaryDelimitedStream.class.getName()); protected byte[] boundary = null; /** The boundary length. */ int boundaryLen = 0; /** The boundary length plus crlf. */ int boundaryBufLen = 0; /** The source input stream. */ java.io.InputStream is = null; /** The stream has been closed. */ boolean closed = true; /** eof has been detected. */ boolean eos = false; /** There are no more streams left. */ boolean theEnd = false; /** Minimum to read at one time. */ int readbufsz = 0; /** The buffer we are reading. */ byte[] readbuf = null; /** Where we have read so far in the stream. */ int readBufPos = 0; /** The number of bytes in array. */ int readBufEnd = 0; /** Field BOUNDARY_NOT_FOUND. */ protected static final int BOUNDARY_NOT_FOUND = Integer.MAX_VALUE; // Where in the stream a boundary is located. /** Field boundaryPos. */ int boundaryPos = BOUNDARY_NOT_FOUND; /** The number of streams produced. */ static int streamCount = 0; /** * Signal that a new stream has been created. * * @return */ protected static synchronized int newStreamNo() { log.debug(Messages.getMessage("streamNo", "" + (streamCount + 1))); return ++streamCount; } /** Field streamNo. */ protected int streamNo = -1; // Keeps track of stream /** Field isDebugEnabled. */ static boolean isDebugEnabled = false; /** * Gets the next stream. From the previous using the same buffer size to * read. * * @return the boundary delmited stream, null if there are no more streams. * @throws java.io.IOException if there was an error loading the data for * the next stream */ public synchronized BoundaryDelimitedStream getNextStream() throws java.io.IOException { return getNextStream(readbufsz); } /** * Gets the next stream. From the previous using new buffer reading size. * * @param readbufsz * @return the boundary delmited stream, null if there are no more streams. * @throws java.io.IOException if there was an error loading the data for * the next stream */ protected synchronized BoundaryDelimitedStream getNextStream( int readbufsz) throws java.io.IOException { BoundaryDelimitedStream ret = null; if (!theEnd) { // Create an new boundary stream that comes after this one. ret = new BoundaryDelimitedStream(this, readbufsz); } return ret; } /** * Constructor to create the next stream from the previous one. * * @param prev the previous stream * @param readbufsz how many bytes to make the read buffer * @throws java.io.IOException if there was a problem reading data from * <code>prev</code> */ protected BoundaryDelimitedStream(BoundaryDelimitedStream prev, int readbufsz) throws java.io.IOException { super(null); streamNo = newStreamNo(); boundary = prev.boundary; boundaryLen = prev.boundaryLen; boundaryBufLen = prev.boundaryBufLen; skip = prev.skip; is = prev.is; closed = false; // The new one is not closed. eos = false; // Its not at th EOS. readbufsz = prev.readbufsz; readbuf = prev.readbuf; // Move past the old boundary. readBufPos = prev.readBufPos + boundaryBufLen; readBufEnd = prev.readBufEnd; // find the new boundary. boundaryPos = boundaryPosition(readbuf, readBufPos, readBufEnd); prev.theEnd = theEnd; // The stream. } /** * Create a new boundary stream. * * @param is * @param boundary is the boundary that separates the individual streams. * @param readbufsz lets you have some control over the amount of buffering. * by buffering you can some effiency in searching. * * @throws org.apache.axis.AxisFault */ BoundaryDelimitedStream( java.io.InputStream is, byte[] boundary, int readbufsz) throws org.apache.axis.AxisFault { // super (is); super(null); // we handle everything so this is not necessary, don't won't to hang on to a reference. isDebugEnabled = log.isDebugEnabled(); streamNo = newStreamNo(); closed = false; this.is = is; // Copy the boundary array to make certain it is never altered. this.boundary = new byte[boundary.length]; System.arraycopy(boundary, 0, this.boundary, 0, boundary.length); this.boundaryLen = this.boundary.length; this.boundaryBufLen = boundaryLen + 2; // allways leave room for at least a 2x boundary // Most mime boundaries are 40 bytes or so. this.readbufsz = Math.max((boundaryBufLen) * 2, readbufsz); } private final int readFromStream(final byte[] b) throws java.io.IOException { return readFromStream(b, 0, b.length); } private final int readFromStream( final byte[] b, final int start, final int length) throws java.io.IOException { int minRead = Math.max(boundaryBufLen * 2, length); minRead = Math.min(minRead, length - start); int br = 0; int brTotal = 0; do { br = is.read(b, brTotal + start, length - brTotal); if (br > 0) { brTotal += br; } } while ((br > -1) && (brTotal < minRead)); return (brTotal != 0) ? brTotal : br; } /** * Read from the boundary delimited stream. * @param b is the array to read into. * @param off is the offset * @param len * @return the number of bytes read. -1 if endof stream. * * @throws java.io.IOException */ public synchronized int read(byte[] b, final int off, final int len) throws java.io.IOException { if (closed) { throw new java.io.IOException(Messages.getMessage("streamClosed")); } if (eos) { return -1; } if (readbuf == null) { // Allocate the buffer. readbuf = new byte[Math.max(len, readbufsz)]; readBufEnd = readFromStream(readbuf); if (readBufEnd < 0) { readbuf = null; closed = true; finalClose(); throw new java.io.IOException( Messages.getMessage("eosBeforeMarker")); } readBufPos = 0; // Finds the boundary pos. boundaryPos = boundaryPosition(readbuf, 0, readBufEnd); } int bwritten = 0; // Number of bytes written. // read and copy bytes in. do { // Always allow to have a boundary length left in the buffer. int bcopy = Math.min(readBufEnd - readBufPos - boundaryBufLen, len - bwritten); // never go past the boundary. bcopy = Math.min(bcopy, boundaryPos - readBufPos); if (bcopy > 0) { System.arraycopy(readbuf, readBufPos, b, off + bwritten, bcopy); bwritten += bcopy; readBufPos += bcopy; } if (readBufPos == boundaryPos) { eos = true; // hit the boundary so it the end of the stream. log.debug(Messages.getMessage("atEOS", "" + streamNo)); } else if (bwritten < len) { // need to get more data. byte[] dstbuf = readbuf; if (readbuf.length < len) { dstbuf = new byte[len]; } int movecnt = readBufEnd - readBufPos; // copy what was left over. System.arraycopy(readbuf, readBufPos, dstbuf, 0, movecnt); // Read in the new data. int readcnt = readFromStream(dstbuf, movecnt, dstbuf.length - movecnt); if (readcnt < 0) { readbuf = null; closed = true; finalClose(); throw new java.io.IOException( Messages.getMessage("eosBeforeMarker")); } readBufEnd = readcnt + movecnt; readbuf = dstbuf; readBufPos = 0; // start at the begining. // just move the boundary by what we moved if (BOUNDARY_NOT_FOUND != boundaryPos) { boundaryPos -= movecnt; } else { boundaryPos = boundaryPosition( readbuf, readBufPos, readBufEnd); // See if the boundary is now there. } } } // read till we get the amount or the stream is finished. while (!eos && (bwritten < len)); if (log.isDebugEnabled()) { if (bwritten > 0) { byte tb[] = new byte[bwritten]; System.arraycopy(b, off, tb, 0, bwritten); log.debug(Messages.getMessage("readBStream", new String[]{"" + bwritten, "" + streamNo, new String(tb)})); } } if (eos && theEnd) { readbuf = null; // dealloc even in Java. } return bwritten; } /** * Read from the boundary delimited stream. * @param b is the array to read into. Read as much as possible * into the size of this array. * @return the number of bytes read. -1 if endof stream. * * @throws java.io.IOException */ public int read(byte[] b) throws java.io.IOException { return read(b, 0, b.length); } /** * Read from the boundary delimited stream. * @return The byte read, or -1 if endof stream. * * @throws java.io.IOException */ public int read() throws java.io.IOException { byte[] b = new byte[1]; // quick and dirty. //for now int read = read(b); if (read < 0) { return -1; } else { return b[0]&0xff; } } /** * Closes the stream. * * @throws java.io.IOException */ public synchronized void close() throws java.io.IOException { if (closed) { return; } log.debug(Messages.getMessage("bStreamClosed", "" + streamNo)); closed = true; // mark it closed. if (!eos) { // We need get this off the stream. // Easy way to flush through the stream; byte[] readrest = new byte[1024 * 16]; int bread = 0; do { bread = read(readrest); } while (bread > -1); } } /** * mark the stream. * This is not supported. * * @param readlimit */ public void mark(int readlimit) { // do nothing } /** * reset the stream. * This is not supported. * * @throws java.io.IOException */ public void reset() throws java.io.IOException { throw new java.io.IOException( Messages.getMessage("attach.bounday.mns")); } /** * markSupported * return false; * * @return */ public boolean markSupported() { return false; } public int available() throws java.io.IOException { int bcopy = readBufEnd - readBufPos - boundaryBufLen; // never go past the boundary. bcopy = Math.min(bcopy, boundaryPos - readBufPos); return Math.max(0, bcopy); } /** * Read from the boundary delimited stream. * * @param searchbuf buffer to read from * @param start starting index * @param end ending index * @return The position of the boundary. Detects the end of the source stream. * @throws java.io.IOException if there was an error manipulating the * underlying stream */ protected int boundaryPosition(byte[] searchbuf, int start, int end) throws java.io.IOException { int foundAt = boundarySearch(searchbuf, start, end); // First find the boundary marker if (BOUNDARY_NOT_FOUND != foundAt) { // Something was found. if (foundAt + boundaryLen + 2 > end) { foundAt = BOUNDARY_NOT_FOUND; } else { // If the marker has a "--" at the end then this is the last boundary. if ((searchbuf[foundAt + boundaryLen] == '-') && (searchbuf[foundAt + boundaryLen + 1] == '-')) { finalClose(); } else if ((searchbuf[foundAt + boundaryLen] != 13) || (searchbuf[foundAt + boundaryLen + 1] != 10)) { // If there really was no crlf at then end then this is not a boundary. foundAt = BOUNDARY_NOT_FOUND; } } } return foundAt; } /* The below uses a standard textbook Boyer-Moore pattern search. */ private int[] skip = null; private int boundarySearch(final byte[] text, final int start, final int end) { // log.debug(">>>>" + start + "," + end); int i = 0, j = 0, k = 0; if (boundaryLen > (end - start)) { return BOUNDARY_NOT_FOUND; } if (null == skip) { skip = new int[256]; java.util.Arrays.fill(skip, boundaryLen); for (k = 0; k < boundaryLen - 1; k++) { skip[boundary[k]] = boundaryLen - k - 1; } } for (k = start + boundaryLen - 1; k < end; k += skip[text[k] & (0xff)]) { // log.debug(">>>>" + k); // printarry(text, k-boundaryLen+1, end); try { for (j = boundaryLen - 1, i = k; (j >= 0) && (text[i] == boundary[j]); j--) { i--; } } catch (ArrayIndexOutOfBoundsException e) { StringBuffer sb = new StringBuffer(); sb.append( ">>>" + e); // rr temporary till a boundary issue is resolved. sb.append("start=" + start); sb.append("k=" + k); sb.append("text.length=" + text.length); sb.append("i=" + i); sb.append("boundary.length=" + boundary.length); sb.append("j=" + j); sb.append("end=" + end); log.warn(Messages.getMessage("exception01",sb.toString())); throw e; } if (j == (-1)) { return i + 1; } } // log.debug(">>>> not found" ); return BOUNDARY_NOT_FOUND; } /** * Close the underlying stream and remove all references to it. * * @throws java.io.IOException if the stream could not be closed */ protected void finalClose() throws java.io.IOException { if(theEnd) return; theEnd= true; is.close(); is= null; } /** * Method printarry * * @param b * @param start * @param end */ public static void printarry(byte[] b, int start, int end) { if (log.isDebugEnabled()) { byte tb[] = new byte[end - start]; System.arraycopy(b, start, tb, 0, end - start); log.debug("\"" + new String(tb) + "\""); } } }
7,785
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DimeAttachmentStreams.java
package org.apache.axis.attachments; import java.io.IOException; import org.apache.axis.AxisFault; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; /** * * This is the concrete implementation of the IncomingAttachmentStreams class * and is used to parse data that is in the DIME format. This class will make * use of Axis' DimeDelimitedInputStream to parse the data in the HTTP stream * which will give this class the capability of creating * IncomingAttachmentInputStream objects at each marker within the HTTP stream. * * @author David Wong * @author Brian Husted * */ public final class DimeAttachmentStreams extends IncomingAttachmentStreams { private DimeDelimitedInputStream _delimitedStream = null; public DimeAttachmentStreams(DimeDelimitedInputStream stream) throws AxisFault { if (stream == null) { throw new AxisFault(Messages.getMessage("nullDelimitedStream")); } _delimitedStream = stream; } /* (non-Javadoc) * @see org.apache.axis.attachments.IncomingAttachmentStreams#getNextStream() */ public IncomingAttachmentInputStream getNextStream() throws AxisFault { IncomingAttachmentInputStream stream = null; if (!isReadyToGetNextStream()) { throw new IllegalStateException(Messages.getMessage("nextStreamNotReady")); } try { _delimitedStream = _delimitedStream.getNextStream(); if (_delimitedStream == null) { return null; } stream = new IncomingAttachmentInputStream(_delimitedStream); } catch (IOException e) { throw new AxisFault(Messages.getMessage("failedToGetDelimitedAttachmentStream"), e); } String value = _delimitedStream.getContentId(); if (value != null && value.length() > 0) { stream.addHeader(HTTPConstants.HEADER_CONTENT_ID, value); } value = _delimitedStream.getType(); if (value != null && value.length() > 0) { stream.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, value); } setReadyToGetNextStream(false); return stream; } }
7,786
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/Attachments.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import org.apache.axis.Part; /** * Access the Attachments of a Message. This interface essentially * firewalls the rest of Axis from any dependencies on javax.activation. * <p> * If javax.activation is not available, this is the *only* class that * will be compiled in org.apache.axis.attachments. * * @author Rob Jellinghaus (robj@unrealities.com) * @author Rick Rineholt */ public interface Attachments extends java.io.Serializable { /** * Adds an existing attachment to this list. * Note: Passed part will be bound to this message. * @param newPart new part to add * @return Part old attachment with the same Content-ID, or null. * @throws org.apache.axis.AxisFault */ public Part addAttachmentPart(Part newPart) throws org.apache.axis.AxisFault; /** * This method uses getAttacmentByReference() to look for attachment. * If attachment has been found, it will be removed from the list, and * returned to the user. * * @param reference The reference that referers to an attachment. * @return The part associated with the removed attachment, or null. * * @throws org.apache.axis.AxisFault */ public Part removeAttachmentPart(String reference) throws org.apache.axis.AxisFault; /** * Removes all <CODE>AttachmentPart</CODE> objects that have * been added to this <CODE>SOAPMessage</CODE> object. * * <P>This method does not touch the SOAP part.</P> */ public void removeAllAttachments(); /** * This method should look at a refernce and determine if it is a CID: or url * to look for attachment. * * @param reference The reference in the xml that referers to an attachment. * @return The part associated with the attachment. * * @throws org.apache.axis.AxisFault */ public Part getAttachmentByReference(String reference) throws org.apache.axis.AxisFault; /** * This method will return all attachments as a collection. * * @return A collection of attachments. * * @throws org.apache.axis.AxisFault */ public java.util.Collection getAttachments() throws org.apache.axis.AxisFault; /** * Retrieves all the <CODE>AttachmentPart</CODE> objects * that have header entries that match the specified headers. * Note that a returned attachment could have headers in * addition to those specified. * @param headers a <CODE>MimeHeaders</CODE> * object containing the MIME headers for which to * search * @return an iterator over all attachments that have a header * that matches one of the given headers */ public java.util.Iterator getAttachments( javax.xml.soap.MimeHeaders headers); /** * Create a new attachment Part in this Message. * Will actually, and always, return an AttachmentPart. * * @param part The part that is referenced * * @return a new attachment part * * @throws org.apache.axis.AxisFault */ public Part createAttachmentPart(Object part) throws org.apache.axis.AxisFault; /** * Create a new attachment Part in this Message. * Will actually, and always, return an AttachmentPart. * * @return a new attachment part * * @throws org.apache.axis.AxisFault */ public Part createAttachmentPart() throws org.apache.axis.AxisFault; /** * Will the attachments of this message to that of the colleciton. * * @param parts * * @throws org.apache.axis.AxisFault */ public void setAttachmentParts(java.util.Collection parts) throws org.apache.axis.AxisFault; /** * From the complex stream return the SOAP part. * @return will return the root part if the stream is supported, * otherwise null. */ public Part getRootPart(); /** * Sets the root part of this multipart block * * @param newRoot the new root <code>Part</code> */ public void setRootPart(Part newRoot); /** * Get the content length of the stream. * * @return the content length of * * @throws org.apache.axis.AxisFault */ public long getContentLength() throws org.apache.axis.AxisFault; /** * Write the content to the stream. * * @param os the stream * * @throws org.apache.axis.AxisFault */ public void writeContentToStream(java.io.OutputStream os) throws org.apache.axis.AxisFault; /** * Write the content to the stream. * * @return the content type * * @throws org.apache.axis.AxisFault */ public String getContentType() throws org.apache.axis.AxisFault; /** * This is the number of attachments. * * @return the number of attachments */ public int getAttachmentCount(); /** * Determine if an object is to be treated as an attchment. * * @param value the value that is to be determined if * its an attachment. * * @return True if value should be treated as an attchment. */ public boolean isAttachment(Object value); /** Use the default attatchment send type. */ public final int SEND_TYPE_NOTSET = 1; /** Use the SOAP with MIME attatchment send type. */ public final int SEND_TYPE_MIME = 2; //use mime /** Use the DIME attatchment type. */ public final int SEND_TYPE_DIME= 3; //use dime; /** Use the MTOM attatchment type. */ public final int SEND_TYPE_MTOM= 4; //use MTOM; /** Use the DIME attatchment type. */ public final int SEND_TYPE_NONE= 5; //don't send as attachments final int SEND_TYPE_MAX = 5; /** The default attatchment type. MIME */ final int SEND_TYPE_DEFAULT = SEND_TYPE_MIME; /** The prefix used to assoc. attachments as content-id */ public final String CIDprefix= "cid:"; /** * Set the format for attachments. * * @param sendtype the format to send. * SEND_TYPE_MIME for Multipart Releated Mail type attachments. * SEND_TYPE_DIME for DIME type attachments. */ public void setSendType( int sendtype); /** * Determine if an object is to be treated as an attchment. * * * @return SEND_TYPE_MIME, SEND_TYPE_DIME, SEND_TYPE_NOTSET */ public int getSendType(); /** * dispose of the attachments and their files; do not use the object * after making this call. */ public void dispose(); /** * Once this method is called, attachments can only be accessed via the InputStreams. * Any other access to the attachments collection (e.g. via getAttachments()) is * prohibited and will cause a ConcurrentModificationException to be thrown. * @return All of the attachment streams. */ public IncomingAttachmentStreams getIncomingAttachmentStreams(); }
7,787
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DynamicContentDataHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.attachments; import java.net.URL; import javax.activation.DataHandler; import javax.activation.DataSource; /** * To be used with writing out DIME Attachments. * * AXIS will use DIME record chunking. * * @author Marc Dumontier (mrdumont@blueprint.org) * */ public class DynamicContentDataHandler extends DataHandler { int chunkSize = 1*1024*1024; /** * @param arg0 */ public DynamicContentDataHandler(DataSource arg0) { super(arg0); } /** * @param arg0 * @param arg1 */ public DynamicContentDataHandler(Object arg0, String arg1) { super(arg0, arg1); } /** * @param arg0 */ public DynamicContentDataHandler(URL arg0) { super(arg0); } /** * Get the DIME record chunk size * @return The value */ public int getChunkSize() { return chunkSize; } /** * Set the DIME record chunk size * @param chunkSize The value. */ public void setChunkSize(int chunkSize) { this.chunkSize = chunkSize; } }
7,788
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/attachments/DimeTypeNameFormat.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Rick Rineholt */ package org.apache.axis.attachments; import org.apache.axis.utils.Messages; /** * This class is a single part for DIME mulitpart message. */ public final class DimeTypeNameFormat { private byte format = 0; private DimeTypeNameFormat() {} private DimeTypeNameFormat(byte f) { format = f; } //Current type values. static final byte NOCHANGE_VALUE = 0x00; // indicates the type is unchanged from the previous record (used for chunking) static final byte MIME_VALUE = 0x01; //indicates the type is specified as a MIME media-type static final byte URI_VALUE = 0x02; // indicates the type is specified as an absolute URI static final byte UNKNOWN_VALUE = 0x03; // indicates the type is not specified static final byte NODATA_VALUE = 0x04; // indicates the record has no payload static final DimeTypeNameFormat NOCHANGE = new DimeTypeNameFormat(NOCHANGE_VALUE); public static final DimeTypeNameFormat MIME= new DimeTypeNameFormat(MIME_VALUE); public static final DimeTypeNameFormat URI= new DimeTypeNameFormat(URI_VALUE); public static final DimeTypeNameFormat UNKNOWN= new DimeTypeNameFormat(UNKNOWN_VALUE); static final DimeTypeNameFormat NODATA= new DimeTypeNameFormat(NODATA_VALUE); private static String[] toEnglish = {"NOCHANGE", "MIME", "URI", "UNKNOWN", "NODATA"}; private static DimeTypeNameFormat[] fromByte = {NOCHANGE, MIME, URI, UNKNOWN, NODATA}; public final String toString() { return toEnglish[format]; } public final byte toByte() { return format; } public int hashCode() { return (int) format; } public final boolean equals(final Object x) { if (x == null) { return false; } if (!(x instanceof DimeTypeNameFormat)) { return false; } return ((DimeTypeNameFormat) x).format == this.format; } public static DimeTypeNameFormat parseByte(byte x) { if (x < 0 || x > fromByte.length) { throw new IllegalArgumentException(Messages.getMessage( "attach.DimeStreamBadType", "" + x)); } return fromByte[x]; } public static DimeTypeNameFormat parseByte(Byte x) { return parseByte(x.byteValue()); } }
7,789
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/Stub.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import org.apache.axis.AxisFault; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.utils.Messages; import javax.xml.namespace.QName; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.Service; import javax.xml.rpc.ServiceException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Properties; import java.util.Vector; /** * This class is the base for all generated stubs. */ public abstract class Stub implements javax.xml.rpc.Stub { protected Service service = null; // If maintainSessionSet is true, then setMaintainSession // was called and it set the value of maintainSession. // Use that value when getting the new Call object. // If maintainSession HAS NOT been set, then the // Call object uses the default maintainSession // from the Service. protected boolean maintainSessionSet = false; protected boolean maintainSession = false; protected Properties cachedProperties = new Properties(); protected String cachedUsername = null; protected String cachedPassword = null; protected URL cachedEndpoint = null; protected Integer cachedTimeout = null; protected QName cachedPortName = null; // Support for Header private Vector headers = new Vector(); // Support for Attachments private Vector attachments = new Vector(); // Flag to determine whether this is the first call to register type mappings. // This need not be synchronized because firstCall is ONLY called from within // a synchronized block in the generated stub code. private boolean firstCall = true; // The last call object protected Call _call = null; /** * Is this the first time the type mappings are being registered? */ protected boolean firstCall() { boolean ret = firstCall; firstCall = false; return ret; } // firstCall /** * Sets the value for a named property. JAX-RPC 1.0 specification * specifies a standard set of properties that may be passed * to the Stub._setProperty method. These properties include: * <UL> * <LI>javax.xml.rpc.security.auth.username: Username for the HTTP Basic Authentication * <LI>javax.xml.rpc.security.auth.password: Password for the HTTP Basic Authentication * <LI>javax.xml.rpc.service.endpoint.address: Target service endpoint address. * <LI>[TBD: Additional properties] * </UL> * * @param name - Name of the property * @param value - Value of the property */ public void _setProperty(String name, Object value) { if (name == null || value == null) { throw new JAXRPCException( Messages.getMessage(name == null ? "badProp03" : "badProp04")); } else if (name.equals(Call.USERNAME_PROPERTY)) { if (!(value instanceof String)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] { name, "java.lang.String", value.getClass().getName()})); } cachedUsername = (String) value; } else if (name.equals(Call.PASSWORD_PROPERTY)) { if (!(value instanceof String)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] { name, "java.lang.String", value.getClass().getName()})); } cachedPassword = (String) value; } else if (name.equals(Stub.ENDPOINT_ADDRESS_PROPERTY)) { if (!(value instanceof String)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] { name, "java.lang.String", value.getClass().getName()})); } try { cachedEndpoint = new URL ((String) value); } catch (MalformedURLException mue) { throw new JAXRPCException(mue.getMessage()); } } else if (name.equals(Call.SESSION_MAINTAIN_PROPERTY)) { if (!(value instanceof Boolean)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] {name, "java.lang.Boolean", value.getClass().getName()})); } maintainSessionSet = true; maintainSession = ((Boolean) value).booleanValue(); } else if (name.startsWith("java.") || name.startsWith("javax.")) { throw new JAXRPCException( Messages.getMessage("badProp05", name)); } else { cachedProperties.put(name, value); } } // _setProperty /** * Gets the value of a named property. * * @param name * * @return the value of a named property. */ public Object _getProperty(String name) { if (name == null) { throw new JAXRPCException( Messages.getMessage("badProp05", name)); } else { if (name.equals(Call.USERNAME_PROPERTY)) { return cachedUsername; } else if (name.equals(Call.PASSWORD_PROPERTY)) { return cachedPassword; } else if (name.equals(Stub.ENDPOINT_ADDRESS_PROPERTY)) { return cachedEndpoint.toString(); } else if (name.equals(Call.SESSION_MAINTAIN_PROPERTY)) { return maintainSessionSet ? (maintainSession ? Boolean.TRUE : Boolean.FALSE) : null; } else if (name.startsWith("java.") || name.startsWith("javax.")) { throw new JAXRPCException( Messages.getMessage("badProp05", name)); } else { return cachedProperties.get(name); } } } // _getProperty /** * Remove a property from this instance of the Stub * NOTE: This is NOT part of JAX-RPC and is an Axis extension. * * @param name the name of the property to remove * @return the value to which the key had been mapped, or null if the key did not have a mapping. */ public Object removeProperty(String name) { return cachedProperties.remove(name); } /** * Return the names of configurable properties for this stub class. */ public Iterator _getPropertyNames() { return cachedProperties.keySet().iterator(); } // _getPropertyNames /** * Set the username. */ public void setUsername(String username) { cachedUsername = username; } // setUsername /** * Get the user name */ public String getUsername() { return cachedUsername; } // getUsername /** * Set the password. */ public void setPassword(String password) { cachedPassword = password; } // setPassword /** * Get the password */ public String getPassword() { return cachedPassword; } // getPassword /** * Get the timeout value in milliseconds. 0 means no timeout. */ public int getTimeout() { return cachedTimeout == null ? 0 : cachedTimeout.intValue(); } // getTimeout /** * Set the timeout in milliseconds. */ public void setTimeout(int timeout) { cachedTimeout = new Integer(timeout); } // setTimeout /** * Get the port name. */ public QName getPortName() { return cachedPortName; } // getPortName /** * Set the port QName. */ public void setPortName(QName portName) { cachedPortName = portName; } // setPortName /** * Set the port name. */ public void setPortName(String portName) { setPortName(new QName(portName)); } // setPortName /** * If set to true, session is maintained; if false, it is not. */ public void setMaintainSession(boolean session) { maintainSessionSet = true; maintainSession = session; cachedProperties.put(Call.SESSION_MAINTAIN_PROPERTY, session ? Boolean.TRUE : Boolean.FALSE); } // setmaintainSession /** * Set the header * @param namespace * @param partName that uniquely identify a header object. * @param headerValue Object that is sent in the request as a SOAPHeader */ public void setHeader(String namespace, String partName, Object headerValue) { headers.add(new SOAPHeaderElement(namespace, partName, headerValue)); } /** * Set the header */ public void setHeader(SOAPHeaderElement header) { headers.add(header); } /** * Extract attachments * @param call */ public void extractAttachments(Call call) { attachments.clear(); if(call.getResponseMessage() != null) { Iterator iterator = call.getResponseMessage().getAttachments(); while(iterator.hasNext()){ attachments.add(iterator.next()); } } } /** * Add an attachment * @param handler */ public void addAttachment(Object handler) { attachments.add(handler); } /** * Get the header element */ public SOAPHeaderElement getHeader(String namespace, String partName) { for(int i=0;i<headers.size();i++) { SOAPHeaderElement header = (SOAPHeaderElement)headers.get(i); if(header.getNamespaceURI().equals(namespace) && header.getName().equals(partName)) return header; } return null; } /** * Get a response header element */ public SOAPHeaderElement getResponseHeader(String namespace, String partName) { try { if (_call == null) return null; return _call.getResponseMessage().getSOAPEnvelope().getHeaderByName(namespace, partName); } catch (Exception e) { return null; } } /** * Get the array of header elements */ public SOAPHeaderElement[] getHeaders() { SOAPHeaderElement[] array = new SOAPHeaderElement[headers.size()]; headers.copyInto(array); return array; } /** * Get the array of response header elements */ public SOAPHeaderElement[] getResponseHeaders() { SOAPHeaderElement[] array = new SOAPHeaderElement[0]; try { if (_call == null) return array; Vector h = _call.getResponseMessage().getSOAPEnvelope().getHeaders(); array = new SOAPHeaderElement[h.size()]; h.copyInto(array); return array; } catch (Exception e) { return array; } } /** * Get the array of attachments * The attachment array is cleared after this, so it is a destructive operation. * @return the array of attachments that was in the message, or an empty array if * there were none */ public Object[] getAttachments() { Object[] array = new Object[attachments.size()]; attachments.copyInto(array); attachments.clear(); return array; } /** * This method clears both requestHeaders and responseHeaders hashtables. */ public void clearHeaders() { headers.clear(); } /** * This method clears the request attachments. */ public void clearAttachments() { attachments.clear(); } protected void setRequestHeaders(org.apache.axis.client.Call call) throws AxisFault { // Set the call headers. SOAPHeaderElement[] headers = getHeaders(); for(int i=0;i<headers.length;i++){ call.addHeader(headers[i]); } } /** * copy the attachments from the stub to the call object. After doing so, * the local set of attachments are cleared. * @param call call object to configure * @throws AxisFault */ protected void setAttachments(org.apache.axis.client.Call call) throws AxisFault { // Set the attachments. Object[] attachments = getAttachments(); for(int i=0;i<attachments.length;i++){ call.addAttachmentPart(attachments[i]); } clearAttachments(); } /** * Provide access to the service object. Not part of JAX-RPC * * @return the service object for this stub */ public Service _getService() { return service; } /** * Creates a call from the service. * @return */ public Call _createCall() throws ServiceException { // A single stub instance may be used concurrently by multiple threads; therefore we need // to return the value of the local call variable instead of reading the _call attribute. Call call = (Call) service.createCall(); _call = call; // TODO: There is a lot of code in the generated stubs that // can be moved here. return call; } /** * Returns last Call object associated with this stub. */ public Call _getCall() { return _call; } /** * Helper method for updating headers from the response. * * Deprecated, since response headers should not be * automatically reflected back into the stub list. * * * @deprecated This method has been changed to a no-op but remains * in the code to keep compatibility with pre-1.1 * generated stubs. */ protected void getResponseHeaders(org.apache.axis.client.Call call) throws AxisFault { } }
7,790
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/AxisClientProxy.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; import java.util.Vector; import javax.xml.namespace.QName; import javax.xml.rpc.holders.Holder; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.utils.JavaUtils; /** * Very simple dynamic proxy InvocationHandler class. This class is * constructed with a Call object, and then each time a method is invoked * on a dynamic proxy using this invocation handler, we simply turn it into * a SOAP request. * * @author Glen Daniels (gdaniels@apache.org) * @author C?dric Chabanois (cchabanois@ifrance.com) */ public class AxisClientProxy implements InvocationHandler { private Call call; private QName portName; /** * Constructor - package access only (should only really get used * in Service.getPort(endpoint, proxyClass). * Call can be pre-filled from wsdl */ AxisClientProxy(Call call, QName portName) { this.call = call; this.portName = portName; // can be null } /** * Map between the parameters for the method call and the parameters needed * for the <code>Call</code>. * <p> * Parameters for invoke method are not the same as parameter for Call * instance : * - Holders must be converted to their mapped java types * - only in and inout parameters must be present in call parameters * * @param proxyParams proxyParameters * @return Object[] Call parameters * @throws JavaUtils.HolderException */ private Object[] proxyParams2CallParams(Object[] proxyParams) throws JavaUtils.HolderException { OperationDesc operationDesc = call.getOperation(); if (operationDesc == null) { // we don't know which parameters are IN, OUT or INOUT // let's suppose they are all in return proxyParams; } Vector paramsCall = new Vector(); for (int i = 0; proxyParams != null && i < proxyParams.length;i++) { Object param = proxyParams[i]; ParameterDesc paramDesc = operationDesc.getParameter(i); if (paramDesc.getMode() == ParameterDesc.INOUT) { paramsCall.add(JavaUtils.getHolderValue((Holder)param)); } else if (paramDesc.getMode() == ParameterDesc.IN) { paramsCall.add(param); } } return paramsCall.toArray(); } /** * Copy in/out and out parameters (Holder parameters) back to proxyParams. * * @param proxyParams proxyParameters */ private void callOutputParams2proxyParams(Object[] proxyParams) throws JavaUtils.HolderException { OperationDesc operationDesc = call.getOperation(); if (operationDesc == null) { // we don't know which parameters are IN, OUT or INOUT // let's suppose they are all in return; } Map outputParams = call.getOutputParams(); for (int i = 0; i < operationDesc.getNumParams();i++) { Object param = proxyParams[i]; ParameterDesc paramDesc = operationDesc.getParameter(i); if ((paramDesc.getMode() == ParameterDesc.INOUT) || (paramDesc.getMode() == ParameterDesc.OUT)) { JavaUtils.setHolderValue((Holder)param, outputParams.get(paramDesc.getQName())); } } } // fixme: what is o used for? /** * Handle a method invocation. * * @param o the object to invoke relative to * @param method the <code>Method</code> to invoke * @param objects the arguments to the method * @return the result of the method * @throws Throwable if anything went wrong in method dispatching or the * execution of the method itself */ public Object invoke(Object o, Method method, Object[] objects) throws Throwable { // first see if we invoke Stub methods if (method.getName().equals("_setProperty")) { call.setProperty((String) objects[0], objects[1]); return null; } else if (method.getName().equals("_getProperty")) { return call.getProperty((String) objects[0]); } else if (method.getName().equals("_getPropertyNames")) { return call.getPropertyNames(); } else if (Object.class.equals(method.getDeclaringClass())) { // if we invoke basic Object methods : delegate to Call instance return method.invoke(call, objects); } else { Object outValue; Object[] paramsCall; if ((call.getTargetEndpointAddress() != null) && (call.getPortName() != null)) { // call object has been prefilled : targetEndPoint and portname // are already set. We complete it with method informations call.setOperation(method.getName()); paramsCall = proxyParams2CallParams(objects); outValue = call.invoke(paramsCall); } else if (portName != null) { // we only know the portName. Try to complete this information // from wsdl if available call.setOperation(portName,method.getName()); paramsCall = proxyParams2CallParams(objects); outValue = call.invoke(paramsCall); } else { // we don't even know the portName (we don't have wsdl) paramsCall = objects; outValue = call.invoke(method.getName(), paramsCall); } callOutputParams2proxyParams(objects); return outValue; } } /** * Returns the current call. * * @return the current <code>Call</code> */ public Call getCall(){ return call; } }
7,791
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/Transport.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; public class Transport { /** * Transport Chain Name - so users can change the default. */ public String transportName = null ; /** * Transport URL, if any. */ public String url = null; public final void setupMessageContext(MessageContext context, Call message, AxisEngine engine) throws AxisFault { if (url != null) context.setProperty(MessageContext.TRANS_URL, url); if (transportName != null) context.setTransportName(transportName); setupMessageContextImpl(context, message, engine); } public void setupMessageContextImpl(MessageContext context, Call message, AxisEngine engine) throws AxisFault { // Default impl does nothing } /** * Allow the transport to grab any transport-specific stuff it might * want from a returned MessageContext */ public void processReturnedMessageContext(MessageContext context) { // Default impl does nothing } /** * Sets the transport chain name - to override the default. * @param name the name of the transport chain to use */ public void setTransportName(String name) { transportName = name ; } /** * Returns the name of the transport chain to use * @return the transport chain name (or null if the default chain) */ public String getTransportName() { return( transportName ); } /** * Get the transport-specific URL */ public String getUrl() { return url; } /** * Set the transport-specific URL */ public void setUrl(String url) { this.url = url; } }
7,792
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/HappyClient.java
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import org.apache.axis.utils.Messages; import org.apache.axis.utils.ClassUtils; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; /** * Client side equivalent of happyaxis */ public class HappyClient { PrintStream out; public HappyClient(PrintStream out) { this.out = out; } /** * test for a class existing * @param classname * @return class iff present */ Class classExists(String classname) { try { return Class.forName(classname); } catch (ClassNotFoundException e) { return null; } } /** * test for resource on the classpath * @param resource * @return true iff present */ boolean resourceExists(String resource) { boolean found; InputStream instream = ClassUtils.getResourceAsStream(this.getClass(),resource); found = instream != null; if (instream != null) { try { instream.close(); } catch (IOException e) { } } return found; } /** * probe for a class, print an error message is missing * @param category text like "warning" or "error" * @param classname class to look for * @param jarFile where this class comes from * @param errorText extra error text * @param homePage where to d/l the library * @return the number of missing classes * @throws java.io.IOException */ int probeClass( String category, String classname, String jarFile, String description, String errorText, String homePage) throws IOException { String url = ""; if (homePage != null) { url=Messages.getMessage("happyClientHomepage",homePage); } String errorLine=""; if (errorText != null) { errorLine=Messages.getMessage(errorText); } try { Class clazz = classExists(classname); if (clazz == null) { String text; text=Messages.getMessage("happyClientMissingClass", category,classname,jarFile); out.println(text); out.println(url); return 1; } else { String location = getLocation(clazz); String text; if (location == null) { text=Messages.getMessage("happyClientFoundDescriptionClass", description,classname); } else { text = Messages.getMessage("happyClientFoundDescriptionClassLocation", description, classname,location); } out.println(text); return 0; } } catch (NoClassDefFoundError ncdfe) { out.println(Messages.getMessage("happyClientNoDependency", category, classname, jarFile)); out.println(errorLine); out.println(url); out.println(ncdfe.getMessage()); return 1; } } /** * get the location of a class * @param clazz * @return the jar file or path where a class was found */ String getLocation( Class clazz) { try { java.net.URL url = clazz.getProtectionDomain().getCodeSource().getLocation(); String location = url.toString(); if (location.startsWith("jar")) { url = ((java.net.JarURLConnection) url.openConnection()).getJarFileURL(); location = url.toString(); } if (location.startsWith("file")) { java.io.File file = new java.io.File(url.getFile()); return file.getAbsolutePath(); } else { return url.toString(); } } catch (Throwable t) { } return Messages.getMessage("happyClientUnknownLocation"); } /** * a class we need if a class is missing * @param classname class to look for * @param jarFile where this class comes from * @param errorText extra error text * @param homePage where to d/l the library * @throws java.io.IOException when needed * @return the number of missing libraries (0 or 1) */ int needClass( String classname, String jarFile, String description, String errorText, String homePage) throws IOException { return probeClass( Messages.getMessage("happyClientError"), classname, jarFile, description, errorText, homePage); } /** * print warning message if a class is missing * @param classname class to look for * @param jarFile where this class comes from * @param errorText extra error text * @param homePage where to d/l the library * @throws java.io.IOException when needed * @return the number of missing libraries (0 or 1) */ int wantClass( String classname, String jarFile, String description, String errorText, String homePage) throws IOException { return probeClass( Messages.getMessage("happyClientWarning"), classname, jarFile, description, errorText, homePage); } /** * probe for a resource existing, * @param resource * @param errorText * @throws Exception */ int wantResource( String resource, String errorText) throws Exception { if (!resourceExists(resource)) { out.println(Messages.getMessage("happyClientNoResource",resource)); out.println(errorText); return 0; } else { out.println(Messages.getMessage("happyClientFoundResource", resource)); return 1; } } /** * what parser are we using. * @return the classname of the parser */ private String getParserName() { SAXParser saxParser = getSAXParser(); if (saxParser == null) { return Messages.getMessage("happyClientNoParser"); } // check to what is in the classname String saxParserName = saxParser.getClass().getName(); return saxParserName; } /** * Create a JAXP SAXParser * @return parser or null for trouble */ private SAXParser getSAXParser() { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); if (saxParserFactory == null) { return null; } SAXParser saxParser = null; try { saxParser = saxParserFactory.newSAXParser(); } catch (Exception e) { } return saxParser; } /** * get the location of the parser * @return path or null for trouble in tracking it down */ private String getParserLocation() { SAXParser saxParser = getSAXParser(); if (saxParser == null) { return null; } String location = getLocation(saxParser.getClass()); return location; } /** * calculate the java version number by probing for classes; * this tactic works across many jvm implementations; taken from Ant. * @return JRE version as 10,11,12,13,14,... */ public int getJavaVersionNumber() { // Determine the Java version by looking at available classes // java.lang.CharSequence was introduced in JDK 1.4 // java.lang.StrictMath was introduced in JDK 1.3 // java.lang.ThreadLocal was introduced in JDK 1.2 // java.lang.Void was introduced in JDK 1.1 // Count up version until a NoClassDefFoundError ends the try int javaVersionNumber=10; try { Class.forName("java.lang.Void"); javaVersionNumber++; Class.forName("java.lang.ThreadLocal"); javaVersionNumber++; Class.forName("java.lang.StrictMath"); javaVersionNumber++; Class.forName("java.lang.CharSequence"); javaVersionNumber++; } catch (Throwable t) { // swallow as we've hit the max class version that // we have } return javaVersionNumber; } private void title(String title) { out.println(); String message=Messages.getMessage(title); out.println(message); //subtitle for(int i=0;i< message.length();i++) { out.print("="); } out.println(); } /** * Audit the client, print out status * @param warningsAsErrors should any warning result in failure? * @return true if we are happy * @throws IOException */ public boolean verifyClientIsHappy(boolean warningsAsErrors) throws IOException { int needed = 0,wanted = 0; out.println(); title("happyClientTitle"); title("happyClientNeeded"); /** * the essentials, without these Axis is not going to work */ needed = needClass("javax.xml.soap.SOAPMessage", "saaj.jar", "SAAJ", "happyClientNoAxis", "http://xml.apache.org/axis/"); needed += needClass("javax.xml.rpc.Service", "jaxrpc.jar", "JAX-RPC", "happyClientNoAxis", "http://xml.apache.org/axis/"); needed += needClass("org.apache.commons.discovery.Resource", "commons-discovery.jar", "Jakarta-Commons Discovery", "happyClientNoAxis", "http://jakarta.apache.org/commons/discovery.html"); needed += needClass("org.apache.commons.logging.Log", "commons-logging.jar", "Jakarta-Commons Logging", "happyClientNoAxis", "http://jakarta.apache.org/commons/logging.html"); //all refs to log4j are split to get past the package tester needed += needClass("org.apache" + ".log" +"4j" +".Layout", "log4"+"j-1.2.4.jar", "Log4"+"j", "happyClientNoLog4J", "http://jakarta.apache.org/log"+"4j"); //should we search for a javax.wsdl file here, to hint that it needs //to go into an approved directory? because we dont seem to need to do that. needed += needClass("com.ibm.wsdl.factory.WSDLFactoryImpl", "wsdl4j.jar", "WSDL4Java", "happyClientNoAxis", null); needed += needClass("javax.xml.parsers.SAXParserFactory", "xerces.jar", "JAXP", "happyClientNoAxis", "http://xml.apache.org/xerces-j/"); title("happyClientOptional"); wanted += wantClass("javax.mail.internet.MimeMessage", "mail.jar", "Mail", "happyClientNoAttachments", "http://java.sun.com/products/javamail/"); wanted += wantClass("javax.activation.DataHandler", "activation.jar", "Activation", "happyClientNoAttachments", "http://java.sun.com/products/javabeans/glasgow/jaf.html"); wanted += wantClass("org.apache.xml.security.Init", "xmlsec.jar", "XML Security", "happyClientNoSecurity", "http://xml.apache.org/security/"); wanted += wantClass("javax.net.ssl.SSLSocketFactory", Messages.getMessage("happyClientJSSEsources"), "Java Secure Socket Extension", "happyClientNoHTTPS", "http://java.sun.com/products/jsse/"); /* * resources on the classpath path */ int warningMessages=0; String xmlParser = getParserName(); String xmlParserLocation = getParserLocation(); out.println(Messages.getMessage("happyClientXMLinfo", xmlParser,xmlParserLocation)); if (xmlParser.indexOf("xerces") <= 0) { warningMessages++; out.println(); out.println(Messages.getMessage("happyClientRecommendXerces")); } if (getJavaVersionNumber() < 13) { warningMessages++; out.println(); out.println(Messages.getMessage("happyClientUnsupportedJVM")); } /* add more libraries here */ //print the summary information boolean happy; title("happyClientSummary"); //is everythng we need here if (needed == 0) { //yes, be happy out.println(Messages.getMessage("happyClientCorePresent")); happy=true; } else { happy=false; //no, be very unhappy out.println(Messages.getMessage("happyClientCoreMissing", Integer.toString(needed))); } //now look at wanted stuff if (wanted > 0) { out.println(); out.println(Messages.getMessage("happyClientOptionalMissing", Integer.toString(wanted))); out.println(Messages.getMessage("happyClientOptionalOK")); if (warningsAsErrors) { happy = false; } } else { out.println(Messages.getMessage("happyClientOptionalPresent")); } if (warningMessages > 0) { out.println(Messages.getMessage("happyClientWarningMessageCount", Integer.toString(warningMessages))); if (warningsAsErrors) { happy = false; } } return happy; } /** * public happiness test. Exits with -1 if the client is unhappy. * @param args a list of extra classes to look for * */ public static void main(String args[]) { boolean isHappy = isClientHappy(args); System.exit(isHappy?0:-1); } /** * this is the implementation of the happiness test. * @param args a list of extra classes to look for * @return true iff we are happy: all needed ant all argument classes * found */ private static boolean isClientHappy(String[] args) { HappyClient happy=new HappyClient(System.out); boolean isHappy; int missing=0; try { isHappy = happy.verifyClientIsHappy(false); for(int i=0;i<args.length;i++) { missing+=happy.probeClass( "argument", args[i], null, null, null, null ); } if(missing>0) { isHappy=false; } } catch (IOException e) { e.printStackTrace(); isHappy=false; } return isHappy; } }
7,793
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/ServiceFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import org.apache.axis.EngineConfiguration; import org.apache.axis.configuration.EngineConfigurationFactoryFinder; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.spi.ObjectFactory; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import java.lang.reflect.Constructor; import java.net.URL; import java.util.Hashtable; import java.util.Map; import java.util.Properties; /** * Helper class for obtaining Services from JNDI. * * !!! WORK IN PROGRESS * * @author Glen Daniels (gdaniels@apache.org) */ public class ServiceFactory extends javax.xml.rpc.ServiceFactory implements ObjectFactory { // Constants for RefAddrs in the Reference. public static final String SERVICE_CLASSNAME = "service classname"; public static final String WSDL_LOCATION = "WSDL location"; public static final String MAINTAIN_SESSION = "maintain session"; public static final String SERVICE_NAMESPACE = "service namespace"; public static final String SERVICE_LOCAL_PART = "service local part"; public static final String SERVICE_IMPLEMENTATION_NAME_PROPERTY = "serviceImplementationName"; private static final String SERVICE_IMPLEMENTATION_SUFFIX = "Locator"; private static EngineConfiguration _defaultEngineConfig = null; private static ThreadLocal threadDefaultConfig = new ThreadLocal(); public static void setThreadDefaultConfig(EngineConfiguration config) { threadDefaultConfig.set(config); } private static EngineConfiguration getDefaultEngineConfig() { if (_defaultEngineConfig == null) { _defaultEngineConfig = EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig(); } return _defaultEngineConfig; } /** * Obtain an AxisClient reference, using JNDI if possible, otherwise * creating one using the standard Axis configuration pattern. If we * end up creating one and do have JNDI access, bind it to the passed * name so we find it next time. * * @param environment * @return a service */ public static Service getService(Map environment) { Service service = null; InitialContext context = null; EngineConfiguration configProvider = (EngineConfiguration)environment.get(EngineConfiguration.PROPERTY_NAME); if (configProvider == null) configProvider = (EngineConfiguration)threadDefaultConfig.get(); if (configProvider == null) configProvider = getDefaultEngineConfig(); // First check to see if JNDI works // !!! Might we need to set up context parameters here? try { context = new InitialContext(); } catch (NamingException e) { } if (context != null) { String name = (String)environment.get("jndiName"); if(name!=null && (name.toUpperCase().indexOf("LDAP")!=-1 || name.toUpperCase().indexOf("RMI")!=-1 || name.toUpperCase().indexOf("JMS")!=-1 || name.toUpperCase().indexOf("JMX")!=-1) || name.toUpperCase().indexOf("JRMP")!=-1 || name.toUpperCase().indexOf("JAVA")!=-1 || name.toUpperCase().indexOf("DNS")!=-1) { return null; } if (name == null) { name = "axisServiceName"; } // We've got JNDI, so try to find an AxisClient at the // specified name. try { service = (Service)context.lookup(name); } catch (NamingException e) { service = new Service(configProvider); try { context.bind(name, service); } catch (NamingException e1) { // !!! Couldn't do it, what should we do here? return null; } } } else { service = new Service(configProvider); } return service; } public Object getObjectInstance(Object refObject, Name name, Context nameCtx, Hashtable environment) throws Exception { Object instance = null; if (refObject instanceof Reference) { Reference ref = (Reference) refObject; RefAddr addr = ref.get(SERVICE_CLASSNAME); Object obj = null; // If an explicit service classname is provided, then this is a // generated Service class. Just use its default constructor. if (addr != null && (obj = addr.getContent()) instanceof String) { instance = ClassUtils.forName((String) obj).newInstance(); } // else this is an instance of the Service class, so grab the // reference data... else { // Get the WSDL location... addr = ref.get(WSDL_LOCATION); if (addr != null && (obj = addr.getContent()) instanceof String) { URL wsdlLocation = new URL((String) obj); // Build the service qname... addr = ref.get(SERVICE_NAMESPACE); if (addr != null && (obj = addr.getContent()) instanceof String) { String namespace = (String) obj; addr = ref.get(SERVICE_LOCAL_PART); if (addr != null && (obj = addr.getContent()) instanceof String) { String localPart = (String) obj; QName serviceName = new QName(namespace, localPart); // Construct an instance of the service Class[] formalArgs = new Class[] {URL.class, QName.class}; Object[] actualArgs = new Object[] {wsdlLocation, serviceName}; Constructor ctor = Service.class.getDeclaredConstructor( formalArgs); instance = ctor.newInstance(actualArgs); } } } } // If maintainSession should be set to true, there will be an // addr for it. addr = ref.get(MAINTAIN_SESSION); if (addr != null && instance instanceof Service) { ((Service) instance).setMaintainSession(true); } } return instance; } // getObjectInstance /** * Create a Service instance. * @param wsdlDocumentLocation URL for the WSDL document location for the service * @param serviceName QName for the service. * @return Service. * @throws ServiceException If any error in creation of the specified service */ public javax.xml.rpc.Service createService(URL wsdlDocumentLocation, QName serviceName) throws ServiceException { return new Service(wsdlDocumentLocation, serviceName); } // createService /** * Create a Service instance. Since the WSDL file is not provided * here, the Service object returned is quite simpleminded. * Likewise, the Call object that service.createCall will return * will also be simpleminded. The caller must explicitly fill in * all the info on the Call object (ie., endpoint address, etc.). * * @param serviceName QName for the service * @return Service. * @throws ServiceException If any error in creation of the specified service */ public javax.xml.rpc.Service createService(QName serviceName) throws ServiceException { return new Service(serviceName); } // createService /** * Create an instance of the generated service implementation class * for a given service interface, if available. * * @param serviceInterface Service interface * @return Service. * @throws ServiceException If there is any error while creating the specified service, * including the case where a generated service implementation class cannot be located */ public javax.xml.rpc.Service loadService(Class serviceInterface) throws ServiceException { if (serviceInterface == null) { throw new IllegalArgumentException( Messages.getMessage("serviceFactoryIllegalServiceInterface")); } if (!(javax.xml.rpc.Service.class).isAssignableFrom(serviceInterface)) { throw new ServiceException( Messages.getMessage("serviceFactoryServiceInterfaceRequirement", serviceInterface.getName())); } else { String serviceImplementationName = serviceInterface.getName() + SERVICE_IMPLEMENTATION_SUFFIX; Service service = createService(serviceImplementationName); return service; } } /** * Create an instance of the generated service implementation class * for a given service interface, if available. * An implementation may use the provided wsdlDocumentLocation and properties * to help locate the generated implementation class. * If no such class is present, a ServiceException will be thrown. * * @param wsdlDocumentLocation URL for the WSDL document location for the service or null * @param serviceInterface Service interface * @param properties A set of implementation-specific properties * to help locate the generated service implementation class * @return Service. * @throws ServiceException If there is any error while creating the specified service, * including the case where a generated service implementation class cannot be located */ public javax.xml.rpc.Service loadService(URL wsdlDocumentLocation, Class serviceInterface, Properties properties) throws ServiceException { if (serviceInterface == null) { throw new IllegalArgumentException( Messages.getMessage("serviceFactoryIllegalServiceInterface")); } if (!(javax.xml.rpc.Service.class).isAssignableFrom(serviceInterface)) { throw new ServiceException( Messages.getMessage("serviceFactoryServiceInterfaceRequirement", serviceInterface.getName())); } else { String serviceImplementationName = serviceInterface.getName() + SERVICE_IMPLEMENTATION_SUFFIX; Service service = createService(serviceImplementationName); return service; } } /** * Create an instance of the generated service implementation class * for a given service, if available. * The service is uniquely identified by the wsdlDocumentLocation and serviceName arguments. * An implementation may use the provided properties to help locate the generated implementation class. * If no such class is present, a ServiceException will be thrown. * * @param wsdlDocumentLocation URL for the WSDL document location for the service or null * @param serviceName Qualified name for the service * @param properties A set of implementation-specific properties * to help locate the generated service implementation class * @return Service. * @throws ServiceException If there is any error while creating the specified service, * including the case where a generated service implementation class cannot be located */ public javax.xml.rpc.Service loadService(URL wsdlDocumentLocation, QName serviceName, Properties properties) throws ServiceException { String serviceImplementationName = properties.getProperty(SERVICE_IMPLEMENTATION_NAME_PROPERTY); javax.xml.rpc.Service service = createService(serviceImplementationName); if (service.getServiceName().equals(serviceName)) { return service; } else { throw new ServiceException( Messages.getMessage("serviceFactoryServiceImplementationNotFound", serviceImplementationName)); } } private Service createService(String serviceImplementationName) throws ServiceException { if(serviceImplementationName == null) { throw new IllegalArgumentException(Messages.getMessage("serviceFactoryInvalidServiceName")); } try { Class serviceImplementationClass; serviceImplementationClass = Thread.currentThread().getContextClassLoader().loadClass(serviceImplementationName); if (!(org.apache.axis.client.Service.class).isAssignableFrom(serviceImplementationClass)) { throw new ServiceException( Messages.getMessage("serviceFactoryServiceImplementationRequirement", serviceImplementationName)); } Service service = (Service) serviceImplementationClass.newInstance(); if (service.getServiceName() != null) { return service; } else { throw new ServiceException(Messages.getMessage("serviceFactoryInvalidServiceName")); } } catch (ServiceException e) { throw e; } catch (Exception e){ throw new ServiceException(e); } } }
7,794
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/AxisClient.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client ; import javax.xml.namespace.QName; import javax.xml.rpc.handler.HandlerChain; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.configuration.EngineConfigurationFactoryFinder; import org.apache.axis.handlers.HandlerInfoChainFactory; import org.apache.axis.handlers.soap.MustUnderstandChecker; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * Provides the equivalent of an "Axis engine" on the client side. * Subclasses hardcode initialization &amp; setup logic for particular * client-side transports. * * @author Rob Jellinghaus (robj@unrealities.com) * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@allaire.com) */ public class AxisClient extends AxisEngine { protected static Log log = LogFactory.getLog(AxisClient.class.getName()); MustUnderstandChecker checker = new MustUnderstandChecker(null); public AxisClient(EngineConfiguration config) { super(config); } public AxisClient() { this(EngineConfigurationFactoryFinder.newFactory(). getClientEngineConfig()); } /** * @return this instance, as this is the client engine */ public AxisEngine getClientEngine () { return this; } /** * Main routine of the AXIS engine. In short we locate the appropriate * handler for the desired service and invoke() it. * * @param msgContext the <code>MessageContext</code> to invoke relative * to * @throws AxisFault if anything goes wrong during invocation */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: AxisClient::invoke"); } String hName = null; Handler h = null; HandlerChain handlerImpl = null; // save previous context MessageContext previousContext = getCurrentMessageContext(); try { // set active context setCurrentMessageContext(msgContext); hName = msgContext.getStrProp(MessageContext.ENGINE_HANDLER); if (log.isDebugEnabled()) { log.debug("EngineHandler: " + hName); } if (hName != null) { h = getHandler(hName); if (h != null) h.invoke(msgContext); else throw new AxisFault("Client.error", Messages.getMessage("noHandler00", hName), null, null); } else { /* Now we do the 'real' work. The flow is basically: */ /* */ /* Service Specific Request Chain */ /* Global Request Chain */ /* Transport Request Chain - must have a send at the end */ /* Transport Response Chain */ /* Global Response Chain */ /* Service Specific Response Chain */ /* Protocol Specific-Handler/Checker */ /**************************************************************/ SOAPService service = null; msgContext.setPastPivot(false); /* Process the Service Specific Request Chain */ /**********************************************/ service = msgContext.getService(); if (service != null) { h = service.getRequestHandler(); if (h != null) h.invoke(msgContext); } /* Process the Global Request Chain */ /**********************************/ if ((h = getGlobalRequest()) != null) h.invoke(msgContext); /* Process the JAX-RPC Handlers - handleRequest. * Make sure to set the pastPivot to true if this returns a * false. In that case we do not invoke the transport request * chain. Also note that if a a false was returned from the * JAX-RPC handler chain, then the chain still holds the index * of the handler that returned false. So when we invoke the * handleResponse method of the chain, it will correctly call * the handleResponse from that specific handler instance. So * do not destroy the chain at this point - the chain will be * destroyed in the finally block. */ handlerImpl = getJAXRPChandlerChain(msgContext); if (handlerImpl != null) { try { if (!handlerImpl.handleRequest(msgContext)) { msgContext.setPastPivot(true); } } catch (RuntimeException re) { handlerImpl.destroy(); // WS4EE 1.1 6.2.2.1 Handler Life Cycle. "RuntimeException" --> destroy handler throw re; } } /** Process the Transport Specific stuff * * NOTE: Somewhere in here there is a handler which actually * sends the message and receives a response. Generally * this is the pivot point in the Transport chain. But invoke * this only if pivot point has not been set to false. This * can be set to false if any of the JAX-RPC handler's * handleRequest returned false. */ if (!msgContext.getPastPivot()) { hName = msgContext.getTransportName(); if (hName != null && (h = getTransport(hName)) != null) { try { h.invoke(msgContext); } catch (AxisFault e) { throw e; } } else { throw new AxisFault(Messages.getMessage("noTransport00", hName)); } } msgContext.setPastPivot(true); if (!msgContext.isPropertyTrue(Call.ONE_WAY)) { if ((handlerImpl != null) && !msgContext.isPropertyTrue(Call.ONE_WAY)) { try { handlerImpl.handleResponse(msgContext); } catch (RuntimeException ex) { handlerImpl.destroy(); // WS4EE 1.1 6.2.2.1 Handler Life Cycle. "RuntimeException" --> destroy handler throw ex; } } /* Process the Global Response Chain */ /***********************************/ if ((h = getGlobalResponse()) != null) { h.invoke(msgContext); } /* Process the Service-Specific Response Chain */ /***********************************************/ if (service != null) { h = service.getResponseHandler(); if (h != null) { h.invoke(msgContext); } } // Do SOAP Semantics checks here - this needs to be a call // to a pluggable object/handler/something if (msgContext.isPropertyTrue(Call.CHECK_MUST_UNDERSTAND, true)) { checker.invoke(msgContext); } } } } catch (Exception e) { // Should we even bother catching it ? if (e instanceof AxisFault) { throw (AxisFault) e; } else { log.debug(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } } finally { if (handlerImpl != null) { handlerImpl.destroy(); } // restore previous state setCurrentMessageContext(previousContext); } if (log.isDebugEnabled()) { log.debug("Exit: AxisClient::invoke"); } } /** * @param context Stores the Service, port QName and optionnaly a HandlerInfoChainFactory * @return Returns a HandlerChain if one has been specified */ protected HandlerChain getJAXRPChandlerChain(MessageContext context) { java.util.List chain = null; HandlerInfoChainFactory hiChainFactory = null; boolean clientSpecified = false; Service service = (Service) context.getProperty(Call.WSDL_SERVICE); if(service == null) { return null; } QName portName = (QName) context.getProperty(Call.WSDL_PORT_NAME); if(portName == null) { return null; } javax.xml.rpc.handler.HandlerRegistry registry; registry = service.getHandlerRegistry(); if(registry != null) { chain = registry.getHandlerChain(portName); if ((chain != null) && (!chain.isEmpty())) { hiChainFactory = new HandlerInfoChainFactory(chain); clientSpecified = true; } } // Otherwise, use the container support if (!clientSpecified) { SOAPService soapService = context.getService(); if (soapService != null) { // A client configuration exists for this service. Check // to see if there is a HandlerInfoChain configured on it. hiChainFactory = (HandlerInfoChainFactory) soapService.getOption(Constants.ATTR_HANDLERINFOCHAIN); } } if (hiChainFactory == null) { return null; } return hiChainFactory.createHandlerChain(); } }
7,795
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/Call.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client ; import org.apache.axis.AxisFault; import org.apache.axis.AxisProperties; import org.apache.axis.Constants; import org.apache.axis.Handler; import org.apache.axis.InternalException; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.AxisEngine; import org.apache.axis.SOAPPart; import org.apache.axis.attachments.Attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.FaultDesc; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.encoding.DeserializerFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SerializerFactory; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.XMLType; import org.apache.axis.encoding.ser.BaseDeserializerFactory; import org.apache.axis.encoding.ser.BaseSerializerFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.message.RPCElement; import org.apache.axis.message.RPCHeaderParam; import org.apache.axis.message.RPCParam; import org.apache.axis.message.SOAPBodyElement; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPFault; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.transport.http.HTTPTransport; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.LockableHashtable; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.Utils; import org.apache.commons.logging.Log; import javax.wsdl.Binding; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.Operation; import javax.wsdl.extensions.mime.MIMEPart; import javax.wsdl.extensions.mime.MIMEMultipartRelated; import javax.wsdl.Part; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.extensions.soap.SOAPAddress; import javax.wsdl.extensions.soap.SOAPBody; import javax.wsdl.extensions.soap.SOAPOperation; import javax.xml.namespace.QName; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.ParameterMode; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import java.rmi.RemoteException; /** * Axis' JAXRPC Dynamic Invocation Interface implementation of the Call * interface. This class should be used to actually invoke the Web Service. * It can be prefilled by a WSDL document (on the constructor to the Service * object) or you can fill in the data yourself. * <pre> * Standard properties defined by in JAX-RPC's javax..xml.rpc.Call interface: * USERNAME_PROPERTY - User name for authentication * PASSWORD_PROPERTY - Password for authentication * SESSION_PROPERTY - Participate in a session with the endpoint? * OPERATION_STYLE_PROPERTY - "rpc" or "document" * SOAPACTION_USE_PROPERTY - Should SOAPAction be used? * SOAPACTION_URI_PROPERTY - If SOAPAction is used, this is that action * ENCODING_STYLE_PROPERTY - Default is SOAP 1.1: "http://schemas.xmlsoap.org/soap/encoding/" * * AXIS properties: * SEND_TYPE_ATTR - Should we send the XSI type attributes (true/false) * TIMEOUT - Timeout used by transport sender in milliseconds * TRANSPORT_NAME - Name of transport handler to use * ATTACHMENT_ENCAPSULATION_FORMAT- Send attachments as MIME the default, or DIME. * CHARACTER_SET_ENCODING - Character set encoding to use for request * </pre> * * @author Doug Davis (dug@us.ibm.com) * @author Steve Loughran */ public class Call implements javax.xml.rpc.Call { protected static Log log = LogFactory.getLog(Call.class.getName()); private static Log tlog = LogFactory.getLog(Constants.TIME_LOG_CATEGORY); // The enterprise category is for stuff that an enterprise product might // want to track, but in a simple environment (like the AXIS build) would // be nothing more than a nuisance. protected static Log entLog = LogFactory.getLog(Constants.ENTERPRISE_LOG_CATEGORY); private boolean parmAndRetReq = true ; private Service service = null ; private QName portName = null; private QName portTypeName = null; private QName operationName = null ; private MessageContext msgContext = null ; // Collection of properties to store and put in MessageContext at // invoke() time. Known ones are stored in actual variables for // efficiency/type-consistency. Unknown ones are in myProperties. private LockableHashtable myProperties = new LockableHashtable(); private String username = null; private String password = null; private boolean maintainSession = false; private boolean useSOAPAction = false; private String SOAPActionURI = null; private Integer timeout = null; private boolean useStreaming = false; /** Metadata for the operation associated with this Call */ private OperationDesc operation = null; /** This will be true if an OperationDesc is handed to us whole */ private boolean operationSetManually = false; // Is this a one-way call? private boolean invokeOneWay = false; private boolean isMsg = false; // Our Transport, if any private Transport transport = null ; private String transportName = null ; // A couple places to store output parameters. // As a HashMap, retrievable via QName (for getOutputParams). private HashMap outParams = null; // As a list, retrievable by index (for getOutputValues). private ArrayList outParamsList = null; // A place to store any client-specified headers private Vector myHeaders = null; public static final String SEND_TYPE_ATTR = AxisEngine.PROP_SEND_XSI; /** * This is the name of a property to set the transport of the message * * @see #setProperty */ public static final String TRANSPORT_NAME = "transport_name" ; /** * This is the character set encoding to use for the message * * @see #setProperty */ public static final String CHARACTER_SET_ENCODING = SOAPMessage.CHARACTER_SET_ENCODING; /** * This is not the name of a property that can be set with * setProperty, despite its name. */ public static final String TRANSPORT_PROPERTY= "java.protocol.handler.pkgs"; /** * this is a property set in the message context when the invocation * process begins, for the benefit of handlers */ public static final String WSDL_SERVICE = "wsdl.service"; /** * this is a property set in the message context when the invocation * process begins, for the benefit of handlers */ public static final String WSDL_PORT_NAME = "wsdl.portName"; /** * @deprecated use WSDL_SERVICE instead. */ public static final String JAXRPC_SERVICE = WSDL_SERVICE; /** * @deprecated use WSDL_PORT_NAME instead. */ public static final String JAXRPC_PORTTYPE_NAME = WSDL_PORT_NAME; /** * If this property is true, the code will throw a fault if there is no * response message from the server. Otherwise, the * invoke method will return a null. */ public static final String FAULT_ON_NO_RESPONSE = "call.FaultOnNoResponse"; /** * If this property is true, code will enforce must understand check on both * the request and the response paths. */ public static final String CHECK_MUST_UNDERSTAND = "call.CheckMustUnderstand"; /** * Property for setting attachment format. * Can be set to either DIME or MIME (default) * @see #setProperty * @see #ATTACHMENT_ENCAPSULATION_FORMAT_DIME * @see #ATTACHMENT_ENCAPSULATION_FORMAT_MIME * @see #ATTACHMENT_ENCAPSULATION_FORMAT_MTOM */ public static final String ATTACHMENT_ENCAPSULATION_FORMAT= "attachment_encapsulation_format"; /** * Property value for setting attachment format as MIME. */ public static final String ATTACHMENT_ENCAPSULATION_FORMAT_MIME= "axis.attachment.style.mime"; /** * Property value for setting attachment format as DIME. */ public static final String ATTACHMENT_ENCAPSULATION_FORMAT_DIME= "axis.attachment.style.dime"; /** * Property value for setting attachment format as DIME. */ public static final String ATTACHMENT_ENCAPSULATION_FORMAT_MTOM= "axis.attachment.style.mtom"; /** * Timeout property: should be accompanies by an integer * @see #setProperty */ public static final String CONNECTION_TIMEOUT_PROPERTY = "axis.connection.timeout"; /** * Streaming property: should be accompanied by an boolean * (i.e. NO high-fidelity recording, deserialize on the fly) * @see #setProperty */ public static final String STREAMING_PROPERTY = "axis.streaming"; /** * Internal property to indicate a one way call. * That will disable processing of response handlers. */ protected static final String ONE_WAY = "axis.one.way"; /** * A Hashtable mapping protocols (Strings) to Transports (classes) */ private static Hashtable transports = new Hashtable(); static ParameterMode [] modes = new ParameterMode [] { null, ParameterMode.IN, ParameterMode.OUT, ParameterMode.INOUT }; /** This is true when someone has called setEncodingStyle() */ private boolean encodingStyleExplicitlySet = false; /** This is true when someone has called setOperationUse() */ private boolean useExplicitlySet = false; /** * the name of a SOAP service that the call is bound to */ private SOAPService myService = null; /** * these are our attachments */ protected java.util.Vector attachmentParts = new java.util.Vector(); /** This is false when invoke() is called. */ private boolean isNeverInvoked = true; static { initialize(); } /************************************************************************/ /* Start of core JAX-RPC stuff */ /************************************************************************/ /** * Default constructor - not much else to say. * * @param service the <code>Service</code> this <code>Call</code> will * work with */ public Call(Service service) { this.service = service ; AxisEngine engine = service.getEngine(); msgContext = new MessageContext( engine ); myProperties.setParent(engine.getOptions()); maintainSession = service.getMaintainSession(); } /** * Build a call from a URL string. * * This is handy so that you don't have to manually call Call.initialize() * in order to register custom transports. In other words, whereas doing * a new URL("local:...") would fail, new Call("local:...") works because * we do the initialization of our own and any configured custom protocols. * * @param url the target endpoint URL * @exception MalformedURLException */ public Call(String url) throws MalformedURLException { this(new Service()); setTargetEndpointAddress(new URL(url)); } /** * Build a call from a URL. * * @param url the target endpoint URL */ public Call(URL url) { this(new Service()); setTargetEndpointAddress(url); } //////////////////////////// // // Properties and the shortcuts for common ones. // /** * Allows you to set a named property to the passed in value. * There are a few known properties (like username, password, etc) * that are variables in Call. The rest of the properties are * stored in a Hashtable. These common properties should be * accessed via the accessors for speed/type safety, but they may * still be obtained via this method. It's up to one of the * Handlers (or the Axis engine itself) to go looking for * one of them. * * There are various well defined properties defined in the * JAX-RPC specification and declared in the Call and Stub classes. * It is not possible to set any other properties beginning in java. or * javax. that are not in the specification. * @see javax.xml.rpc.Stub * @see javax.xml.rpc.Call * * There are other properties implemented in this class above and * beyond those of the JAX-RPC spec * Specifically, ATTACHMENT_ENCAPSULATION_FORMAT, CONNECTION_TIMEOUT_PROPERTY, * and TRANSPORT_NAME. * * It is intended that all future Axis-specific properties will begin * with axis. or apache. To ensure integration with future versions Axis, * use different prefixes for your own properties. * * Axis developers: keep this in sync with propertyNames below * @see #ATTACHMENT_ENCAPSULATION_FORMAT * @see #TRANSPORT_NAME * @see #CONNECTION_TIMEOUT_PROPERTY * @param name Name of the property * @param value Value of the property */ public void setProperty(String name, Object value) { if (name == null || value == null) { throw new JAXRPCException( Messages.getMessage(name == null ? "badProp03" : "badProp04")); } else if (name.equals(USERNAME_PROPERTY)) { verifyStringProperty(name, value); setUsername((String) value); } else if (name.equals(PASSWORD_PROPERTY)) { verifyStringProperty(name, value); setPassword((String) value); } else if (name.equals(SESSION_MAINTAIN_PROPERTY)) { verifyBooleanProperty(name, value); setMaintainSession(((Boolean) value).booleanValue()); } else if (name.equals(OPERATION_STYLE_PROPERTY)) { verifyStringProperty(name, value); setOperationStyle((String) value); if (getOperationStyle() == Style.DOCUMENT || getOperationStyle() == Style.WRAPPED) { setOperationUse(Use.LITERAL_STR); } else if (getOperationStyle() == Style.RPC) { setOperationUse(Use.ENCODED_STR); } } else if (name.equals(SOAPACTION_USE_PROPERTY)) { verifyBooleanProperty(name, value); setUseSOAPAction(((Boolean) value).booleanValue()); } else if (name.equals(SOAPACTION_URI_PROPERTY)) { verifyStringProperty(name, value); setSOAPActionURI((String) value); } else if (name.equals(ENCODINGSTYLE_URI_PROPERTY)) { verifyStringProperty(name, value); setEncodingStyle((String) value); } else if (name.equals(Stub.ENDPOINT_ADDRESS_PROPERTY)) { verifyStringProperty(name, value); setTargetEndpointAddress((String) value); } else if ( name.equals(TRANSPORT_NAME) ) { verifyStringProperty(name, value); transportName = (String) value ; if (transport != null) { transport.setTransportName((String) value); } } else if ( name.equals(ATTACHMENT_ENCAPSULATION_FORMAT) ) { verifyStringProperty(name, value); if(!value.equals(ATTACHMENT_ENCAPSULATION_FORMAT_MIME ) && !value.equals(ATTACHMENT_ENCAPSULATION_FORMAT_MTOM ) && !value.equals(ATTACHMENT_ENCAPSULATION_FORMAT_DIME )) throw new JAXRPCException( Messages.getMessage("badattachmenttypeerr", new String[] { (String) value, ATTACHMENT_ENCAPSULATION_FORMAT_MIME + " " +ATTACHMENT_ENCAPSULATION_FORMAT_MTOM + " " +ATTACHMENT_ENCAPSULATION_FORMAT_DIME })); } else if (name.equals(CONNECTION_TIMEOUT_PROPERTY)) { verifyIntegerProperty(name,value); setTimeout((Integer)value); } else if (name.equals(STREAMING_PROPERTY)) { verifyBooleanProperty(name, value); setStreaming(((Boolean) value).booleanValue()); } else if (name.equals(CHARACTER_SET_ENCODING)) { verifyStringProperty(name, value); } else if (name.startsWith("java.") || name.startsWith("javax.")) { throw new JAXRPCException( Messages.getMessage("badProp05", name)); } myProperties.put(name, value); } // setProperty /** * Verify that the type of the object is a String, and throw * an i18n-ized exception if not * @param name * @param value * @throws JAXRPCException if value is not a String */ private void verifyStringProperty(String name, Object value) { if (!(value instanceof String)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] {name, "java.lang.String", value.getClass().getName()})); } } /** * Verify that the type of the object is a Boolean, and throw * an i18n-ized exception if not * @param name * @param value * @throws JAXRPCException if value is not a Boolean */ private void verifyBooleanProperty(String name, Object value) { if (!(value instanceof Boolean)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] {name, "java.lang.Boolean", value.getClass().getName()})); } } /** * Verify that the type of the object is an Integer, and throw * an i18n-ized exception if not * @param name * @param value * @throws JAXRPCException if value is not an Integer */ private void verifyIntegerProperty(String name, Object value) { if (!(value instanceof Integer)) { throw new JAXRPCException( Messages.getMessage("badProp00", new String[] {name, "java.lang.Integer", value.getClass().getName()})); } } /** * Returns the value associated with the named property. * * @param name the name of the property * @return Object value of the property or null if the property is not set * @throws JAXRPCException if the requested property is not a supported property */ public Object getProperty(String name) { if (name == null || !isPropertySupported(name)) { throw new JAXRPCException(name == null ? Messages.getMessage("badProp03") : Messages.getMessage("badProp05", name)); } return myProperties.get(name); } // getProperty /** * Removes (if set) the named property. * * @param name name of the property to remove */ public void removeProperty(String name) { if (name == null || !isPropertySupported(name)) { throw new JAXRPCException(name == null ? Messages.getMessage("badProp03") : Messages.getMessage("badProp05", name)); } myProperties.remove(name); } // removeProperty /** * Configurable properties supported by this Call object. */ private static ArrayList propertyNames = new ArrayList(); static { propertyNames.add(USERNAME_PROPERTY); propertyNames.add(PASSWORD_PROPERTY); propertyNames.add(SESSION_MAINTAIN_PROPERTY); propertyNames.add(OPERATION_STYLE_PROPERTY); propertyNames.add(SOAPACTION_USE_PROPERTY); propertyNames.add(SOAPACTION_URI_PROPERTY); propertyNames.add(ENCODINGSTYLE_URI_PROPERTY); propertyNames.add(Stub.ENDPOINT_ADDRESS_PROPERTY); propertyNames.add(TRANSPORT_NAME); propertyNames.add(ATTACHMENT_ENCAPSULATION_FORMAT); propertyNames.add(CONNECTION_TIMEOUT_PROPERTY); propertyNames.add(CHARACTER_SET_ENCODING); } public Iterator getPropertyNames() { return propertyNames.iterator(); } public boolean isPropertySupported(String name) { return propertyNames.contains(name) || (!name.startsWith("java.") && !name.startsWith("javax.")); } /** * Set the username. * * @param username the new user name */ public void setUsername(String username) { this.username = username; } // setUsername /** * Get the user name. * * @return the user name */ public String getUsername() { return username; } // getUsername /** * Set the password. * * @param password plain-text copy of the password */ public void setPassword(String password) { this.password = password; } // setPassword /** * Get the password. * * @return a plain-text copy of the password */ public String getPassword() { return password; } // getPassword /** * Determine whether we'd like to track sessions or not. This * overrides the default setting from the service. * This just passes through the value into the MessageContext. * Note: Not part of JAX-RPC specification. * * @param yesno true if session state is desired, false if not. */ public void setMaintainSession(boolean yesno) { maintainSession = yesno; } /** * Get the value of maintainSession flag. * * @return true if session is maintained, false otherwise */ public boolean getMaintainSession() { return maintainSession; } /** * Set the operation style: "document", "rpc" * @param operationStyle string designating style */ public void setOperationStyle(String operationStyle) { Style style = Style.getStyle(operationStyle, Style.DEFAULT); setOperationStyle(style); } // setOperationStyle /** * Set the operation style * * @param operationStyle */ public void setOperationStyle(Style operationStyle) { if (operation == null) { operation = new OperationDesc(); } operation.setStyle(operationStyle); // If no one has explicitly set the use, we should track // the style. If it's non-RPC, default to LITERAL. if (!useExplicitlySet) { if (operationStyle != Style.RPC) { operation.setUse(Use.LITERAL); } } // If no one has explicitly set the encodingStyle, we should // track the style. If it's RPC, default to SOAP-ENC, otherwise // default to "". if (!encodingStyleExplicitlySet) { String encStyle = ""; if (operationStyle == Style.RPC) { // RPC style defaults to encoded, otherwise default to literal encStyle = msgContext.getSOAPConstants().getEncodingURI(); } msgContext.setEncodingStyle(encStyle); } } /** * Get the operation style. * * @return the <code>Style</code> of the operation */ public Style getOperationStyle() { if (operation != null) { return operation.getStyle(); } return Style.DEFAULT; } // getOperationStyle /** * Set the operation use: "literal", "encoded" * @param operationUse string designating use */ public void setOperationUse(String operationUse) { Use use = Use.getUse(operationUse, Use.DEFAULT); setOperationUse(use); } // setOperationUse /** * Set the operation use * @param operationUse */ public void setOperationUse(Use operationUse) { useExplicitlySet = true; if (operation == null) { operation = new OperationDesc(); } operation.setUse(operationUse); if (!encodingStyleExplicitlySet) { String encStyle = ""; if (operationUse == Use.ENCODED) { // RPC style defaults to encoded, otherwise default to literal encStyle = msgContext.getSOAPConstants().getEncodingURI(); } msgContext.setEncodingStyle(encStyle); } } /** * Get the operation use. * * @return the <code>Use</code> of the operation */ public Use getOperationUse() { if (operation != null) { return operation.getUse(); } return Use.DEFAULT; } // getOperationStyle /** * Flag to indicate if soapAction should be used. * * @param useSOAPAction true if the soapAction header is to be used to * help find the method to invoke, false otherwise */ public void setUseSOAPAction(boolean useSOAPAction) { this.useSOAPAction = useSOAPAction; } // setUseSOAPAction /** * Discover if soapAction is being used. * * @return true if it is, false otherwise */ public boolean useSOAPAction() { return useSOAPAction; } // useSOAPAction /** * Set the soapAction URI. * * @param SOAPActionURI the new SOAP action URI */ public void setSOAPActionURI(String SOAPActionURI) { useSOAPAction = true; this.SOAPActionURI = SOAPActionURI; } // setSOAPActionURI /** * Get the soapAction URI. * * @return the curretn SOAP action URI */ public String getSOAPActionURI() { return SOAPActionURI; } // getSOAPActionURI /** * Sets the encoding style to the URL passed in. * * @param namespaceURI URI of the encoding to use. */ public void setEncodingStyle(String namespaceURI) { encodingStyleExplicitlySet = true; msgContext.setEncodingStyle(namespaceURI); } /** * Returns the encoding style as a URI that should be used for the SOAP * message. * * @return String URI of the encoding style to use */ public String getEncodingStyle() { return msgContext.getEncodingStyle(); } /** * Sets the endpoint address of the target service port. This address must * correspond to the transport specified in the binding for this Call * instance. * * @param address - Endpoint address of the target service port; specified * as URI */ public void setTargetEndpointAddress(String address) { URL urlAddress; try { urlAddress = new URL(address); } catch (MalformedURLException mue) { throw new JAXRPCException(mue); } setTargetEndpointAddress(urlAddress); } /** * Sets the URL of the target Web Service. * * Note: Not part of JAX-RPC specification. * * @param address URL of the target Web Service */ public void setTargetEndpointAddress(java.net.URL address) { try { if ( address == null ) { setTransport(null); return ; } String protocol = address.getProtocol(); // Handle the case where the protocol is the same but we // just want to change the URL - if so just set the URL, // creating a new Transport object will drop all session // data - and we want that stuff to persist between invoke()s. // Technically the session data should be in the message // context so that it can be persistent across transports // as well, but for now the data is in the Transport object. //////////////////////////////////////////////////////////////// if ( this.transport != null ) { String oldAddr = this.transport.getUrl(); if ( oldAddr != null && !oldAddr.equals("") ) { URL tmpURL = new URL( oldAddr ); String oldProto = tmpURL.getProtocol(); if ( protocol.equals(oldProto) ) { this.transport.setUrl( address.toString() ); return ; } } } // Do we already have a transport for this address? Transport transport = service.getTransportForURL(address); if (transport != null) { setTransport(transport); } else { // We don't already have a transport for this address. Create one. transport = getTransportForProtocol(protocol); if (transport == null) throw new AxisFault("Call.setTargetEndpointAddress", Messages.getMessage("noTransport01", protocol), null, null); transport.setUrl(address.toString()); setTransport(transport); service.registerTransportForURL(address, transport); } } catch( Exception exp ) { log.error(Messages.getMessage("exception00"), exp); // do what? // throw new AxisFault("Call.setTargetEndpointAddress", //"Malformed URL Exception: " + e.getMessage(), null, null); } } /** * Returns the URL of the target Web Service. * * @return URL URL of the target Web Service */ public String getTargetEndpointAddress() { try { if ( transport == null ) return( null ); return( transport.getUrl() ); } catch( Exception exp ) { return( null ); } } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public boolean getStreaming() { return useStreaming; } public void setStreaming(boolean useStreaming) { this.useStreaming = useStreaming; } // // end properties code. // //////////////////////////// /** * Is the caller required to provide the parameter and return type * specification? * If true, then * addParameter and setReturnType MUST be called to provide the meta data. * If false, then * addParameter and setReturnType SHOULD NOT be called because the * Call object already has the meta data describing the * parameters and return type. If addParameter is called, the specified * parameter is added to the end of the list of parameters. */ public boolean isParameterAndReturnSpecRequired(QName operationName) { return parmAndRetReq; } // isParameterAndReturnSpecRequired /** * Adds the specified parameter to the list of parameters for the * operation associated with this Call object. * * Note: Not part of JAX-RPC specification. * * @param paramName Name that will be used for the parameter in the XML * @param xmlType XMLType of the parameter * @param parameterMode one of IN, OUT or INOUT */ public void addParameter(QName paramName, QName xmlType, ParameterMode parameterMode) { Class javaType = null; TypeMapping tm = getTypeMapping(); if (tm != null) { javaType = tm.getClassForQName(xmlType); } addParameter(paramName, xmlType, javaType, parameterMode); } /** * Adds the specified parameter to the list of parameters for the * operation associated with this Call object. * * * Note: Not part of JAX-RPC specification. * * @param paramName Name that will be used for the parameter in the XML * @param xmlType XMLType of the parameter * @param javaType The Java class of the parameter * @param parameterMode one of IN, OUT or INOUT */ public void addParameter(QName paramName, QName xmlType, Class javaType, ParameterMode parameterMode) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) operation = new OperationDesc(); ParameterDesc param = new ParameterDesc(); byte mode = ParameterDesc.IN; if (parameterMode == ParameterMode.INOUT) { mode = ParameterDesc.INOUT; param.setIsReturn(true); } else if (parameterMode == ParameterMode.OUT) { mode = ParameterDesc.OUT; param.setIsReturn(true); } param.setMode(mode); param.setQName(new QName(paramName.getNamespaceURI(),Utils.getLastLocalPart(paramName.getLocalPart()))); param.setTypeQName( xmlType ); param.setJavaType( javaType ); operation.addParameter(param); parmAndRetReq = true; } /** * Adds the specified parameter to the list of parameters for the * operation associated with this Call object. * * @param paramName Name that will be used for the parameter in the XML * @param xmlType XMLType of the parameter * @param parameterMode one of IN, OUT or INOUT */ public void addParameter(String paramName, QName xmlType, ParameterMode parameterMode) { Class javaType = null; TypeMapping tm = getTypeMapping(); if (tm != null) { javaType = tm.getClassForQName(xmlType); } addParameter(new QName("", paramName), xmlType, javaType, parameterMode); } /** * Adds a parameter type and mode for a specific operation. Note that the * client code is not required to call any addParameter and setReturnType * methods before calling the invoke method. A Call implementation class * can determine the parameter types by using the Java reflection and * configured type mapping registry. * * @param paramName - Name of the parameter * @param xmlType - XML datatype of the parameter * @param javaType - The Java class of the parameter * @param parameterMode - Mode of the parameter-whether IN, OUT or INOUT * @exception JAXRPCException - if isParameterAndReturnSpecRequired returns * false, then addParameter MAY throw * JAXRPCException....actually Axis allows * modification in such cases */ public void addParameter(String paramName, QName xmlType, Class javaType, ParameterMode parameterMode) { addParameter(new QName("", paramName), xmlType, javaType, parameterMode); } /** * Adds a parameter type as a soap:header. * * @param paramName - Name of the parameter * @param xmlType - XML datatype of the parameter * @param parameterMode - Mode of the parameter-whether IN, OUT or INOUT * @param headerMode - Mode of the header. Even if this is an INOUT * parameter, it need not be in the header in both * directions. * @throws JAXRPCException - if isParameterAndReturnSpecRequired returns * false, then addParameter MAY throw * JAXRPCException....actually Axis allows * modification in such cases */ public void addParameterAsHeader(QName paramName, QName xmlType, ParameterMode parameterMode, ParameterMode headerMode) { Class javaType = null; TypeMapping tm = getTypeMapping(); if (tm != null) { javaType = tm.getClassForQName(xmlType); } addParameterAsHeader(paramName, xmlType, javaType, parameterMode, headerMode); } /** * Adds a parameter type as a soap:header. * @param paramName - Name of the parameter * @param xmlType - XML datatype of the parameter * @param javaType - The Java class of the parameter * @param parameterMode - Mode of the parameter-whether IN, OUT or INOUT * @param headerMode - Mode of the header. Even if this is an INOUT * parameter, it need not be in the header in both * directions. * @exception JAXRPCException - if isParameterAndReturnSpecRequired returns * false, then addParameter MAY throw * JAXRPCException....actually Axis allows * modification in such cases */ public void addParameterAsHeader(QName paramName, QName xmlType, Class javaType, ParameterMode parameterMode, ParameterMode headerMode) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) operation = new OperationDesc(); ParameterDesc param = new ParameterDesc(); param.setQName(new QName(paramName.getNamespaceURI(),Utils.getLastLocalPart(paramName.getLocalPart()))); param.setTypeQName(xmlType); param.setJavaType(javaType); if (parameterMode == ParameterMode.IN) { param.setMode(ParameterDesc.IN); } else if (parameterMode == ParameterMode.INOUT) { param.setMode(ParameterDesc.INOUT); } else if (parameterMode == ParameterMode.OUT) { param.setMode(ParameterDesc.OUT); } if (headerMode == ParameterMode.IN) { param.setInHeader(true); } else if (headerMode == ParameterMode.INOUT) { param.setInHeader(true); param.setOutHeader(true); } else if (headerMode == ParameterMode.OUT) { param.setOutHeader(true); } operation.addParameter(param); parmAndRetReq = true; } // addParameterAsHeader /** * Return the QName of the type of the parameters with the given name. * * @param paramName name of the parameter to return * @return XMLType XMLType of paramName, or null if not found. */ public QName getParameterTypeByName(String paramName) { QName paramQName = new QName("", paramName); return getParameterTypeByQName(paramQName); } /** * Return the QName of the type of the parameters with the given name. * * Note: Not part of JAX-RPC specification. * * @param paramQName QName of the parameter to return * @return XMLType XMLType of paramQName, or null if not found. */ public QName getParameterTypeByQName(QName paramQName) { ParameterDesc param = operation.getParamByQName(paramQName); if (param != null) { return param.getTypeQName(); } return( null ); } /** * Sets the return type of the operation associated with this Call object. * * @param type QName of the return value type. */ public void setReturnType(QName type) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) operation = new OperationDesc(); // In order to allow any Call to be re-used, Axis // chooses to allow setReturnType to be changed when // parmAndRetReq==false. This does not conflict with // JSR 101 which indicates an exception MAY be thrown. //if (parmAndRetReq) { operation.setReturnType(type); TypeMapping tm = getTypeMapping(); operation.setReturnClass(tm.getClassForQName(type)); parmAndRetReq = true; //} //else { //throw new JAXRPCException(Messages.getMessage("noParmAndRetReq")); //} } /** * Sets the return type for a specific operation. * * @param xmlType - QName of the data type of the return value * @param javaType - Java class of the return value * @exception JAXRPCException - if isParameterAndReturnSpecRequired returns * false, then setReturnType MAY throw JAXRPCException...Axis allows * modification without throwing the exception. */ public void setReturnType(QName xmlType, Class javaType) { setReturnType(xmlType); // Use specified type as the operation return operation.setReturnClass(javaType); } /** * Set the return type as a header */ public void setReturnTypeAsHeader(QName xmlType) { setReturnType(xmlType); operation.setReturnHeader(true); } // setReturnTypeAsHeader /** * Set the return type as a header */ public void setReturnTypeAsHeader(QName xmlType, Class javaType) { setReturnType(xmlType, javaType); operation.setReturnHeader(true); } // setReturnTypeAsHeader /** * Returns the QName of the type of the return value of this Call - or null * if not set. * * Note: Not part of JAX-RPC specification. * * @return the XMLType specified for this Call (or null). */ public QName getReturnType() { if (operation != null) return operation.getReturnType(); return null; } /** * Set the QName of the return element * * NOT part of JAX-RPC */ public void setReturnQName(QName qname) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) operation = new OperationDesc(); operation.setReturnQName(qname); } /** * Sets the desired return Java Class. This is a convenience method * which will cause the Call to automatically convert return values * into a desired class if possible. For instance, we return object * arrays by default now for SOAP arrays - you could specify: * * setReturnClass(Vector.class) * * and you'd get a Vector back from invoke() instead of having to do * the conversion yourself. * * Note: Not part of JAX-RPC specification. To be JAX-RPC compliant, * use setReturnType(QName, Class). * * @param cls the desired return class. */ public void setReturnClass(Class cls) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) operation = new OperationDesc(); operation.setReturnClass(cls); TypeMapping tm = getTypeMapping(); operation.setReturnType(tm.getTypeQName(cls)); parmAndRetReq = true; } /** * Clears the list of parameters. * @exception JAXRPCException - if isParameterAndReturnSpecRequired returns * false, then removeAllParameters MAY throw JAXRPCException...Axis allows * modification to the Call object without throwing an exception. */ public void removeAllParameters() { //if (parmAndRetReq) { operation = new OperationDesc(); operationSetManually = false; parmAndRetReq = true; //} //else { //throw new JAXRPCException(Messages.getMessage("noParmAndRetReq")); //} } /** * Returns the operation name associated with this Call object. * * @return String Name of the operation or null if not set. */ public QName getOperationName() { return( operationName ); } /** * Sets the operation name associated with this Call object. This will * not check the WSDL (if there is WSDL) to make sure that it's a valid * operation name. * * @param opName Name of the operation. */ public void setOperationName(QName opName) { operationName = opName ; } /** * This is a convenience method. If the user doesn't care about the QName * of the operation, the user can call this method, which converts a String * operation name to a QName. */ public void setOperationName(String opName) { operationName = new QName(opName); } /** * Prefill as much info from the WSDL as it can. * Right now it's SOAPAction, operation qname, parameter types * and return type of the Web Service. * * This methods considers that port name and target endpoint address have * already been set. This is useful when you want to use the same Call * instance for several calls on the same Port * * Note: Not part of JAX-RPC specification. * * @param opName Operation(method) that's going to be invoked * @throws JAXRPCException */ public void setOperation(String opName) { if ( service == null ) { throw new JAXRPCException( Messages.getMessage("noService04") ); } // remove all settings concerning an operation // leave portName and targetEndPoint as they are this.setOperationName( opName ); this.setEncodingStyle( null ); this.setReturnType( null ); this.removeAllParameters(); javax.wsdl.Service wsdlService = service.getWSDLService(); // Nothing to do is the WSDL is not already set. if(wsdlService == null) { return; } Port port = wsdlService.getPort( portName.getLocalPart() ); if ( port == null ) { throw new JAXRPCException( Messages.getMessage("noPort00", "" + portName) ); } Binding binding = port.getBinding(); PortType portType = binding.getPortType(); if ( portType == null ) { throw new JAXRPCException( Messages.getMessage("noPortType00", "" + portName) ); } this.setPortTypeName(portType.getQName()); List operations = portType.getOperations(); if ( operations == null ) { throw new JAXRPCException( Messages.getMessage("noOperation01", opName) ); } Operation op = null ; for ( int i = 0 ; i < operations.size() ; i++, op=null ) { op = (Operation) operations.get( i ); if ( opName.equals( op.getName() ) ) { break ; } } if ( op == null ) { throw new JAXRPCException( Messages.getMessage("noOperation01", opName) ); } // Get the SOAPAction //////////////////////////////////////////////////////////////////// List list = port.getExtensibilityElements(); String opStyle = null; BindingOperation bop = binding.getBindingOperation(opName, null, null); if ( bop == null ) { throw new JAXRPCException( Messages.getMessage("noOperation02", opName )); } list = bop.getExtensibilityElements(); for ( int i = 0 ; list != null && i < list.size() ; i++ ) { Object obj = list.get(i); if ( obj instanceof SOAPOperation ) { SOAPOperation sop = (SOAPOperation) obj ; opStyle = ((SOAPOperation) obj).getStyle(); String action = sop.getSoapActionURI(); if ( action != null ) { setUseSOAPAction(true); setSOAPActionURI(action); } else { setUseSOAPAction(false); setSOAPActionURI(null); } break ; } } // Get the body's namespace URI and encoding style //////////////////////////////////////////////////////////////////// BindingInput bIn = bop.getBindingInput(); if ( bIn != null ) { list = bIn.getExtensibilityElements(); for ( int i = 0 ; list != null && i < list.size() ; i++ ) { Object obj = list.get(i); if( obj instanceof MIMEMultipartRelated){ MIMEMultipartRelated mpr=(MIMEMultipartRelated) obj; Object part= null; List l= mpr.getMIMEParts(); for(int j=0; l!= null && j< l.size() && part== null; j++){ MIMEPart mp = (MIMEPart)l.get(j); List ll= mp.getExtensibilityElements(); for(int k=0; ll != null && k < ll.size() && part == null; k++){ part= ll.get(k); if ( !(part instanceof SOAPBody)) { part = null; } } } if(null != part) { obj= part; } } if ( obj instanceof SOAPBody ) { SOAPBody sBody = (SOAPBody) obj ; list = sBody.getEncodingStyles(); if ( list != null && list.size() > 0 ) { this.setEncodingStyle( (String) list.get(0) ); } String ns = sBody.getNamespaceURI(); if (ns != null && !ns.equals("")) { setOperationName( new QName( ns, opName ) ); } break ; } } } Service service = this.getService(); SymbolTable symbolTable = service.getWSDLParser().getSymbolTable(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); Parameters parameters = bEntry.getParameters(bop.getOperation()); // loop over paramters and set up in/out params for (int j = 0; j < parameters.list.size(); ++j) { Parameter p = (Parameter) parameters.list.get(j); // Get the QName representing the parameter type QName paramType = Utils.getXSIType(p); // checks whether p is an IN or OUT header // and adds it as a header parameter else // add it to the body ParameterMode mode = modes[p.getMode()]; if (p.isInHeader() || p.isOutHeader()) { this.addParameterAsHeader(p.getQName(), paramType, mode, mode); } else { this.addParameter(p.getQName(), paramType, mode); } } Map faultMap = bEntry.getFaults(); // Get the list of faults for this operation ArrayList faults = (ArrayList) faultMap.get(bop); // check for no faults if (faults == null) { return; } // For each fault, register its information for (Iterator faultIt = faults.iterator(); faultIt.hasNext();) { FaultInfo info = (FaultInfo) faultIt.next(); QName qname = info.getQName(); info.getMessage(); // if no parts in fault, skip it! if (qname == null) { continue; } QName xmlType = info.getXMLType(); Class clazz = getTypeMapping().getClassForQName(xmlType); if (clazz != null) { addFault(qname, clazz, xmlType, true); } else { //we cannot map from the info to a java class //In Axis1.1 and before this was silently swallowed. Now we log it log.debug(Messages.getMessage("clientNoTypemapping", xmlType.toString())); } } // set output type if (parameters.returnParam != null) { // Get the QName for the return Type QName returnType = Utils.getXSIType(parameters.returnParam); QName returnQName = parameters.returnParam.getQName(); // Get the javaType String javaType = null; if (parameters.returnParam.getMIMEInfo() != null) { javaType = "javax.activation.DataHandler"; } else { javaType = parameters.returnParam.getType().getName(); } if (javaType == null) { javaType = ""; } else { javaType = javaType + ".class"; } this.setReturnType(returnType); try { Class clazz = ClassUtils.forName(javaType); this.setReturnClass(clazz); } catch (ClassNotFoundException swallowedException) { //log that this lookup failed, log.debug(Messages.getMessage("clientNoReturnClass", javaType)); } this.setReturnQName(returnQName); } else { this.setReturnType(org.apache.axis.encoding.XMLType.AXIS_VOID); } boolean hasMIME = Utils.hasMIME(bEntry, bop); Use use = bEntry.getInputBodyType(bop.getOperation()); setOperationUse(use); if (use == Use.LITERAL) { // Turn off encoding setEncodingStyle(null); // turn off XSI types setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); } if (hasMIME || use == Use.LITERAL) { // If it is literal, turn off multirefs. // // If there are any MIME types, turn off multirefs. // I don't know enough about the guts to know why // attachments don't work with multirefs, but they don't. setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); } Style style = Style.getStyle(opStyle, bEntry.getBindingStyle()); if (style == Style.DOCUMENT && symbolTable.isWrapped()) { style = Style.WRAPPED; } setOperationStyle(style); // Operation name if (style == Style.WRAPPED) { // We need to make sure the operation name, which is what we // wrap the elements in, matches the Qname of the parameter // element. Map partsMap = bop.getOperation().getInput().getMessage().getParts(); Part p = (Part)partsMap.values().iterator().next(); QName q = p.getElementName(); setOperationName(q); } else { QName elementQName = Utils.getOperationQName(bop, bEntry, symbolTable); if (elementQName != null) { setOperationName(elementQName); } } // Indicate that the parameters and return no longer // need to be specified with addParameter calls. parmAndRetReq = false; return; } /** * prefill as much info from the WSDL as it can. * Right now it's target URL, SOAPAction, Parameter types, * and return type of the Web Service. * * If wsdl is not present, this function set port name and operation name * and does not modify target endpoint address. * * Note: Not part of JAX-RPC specification. * * @param portName PortName in the WSDL doc to search for * @param opName Operation(method) that's going to be invoked */ public void setOperation(QName portName, String opName) { setOperation(portName, new QName(opName)); } /** * prefill as much info from the WSDL as it can. * Right now it's target URL, SOAPAction, Parameter types, * and return type of the Web Service. * * If wsdl is not present, this function set port name and operation name * and does not modify target endpoint address. * * Note: Not part of JAX-RPC specification. * * @param portName PortName in the WSDL doc to search for * @param opName Operation(method) that's going to be invoked */ public void setOperation(QName portName, QName opName) { if ( service == null ) throw new JAXRPCException( Messages.getMessage("noService04") ); // Make sure we're making a fresh start. this.setPortName( portName ); this.setOperationName( opName ); this.setReturnType( null ); this.removeAllParameters(); javax.wsdl.Service wsdlService = service.getWSDLService(); // Nothing to do is the WSDL is not already set. if(wsdlService == null) { return; } // we reinitialize target endpoint only if we have wsdl this.setTargetEndpointAddress( (URL) null ); Port port = wsdlService.getPort( portName.getLocalPart() ); if ( port == null ) { throw new JAXRPCException( Messages.getMessage("noPort00", "" + portName) ); } // Get the URL //////////////////////////////////////////////////////////////////// List list = port.getExtensibilityElements(); for ( int i = 0 ; list != null && i < list.size() ; i++ ) { Object obj = list.get(i); if ( obj instanceof SOAPAddress ) { try { SOAPAddress addr = (SOAPAddress) obj ; URL url = new URL(addr.getLocationURI()); this.setTargetEndpointAddress(url); } catch(Exception exp) { throw new JAXRPCException( Messages.getMessage("cantSetURI00", "" + exp) ); } } } setOperation(opName.getLocalPart()); } /** * Returns the fully qualified name of the port for this Call object * (if there is one). * * @return QName Fully qualified name of the port (or null if not set) */ public QName getPortName() { return( portName ); } // getPortName /** * Sets the port name of this Call object. This call will not set * any additional fields, nor will it do any checking to verify that * this port name is actually defined in the WSDL - for now anyway. * * @param portName Fully qualified name of the port */ public void setPortName(QName portName) { this.portName = portName; } // setPortName /** * Returns the fully qualified name of the port type for this Call object * (if there is one). * * @return QName Fully qualified name of the port type */ public QName getPortTypeName() { return portTypeName == null ? new QName("") : portTypeName; } /** * Sets the port type name of this Call object. This call will not set * any additional fields, nor will it do any checking to verify that * this port type is actually defined in the WSDL - for now anyway. * * @param portType Fully qualified name of the portType */ public void setPortTypeName(QName portType) { this.portTypeName = portType; } /** * Allow the user to set the default SOAP version. For SOAP 1.2, pass * SOAPConstants.SOAP12_CONSTANTS. * * @param soapConstants the SOAPConstants object representing the correct * version */ public void setSOAPVersion(SOAPConstants soapConstants) { msgContext.setSOAPConstants(soapConstants); } /** * Invokes a specific operation using a synchronous request-response interaction mode. The invoke method takes * as parameters the object values corresponding to these defined parameter types. Implementation of the invoke * method must check whether the passed parameter values correspond to the number, order and types of parameters * specified in the corresponding operation specification. * * @param operationName - Name of the operation to invoke * @param params - Parameters for this invocation * * @return the value returned from the other end. * * @throws java.rmi.RemoteException - if there is any error in the remote method invocation or if the Call * object is not configured properly. */ public Object invoke(QName operationName, Object[] params) throws java.rmi.RemoteException { QName origOpName = this.operationName; this.operationName = operationName; try { return this.invoke(params); } catch (AxisFault af) { this.operationName = origOpName; if(af.detail != null && af.detail instanceof RemoteException) { throw ((RemoteException)af.detail); } throw af; } catch (java.rmi.RemoteException re) { this.operationName = origOpName; throw re; } catch (RuntimeException re) { this.operationName = origOpName; throw re; } catch (Error e) { this.operationName = origOpName; throw e; } } // invoke /** * Invokes the operation associated with this Call object using the * passed in parameters as the arguments to the method. * * For Messaging (ie. non-RPC) the params argument should be an array * of SOAPBodyElements. <b>All</b> of them need to be SOAPBodyElements, * if any of them are not this method will default back to RPC. In the * Messaging case the return value will be a vector of SOAPBodyElements. * * @param params Array of parameters to invoke the Web Service with * @return Object Return value of the operation/method - or null * @throws java.rmi.RemoteException if there's an error */ public Object invoke(Object[] params) throws java.rmi.RemoteException { long t0=0, t1=0; if( tlog.isDebugEnabled() ) { t0=System.currentTimeMillis(); } /* First see if we're dealing with Messaging instead of RPC. */ /* If ALL of the params are SOAPBodyElements then we're doing */ /* Messaging, otherwise just fall through to normal RPC processing. */ /********************************************************************/ SOAPEnvelope env = null ; int i ; for ( i = 0 ; params != null && i < params.length ; i++ ) if ( !(params[i] instanceof SOAPBodyElement) ) break ; if ( params != null && params.length > 0 && i == params.length ) { /* ok, we're doing Messaging, so build up the message */ /******************************************************/ isMsg = true ; env = new SOAPEnvelope(msgContext.getSOAPConstants(), msgContext.getSchemaVersion()); for (i = 0; i < params.length; i++) { env.addBodyElement((SOAPBodyElement) params[i]); } Message msg = new Message( env ); setRequestMessage(msg); invoke(); msg = msgContext.getResponseMessage(); if (msg == null) { if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) { throw new AxisFault(Messages.getMessage("nullResponse00")); } else { return null; } } env = msg.getSOAPEnvelope(); return( env.getBodyElements() ); } if ( operationName == null ) { throw new AxisFault( Messages.getMessage("noOperation00") ); } try { Object res=this.invoke(operationName.getNamespaceURI(), operationName.getLocalPart(), params); if( tlog.isDebugEnabled() ) { t1=System.currentTimeMillis(); tlog.debug("axis.Call.invoke: " + (t1-t0) + " " + operationName); } return res; } catch( AxisFault af) { if(af.detail != null && af.detail instanceof RemoteException) { throw ((RemoteException)af.detail); } throw af; } catch( Exception exp ) { entLog.debug(Messages.getMessage("toAxisFault00"), exp); throw AxisFault.makeFault(exp); } } /** * Invokes the operation associated with this Call object using the passed * in parameters as the arguments to the method. This will return * immediately rather than waiting for the server to complete its * processing. * * NOTE: the return immediately part isn't implemented yet * * @param params Array of parameters to invoke the Web Service with * @throws JAXRPCException is there's an error */ public void invokeOneWay(Object[] params) { try { invokeOneWay = true; invoke( params ); } catch( Exception exp ) { throw new JAXRPCException( exp.toString() ); } finally { invokeOneWay = false; } } /************************************************************************/ /* End of core JAX-RPC stuff */ /************************************************************************/ /** * Invoke the service with a custom Message. * This method simplifies invoke(SOAPEnvelope). * <p> * Note: Not part of JAX-RPC specification. * * @param msg a Message to send * @throws AxisFault if there is any failure */ public SOAPEnvelope invoke(Message msg) throws AxisFault { try { setRequestMessage( msg ); invoke(); msg = msgContext.getResponseMessage(); if (msg == null) { if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) { throw new AxisFault(Messages.getMessage("nullResponse00")); } else { return null; } } SOAPEnvelope res = null; res = msg.getSOAPEnvelope(); return res; } catch (Exception exp) { if (exp instanceof AxisFault) { throw (AxisFault) exp ; } entLog.debug(Messages.getMessage("toAxisFault00"), exp); throw new AxisFault( Messages.getMessage("errorInvoking00", "\n" + exp)); } } /** * Invoke the service with a custom SOAPEnvelope. * <p> * Note: Not part of JAX-RPC specification. * * @param env a SOAPEnvelope to send * @throws AxisFault if there is any failure */ public SOAPEnvelope invoke(SOAPEnvelope env) throws AxisFault { try { Message msg = new Message( env ); if (getProperty(CHARACTER_SET_ENCODING) != null) { msg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, getProperty(CHARACTER_SET_ENCODING)); } else if (msgContext.getProperty(CHARACTER_SET_ENCODING) != null) { msg.setProperty(CHARACTER_SET_ENCODING, msgContext.getProperty(CHARACTER_SET_ENCODING)); } setRequestMessage( msg ); invoke(); msg = msgContext.getResponseMessage(); if (msg == null) { if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) { throw new AxisFault(Messages.getMessage("nullResponse00")); } else { return null; } } return( msg.getSOAPEnvelope() ); } catch( Exception exp ) { if ( exp instanceof AxisFault ) { throw (AxisFault) exp ; } entLog.debug(Messages.getMessage("toAxisFault00"), exp); throw AxisFault.makeFault(exp); } } /** Register a Transport that should be used for URLs of the specified * protocol. * * Note: Not part of JAX-RPC specification. * * @param protocol the URL protocol (i.e. "tcp" for "tcp://" urls) * @param transportClass the class of a Transport type which will be used * for matching URLs. */ public static void setTransportForProtocol(String protocol, Class transportClass) { if (Transport.class.isAssignableFrom(transportClass)) { transports.put(protocol, transportClass); } else { throw new InternalException(transportClass.toString()); } } /** * Set up the default transport URL mappings. * * This must be called BEFORE doing non-standard URL parsing (i.e. if you * want the system to accept a "local:" URL). This is why the Options class * calls it before parsing the command-line URL argument. * * Note: Not part of JAX-RPC specification. */ public static synchronized void initialize() { addTransportPackage("org.apache.axis.transport"); setTransportForProtocol("java", org.apache.axis.transport.java.JavaTransport.class); setTransportForProtocol("local", org.apache.axis.transport.local.LocalTransport.class); setTransportForProtocol("http", HTTPTransport.class); setTransportForProtocol("https", HTTPTransport.class); } /** * Cache of transport packages we've already added to the system * property. */ private static ArrayList transportPackages = null; /** Add a package to the system protocol handler search path. This * enables users to create their own URLStreamHandler classes, and thus * allow custom protocols to be used in Axis (typically on the client * command line). * * For instance, if you add "samples.transport" to the packages property, * and have a class samples.transport.tcp.Handler, the system will be able * to parse URLs of the form "tcp://host:port..." * * Note: Not part of JAX-RPC specification. * * @param packageName the package in which to search for protocol names. */ public static synchronized void addTransportPackage(String packageName) { if (transportPackages == null) { transportPackages = new ArrayList(); String currentPackages = AxisProperties.getProperty(TRANSPORT_PROPERTY); if (currentPackages != null) { StringTokenizer tok = new StringTokenizer(currentPackages, "|"); while (tok.hasMoreTokens()) { transportPackages.add(tok.nextToken()); } } } if (transportPackages.contains(packageName)) { return; } transportPackages.add(packageName); StringBuffer currentPackages = new StringBuffer(); for (Iterator i = transportPackages.iterator(); i.hasNext();) { String thisPackage = (String) i.next(); currentPackages.append(thisPackage); currentPackages.append('|'); } final String transportProperty = currentPackages.toString(); java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { public Object run() { try { System.setProperty(TRANSPORT_PROPERTY, transportProperty); } catch (SecurityException se){ } return null; } }); } /** * Convert the list of objects into RPCParam's based on the paramNames, * paramXMLTypes and paramModes variables. If those aren't set then just * return what was passed in. * * @param params Array of parameters to pass into the operation/method * @return Object[] Array of parameters to pass to invoke() */ private Object[] getParamList(Object[] params) { int numParams = 0 ; // If we never set-up any names... then just return what was passed in ////////////////////////////////////////////////////////////////////// if (log.isDebugEnabled()) { log.debug( "operation=" + operation); if (operation != null) { log.debug("operation.getNumParams()=" + operation.getNumParams()); } } if ( operation == null || operation.getNumParams() == 0 ) { return( params ); } // Count the number of IN and INOUT params, this needs to match the // number of params passed in - if not throw an error ///////////////////////////////////////////////////////////////////// numParams = operation.getNumInParams(); if ( params == null || numParams != params.length ) { throw new JAXRPCException( Messages.getMessage( "parmMismatch00", (params == null) ? "no params" : "" + params.length, "" + numParams ) ); } log.debug( "getParamList number of params: " + params.length); // All ok - so now produce an array of RPCParams ////////////////////////////////////////////////// Vector result = new Vector(); int j = 0 ; ArrayList parameters = operation.getParameters(); for (int i = 0; i < parameters.size(); i++) { ParameterDesc param = (ParameterDesc)parameters.get(i); if (param.getMode() != ParameterDesc.OUT) { QName paramQName = param.getQName(); // Create an RPCParam if param isn't already an RPCParam. RPCParam rpcParam = null; Object p = params[j++]; if(p instanceof RPCParam) { rpcParam = (RPCParam)p; } else { rpcParam = new RPCParam(paramQName.getNamespaceURI(), paramQName.getLocalPart(), p); } // Attach the ParameterDescription to the RPCParam // so that the serializer can use the (javaType, xmlType) // information. rpcParam.setParamDesc(param); // Add the param to the header or vector depending // on whether it belongs in the header or body. if (param.isInHeader()) { addHeader(new RPCHeaderParam(rpcParam)); } else { result.add(rpcParam); } } } return( result.toArray() ); } /** * Set the Transport * * Note: Not part of JAX-RPC specification. * * @param trans the Transport object we'll use to set up * MessageContext properties. */ public void setTransport(Transport trans) { transport = trans; if (log.isDebugEnabled()) log.debug(Messages.getMessage("transport00", "" + transport)); } /** Get the Transport registered for the given protocol. * * Note: Not part of JAX-RPC specification. * * @param protocol a protocol such as "http" or "local" which may * have a Transport object associated with it. * @return the Transport registered for this protocol, or null if none. */ public Transport getTransportForProtocol(String protocol) { Class transportClass = (Class)transports.get(protocol); Transport ret = null; if (transportClass != null) { try { ret = (Transport)transportClass.newInstance(); } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } return ret; } /** * Directly set the request message in our MessageContext. * * This allows custom message creation. * * Note: Not part of JAX-RPC specification. * * @param msg the new request message. * @throws RuntimeException containing the text of an AxisFault, if any * AxisFault was thrown */ public void setRequestMessage(Message msg) { String attachformat= (String)getProperty( ATTACHMENT_ENCAPSULATION_FORMAT); if(null != attachformat) { Attachments attachments=msg.getAttachmentsImpl(); if(null != attachments) { if( ATTACHMENT_ENCAPSULATION_FORMAT_MIME.equals(attachformat)) { attachments.setSendType(Attachments.SEND_TYPE_MIME); } else if ( ATTACHMENT_ENCAPSULATION_FORMAT_MTOM.equals(attachformat)) { attachments.setSendType(Attachments.SEND_TYPE_MTOM); } else if ( ATTACHMENT_ENCAPSULATION_FORMAT_DIME.equals(attachformat)) { attachments.setSendType(Attachments.SEND_TYPE_DIME); } } } if(null != attachmentParts && !attachmentParts.isEmpty()){ try{ Attachments attachments= msg.getAttachmentsImpl(); if(null == attachments) { throw new RuntimeException( Messages.getMessage("noAttachments")); } attachments.setAttachmentParts(attachmentParts); }catch(AxisFault ex){ log.info(Messages.getMessage("axisFault00"), ex); throw new RuntimeException(ex.getMessage()); } } msgContext.setRequestMessage(msg); attachmentParts.clear(); } /** * Directly get the response message in our MessageContext. * * Shortcut for having to go thru the msgContext * * Note: Not part of JAX-RPC specification. * * @return the response Message object in the msgContext */ public Message getResponseMessage() { return msgContext.getResponseMessage(); } /** * Obtain a reference to our MessageContext. * * Note: Not part of JAX-RPC specification. * * @return the MessageContext. */ public MessageContext getMessageContext () { return msgContext; } /** * Add a header which should be inserted into each outgoing message * we generate. * * Note: Not part of JAX-RPC specification. * * @param header a SOAPHeaderElement to be inserted into messages */ public void addHeader(SOAPHeaderElement header) { if (myHeaders == null) { myHeaders = new Vector(); } myHeaders.add(header); } /** * Clear the list of headers which we insert into each message * * Note: Not part of JAX-RPC specification. */ public void clearHeaders() { myHeaders = null; } public TypeMapping getTypeMapping() { // Get the TypeMappingRegistry TypeMappingRegistry tmr = msgContext.getTypeMappingRegistry(); // If a TypeMapping is not available, add one. return tmr.getOrMakeTypeMapping(getEncodingStyle()); } /** * Register type mapping information for serialization/deserialization * * Note: Not part of JAX-RPC specification. * * @param javaType is the Java class of the data type. * @param xmlType the xsi:type QName of the associated XML type. * @param sf/df are the factories (or the Class objects of the factory). */ public void registerTypeMapping(Class javaType, QName xmlType, SerializerFactory sf, DeserializerFactory df) { registerTypeMapping(javaType, xmlType, sf, df, true); } /** * Register type mapping information for serialization/deserialization * * Note: Not part of JAX-RPC specification. * * @param javaType is the Java class of the data type. * @param xmlType the xsi:type QName of the associated XML type. * @param sf/df are the factories (or the Class objects of the factory). * @param force Indicates whether to add the information if already registered. */ public void registerTypeMapping(Class javaType, QName xmlType, SerializerFactory sf, DeserializerFactory df, boolean force) { TypeMapping tm = getTypeMapping(); if (!force && tm.isRegistered(javaType, xmlType)) { return; } // Register the information tm.register(javaType, xmlType, sf, df); } /** * register this type matting * @param javaType * @param xmlType * @param sfClass * @param dfClass */ public void registerTypeMapping(Class javaType, QName xmlType, Class sfClass, Class dfClass) { registerTypeMapping(javaType, xmlType, sfClass, dfClass, true); } /** * register a type. This only takes place if either the serializer or * deserializer factory could be created. * @param javaType java type to handle * @param xmlType XML mapping * @param sfClass class of serializer factory * @param dfClass class of deserializer factory * @param force */ public void registerTypeMapping(Class javaType, QName xmlType, Class sfClass, Class dfClass, boolean force) { // Instantiate the factory using introspection. SerializerFactory sf = BaseSerializerFactory.createFactory(sfClass, javaType, xmlType); DeserializerFactory df = BaseDeserializerFactory.createFactory(dfClass, javaType, xmlType); if (sf != null || df != null) { registerTypeMapping(javaType, xmlType, sf, df, force); } } /************************************************ * Invocation */ /** Invoke an RPC service with a method name and arguments. * * This will call the service, serializing all the arguments, and * then deserialize the return value. * * Note: Not part of JAX-RPC specification. * * @param namespace the desired namespace URI of the method element * @param method the method name * @param args an array of Objects representing the arguments to the * invoked method. If any of these objects are RPCParams, * Axis will use the embedded name of the RPCParam as the * name of the parameter. Otherwise, we will serialize * each argument as an XML element called "arg&lt;n&gt;". * @return a deserialized Java Object containing the return value * @exception AxisFault */ public Object invoke(String namespace, String method, Object[] args) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: Call::invoke(ns, meth, args)"); } /** * Since JAX-RPC requires us to specify all or nothing, if setReturnType * was called (returnType != null) and we have args but addParameter * wasn't called (paramXMLTypes == null), then toss a fault. */ if (getReturnType() != null && args != null && args.length != 0 && operation.getNumParams() == 0) { throw new AxisFault(Messages.getMessage("mustSpecifyParms")); } RPCElement body = new RPCElement(namespace, method, getParamList(args)); Object ret = invoke( body ); if (log.isDebugEnabled()) { log.debug("Exit: Call::invoke(ns, meth, args)"); } return ret; } /** Convenience method to invoke a method with a default (empty) * namespace. Calls invoke() above. * * Note: Not part of JAX-RPC specification. * * @param method the method name * @param args an array of Objects representing the arguments to the * invoked method. If any of these objects are RPCParams, * Axis will use the embedded name of the RPCParam as the * name of the parameter. Otherwise, we will serialize * each argument as an XML element called "arg&lt;n&gt;". * @return a deserialized Java Object containing the return value * @exception AxisFault */ public Object invoke( String method, Object [] args ) throws AxisFault { return invoke("", method, args); } /** Invoke an RPC service with a pre-constructed RPCElement. * * Note: Not part of JAX-RPC specification. * * @param body an RPCElement containing all the information about * this call. * @return a deserialized Java Object containing the return value * @exception AxisFault */ public Object invoke( RPCElement body ) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: Call::invoke(RPCElement)"); } /** * Since JAX-RPC requires us to specify a return type if we've set * parameter types, check for this case right now and toss a fault * if things don't look right. */ if (!invokeOneWay && operation != null && operation.getNumParams() > 0 && getReturnType() == null) { // TCK: // Issue an error if the return type was not set, but continue processing. //throw new AxisFault(Messages.getMessage("mustSpecifyReturnType")); log.error(Messages.getMessage("mustSpecifyReturnType")); } SOAPEnvelope reqEnv = new SOAPEnvelope(msgContext.getSOAPConstants(), msgContext.getSchemaVersion()); SOAPEnvelope resEnv = null ; Message reqMsg = new Message( reqEnv ); Message resMsg = null ; Vector resArgs = null ; Object result = null ; // Clear the output params outParams = new HashMap(); outParamsList = new ArrayList(); // Set both the envelope and the RPCElement encoding styles try { body.setEncodingStyle(getEncodingStyle()); setRequestMessage(reqMsg); reqEnv.addBodyElement(body); reqEnv.setMessageType(Message.REQUEST); invoke(); } catch (Exception e) { entLog.debug(Messages.getMessage("toAxisFault00"), e); throw AxisFault.makeFault(e); } resMsg = msgContext.getResponseMessage(); if (resMsg == null) { if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) { throw new AxisFault(Messages.getMessage("nullResponse00")); } else { return null; } } resEnv = resMsg.getSOAPEnvelope(); SOAPBodyElement bodyEl = resEnv.getFirstBody(); if (bodyEl == null) { return null; } if (bodyEl instanceof RPCElement) { try { resArgs = ((RPCElement) bodyEl).getParams(); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } if (resArgs != null && resArgs.size() > 0) { // If there is no return, then we start at index 0 to create the outParams Map. // If there IS a return, then we start with 1. int outParamStart = 0; // If we have resArgs and the returnType is specified, then the first // resArgs is the return. If we have resArgs and neither returnType // nor paramXMLTypes are specified, then we assume that the caller is // following the non-JAX-RPC AXIS shortcut of not having to specify // the return, in which case we again assume the first resArgs is // the return. // NOTE 1: the non-JAX-RPC AXIS shortcut allows a potential error // to escape notice. If the caller IS NOT following the non-JAX-RPC // shortcut but instead intentionally leaves returnType and params // null (ie., a method that takes no parameters and returns nothing) // then, if we DO receive something it should be an error, but this // code passes it through. The ideal solution here is to require // this caller to set the returnType to void, but there's no void // type in XML. // NOTE 2: we should probably verify that the resArgs element // types match the expected returnType and paramXMLTypes, but I'm not // sure how to do that since the resArgs value is a Java Object // and the returnType and paramXMLTypes are QNames. // GD 03/15/02 : We're now checking for invalid metadata // config at the top of this method, so don't need to do it // here. Check for void return, though. boolean findReturnParam = false; QName returnParamQName = null; if (operation != null) { returnParamQName = operation.getReturnQName(); } if (!XMLType.AXIS_VOID.equals(getReturnType())) { if (returnParamQName == null) { // Assume the first param is the return RPCParam param = (RPCParam)resArgs.get(0); result = param.getObjectValue(); outParamStart = 1; } else { // If the QName of the return value was given to us, look // through the result arguments to find the right name findReturnParam = true; } } // The following loop looks at the resargs and // converts the value to the appropriate return/out parameter // value. If the return value is found, is value is // placed in result. The remaining resargs are // placed in the outParams list (note that if a resArg // is found that does not match a operation parameter qname, // it is still placed in the outParms list). for (int i = outParamStart; i < resArgs.size(); i++) { RPCParam param = (RPCParam) resArgs.get(i); Class javaType = getJavaTypeForQName(param.getQName()); Object value = param.getObjectValue(); // Convert type if needed if (javaType != null && value != null && !javaType.isAssignableFrom(value.getClass())) { value = JavaUtils.convert(value, javaType); } // Check if this parameter is our return // otherwise just add it to our outputs if (findReturnParam && returnParamQName.equals(param.getQName())) { // found it! result = value; findReturnParam = false; } else { outParams.put(param.getQName(), value); outParamsList.add(value); } } // added by scheu: // If the return param is still not found, that means // the returned value did not have the expected qname. // The soap specification indicates that this should be // accepted (and we also fail interop tests if we are strict here). // Look through the outParms and find one that // does not match one of the operation parameters. if (findReturnParam) { Iterator it = outParams.keySet().iterator(); while (findReturnParam && it.hasNext()) { QName qname = (QName) it.next(); ParameterDesc paramDesc = operation.getOutputParamByQName(qname); if (paramDesc == null) { // Doesn't match a paramter, so use this for the return findReturnParam = false; result = outParams.remove(qname); } } } // If we were looking for a particular QName for the return and // still didn't find it, throw an exception if (findReturnParam) { String returnParamName = returnParamQName.toString(); throw new AxisFault(Messages.getMessage("noReturnParam", returnParamName)); } } } else { // This is a SOAPBodyElement, try to treat it like a return value try { result = bodyEl.getValueAsType(getReturnType()); } catch (Exception e) { // just return the SOAPElement result = bodyEl; } } if (log.isDebugEnabled()) { log.debug("Exit: Call::invoke(RPCElement)"); } // Convert type if needed if (operation != null && operation.getReturnClass() != null) { result = JavaUtils.convert(result, operation.getReturnClass()); } return( result ); } /** * Get the javaType for a given parameter. * * @param name the QName of the parameter * @return the class associated with that parameter */ private Class getJavaTypeForQName(QName name) { if (operation == null) { return null; } ParameterDesc param = operation.getOutputParamByQName(name); return param == null ? null : param.getJavaType(); } /** * Set engine option. * * Note: Not part of JAX-RPC specification. */ public void setOption(String name, Object value) { service.getEngine().setOption(name, value); } /** * Invoke this Call with its established MessageContext * (perhaps because you called this.setRequestMessage()) * * Note: Not part of JAX-RPC specification. * * @exception AxisFault */ public void invoke() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: Call::invoke()"); } isNeverInvoked = false; Message reqMsg = null ; SOAPEnvelope reqEnv = null ; msgContext.reset(); msgContext.setResponseMessage(null); msgContext.setProperty( MessageContext.CALL, this ); msgContext.setProperty( WSDL_SERVICE, service ); msgContext.setProperty( WSDL_PORT_NAME, getPortName() ); if ( isMsg ) { msgContext.setProperty( MessageContext.IS_MSG, "true" ); } if (username != null) { msgContext.setUsername(username); } if (password != null) { msgContext.setPassword(password); } msgContext.setMaintainSession(maintainSession); if (operation != null) { msgContext.setOperation(operation); operation.setStyle(getOperationStyle()); operation.setUse(getOperationUse()); } if (useSOAPAction) { msgContext.setUseSOAPAction(true); } if (SOAPActionURI != null) { msgContext.setSOAPActionURI(SOAPActionURI); } else { msgContext.setSOAPActionURI(null); } if (timeout != null) { msgContext.setTimeout(timeout.intValue()); } msgContext.setHighFidelity(!useStreaming); // Determine client target service if (myService != null) { // If we have a SOAPService kicking around, use that directly msgContext.setService(myService); } else { if (portName != null) { // No explicit service. If we have a target service name, // try that. msgContext.setTargetService(portName.getLocalPart()); } else { // No direct config, so try the namespace of the first body. reqMsg = msgContext.getRequestMessage(); if (reqMsg != null && !((SOAPPart)reqMsg.getSOAPPart()).isBodyStream()) { reqEnv = reqMsg.getSOAPEnvelope(); SOAPBodyElement body = reqEnv.getFirstBody(); if (body != null) { if ( body.getNamespaceURI() == null ) { throw new AxisFault("Call.invoke", Messages.getMessage("cantInvoke00", body.getName()), null, null); } else { msgContext.setTargetService(body.getNamespaceURI()); } } } } } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("targetService", msgContext.getTargetService())); } Message requestMessage = msgContext.getRequestMessage(); if (requestMessage != null) { try { msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestMessage.getProperty(SOAPMessage.CHARACTER_SET_ENCODING)); } catch (SOAPException e) { } if(myHeaders != null) { reqEnv = requestMessage.getSOAPEnvelope(); // If we have headers to insert, do so now. for (int i = 0 ; myHeaders != null && i < myHeaders.size() ; i++ ) { reqEnv.addHeader((SOAPHeaderElement)myHeaders.get(i)); } } } // set up transport if there is one if (transport != null) { transport.setupMessageContext(msgContext, this, service.getEngine()); } else { msgContext.setTransportName( transportName ); } SOAPService svc = msgContext.getService(); if (svc != null) { svc.setPropertyParent(myProperties); } else { msgContext.setPropertyParent(myProperties); } // For debugging - print request message if (log.isDebugEnabled()) { StringWriter writer = new StringWriter(); try { SerializationContext ctx = new SerializationContext(writer, msgContext); requestMessage.getSOAPEnvelope().output(ctx); writer.close(); } catch (Exception e) { throw AxisFault.makeFault(e); } finally { log.debug(writer.getBuffer().toString()); } } if(!invokeOneWay) { invokeEngine(msgContext); } else { invokeEngineOneWay(msgContext); } if (log.isDebugEnabled()) { log.debug("Exit: Call::invoke()"); } } /** * Invoke the message on the current engine and do not wait for a response. * * @param msgContext the <code>MessageContext</code> to use * @throws AxisFault if the invocation raised a fault */ private void invokeEngine(MessageContext msgContext) throws AxisFault { service.getEngine().invoke( msgContext ); if (transport != null) { transport.processReturnedMessageContext(msgContext); } Message resMsg = msgContext.getResponseMessage(); if (resMsg == null) { if (msgContext.isPropertyTrue(FAULT_ON_NO_RESPONSE, false)) { throw new AxisFault(Messages.getMessage("nullResponse00")); } else { return; } } /** This must happen before deserialization... */ resMsg.setMessageType(Message.RESPONSE); SOAPEnvelope resEnv = resMsg.getSOAPEnvelope(); SOAPBodyElement respBody = resEnv.getFirstBody(); if (respBody instanceof SOAPFault) { //we got a fault if(operation == null || operation.getReturnClass() == null || operation.getReturnClass() != javax.xml.soap.SOAPMessage.class) { //unless we don't care about the return value or we want //a raw message back //get the fault from the body and throw it throw ((SOAPFault)respBody).getFault(); } } } /** * Implement async invocation by running the request in a new thread * @param msgContext */ private void invokeEngineOneWay(final MessageContext msgContext) { //TODO: this is not a good way to do stuff, as it has no error reporting facility //create a new class Runnable runnable = new Runnable(){ public void run() { msgContext.setProperty(Call.ONE_WAY, Boolean.TRUE); try { service.getEngine().invoke( msgContext ); } catch (AxisFault af){ //TODO: handle errors properly log.debug(Messages.getMessage("exceptionPrinting"), af); } msgContext.removeProperty(Call.ONE_WAY); } }; //create a thread to run it Thread thread = new Thread(runnable); //run it thread.start(); } /** * Get the output parameters (if any) from the last invocation. * * This allows named access - if you need sequential access, use * getOutputValues(). * * @return a Map containing the output parameter values, indexed by QName */ public Map getOutputParams() { if (isNeverInvoked) { throw new JAXRPCException( Messages.getMessage("outputParamsUnavailable")); } return this.outParams; } /** * Returns a List values for the output parameters of the last * invoked operation. * * @return Values for the output parameters. An empty List is * returned if there are no output values. * * @throws JAXRPCException - If this method is invoked for a * one-way operation or is invoked * before any invoke method has been called. */ public List getOutputValues() { if (isNeverInvoked) { throw new JAXRPCException( Messages.getMessage("outputParamsUnavailable")); } return outParamsList; } /** * Get the Service object associated with this Call object. * * Note: Not part of JAX-RPC specification. * * @return Service the Service object this Call object is associated with */ public Service getService() { return this.service; } /** * * Set the service so that it defers missing property gets to the * Call. So when client-side Handlers get at the MessageContext, * the property scoping will be MC -&gt; SOAPService -&gt; Call */ public void setSOAPService(SOAPService service) { myService = service; if (service != null) { // Set the service so that it defers missing property gets to the // Call. So when client-side Handlers get at the MessageContext, // the property scoping will be MC -> SOAPService -> Call -> Engine // THE ORDER OF THESE TWO CALLS IS IMPORTANT, since setting the // engine on a service will set the property parent for the service service.setEngine(this.service.getAxisClient()); service.setPropertyParent(myProperties); } } /** * Sets the client-side request and response Handlers. This is handy * for programatically setting up client-side work without deploying * via WSDD or the EngineConfiguration mechanism. */ public void setClientHandlers(Handler reqHandler, Handler respHandler) { // Create a SOAPService which will be used as the client-side service // handler. setSOAPService(new SOAPService(reqHandler, null, respHandler)); } /** * This method adds an attachment. * <p> * Note: Not part of JAX-RPC specification. * * @param attachment the <code>Object</code> to attach * @exception RuntimeException if there is no support for attachments * */ public void addAttachmentPart( Object attachment){ attachmentParts.add(attachment); } /** * Add a fault for this operation. * <p> * Note: Not part of JAX-RPC specificaion. * * @param qname qname of the fault * @param cls class of the fault * @param xmlType XML type of the fault * @param isComplex true if xmlType is a complex type, false otherwise */ public void addFault(QName qname, Class cls, QName xmlType, boolean isComplex) { if (operationSetManually) { throw new RuntimeException( Messages.getMessage("operationAlreadySet")); } if (operation == null) { operation = new OperationDesc(); } FaultDesc fault = new FaultDesc(); fault.setQName(qname); fault.setClassName(cls.getName()); fault.setXmlType(xmlType); fault.setComplex(isComplex); operation.addFault(fault); } /** * Hand a complete OperationDesc to the Call, and note that this was * done so that others don't try to mess with it by calling addParameter, * setReturnType, etc. * * @param operation the OperationDesc to associate with this call. */ public void setOperation(OperationDesc operation) { this.operation = operation; operationSetManually = true; } public OperationDesc getOperation() { return operation; } public void clearOperation() { operation = null; operationSetManually = false; } }
7,796
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/AdminClient.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client ; import org.apache.axis.AxisFault; import org.apache.axis.EngineConfiguration; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.message.SOAPBodyElement; import org.apache.axis.utils.Messages; import org.apache.axis.utils.Options; import org.apache.axis.utils.StringUtils; import org.apache.commons.logging.Log; import javax.xml.rpc.ServiceException; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.Vector; /** * An admin client object that can be used both from the command line * and programmatically. * * @author Rob Jellinghaus (robj@unrealities.com) * @author Doug Davis (dug@us.ibm.com) * @author Simeon Simeonov (simeons@macromedia.com) */ public class AdminClient { protected static Log log = LogFactory.getLog(AdminClient.class.getName()); private static ThreadLocal defaultConfiguration = new ThreadLocal(); /** * If the user calls this with an EngineConfiguration object, all * AdminClients on this thread will use that EngineConfiguration * rather than the default one. This is primarily to enable the * deployment of custom transports and handlers. * * @param config the EngineConfiguration which should be used */ public static void setDefaultConfiguration(EngineConfiguration config) { defaultConfiguration.set(config); } private static String getUsageInfo() { String lSep = System.getProperty("line.separator"); StringBuffer msg = new StringBuffer(); // 26 is the # of lines in resources.properties msg.append(Messages.getMessage("acUsage00")).append(lSep); msg.append(Messages.getMessage("acUsage01")).append(lSep); msg.append(Messages.getMessage("acUsage02")).append(lSep); msg.append(Messages.getMessage("acUsage03")).append(lSep); msg.append(Messages.getMessage("acUsage04")).append(lSep); msg.append(Messages.getMessage("acUsage05")).append(lSep); msg.append(Messages.getMessage("acUsage06")).append(lSep); msg.append(Messages.getMessage("acUsage07")).append(lSep); msg.append(Messages.getMessage("acUsage08")).append(lSep); msg.append(Messages.getMessage("acUsage09")).append(lSep); msg.append(Messages.getMessage("acUsage10")).append(lSep); msg.append(Messages.getMessage("acUsage11")).append(lSep); msg.append(Messages.getMessage("acUsage12")).append(lSep); msg.append(Messages.getMessage("acUsage13")).append(lSep); msg.append(Messages.getMessage("acUsage14")).append(lSep); msg.append(Messages.getMessage("acUsage15")).append(lSep); msg.append(Messages.getMessage("acUsage16")).append(lSep); msg.append(Messages.getMessage("acUsage17")).append(lSep); msg.append(Messages.getMessage("acUsage18")).append(lSep); msg.append(Messages.getMessage("acUsage19")).append(lSep); msg.append(Messages.getMessage("acUsage20")).append(lSep); msg.append(Messages.getMessage("acUsage21")).append(lSep); msg.append(Messages.getMessage("acUsage22")).append(lSep); msg.append(Messages.getMessage("acUsage23")).append(lSep); msg.append(Messages.getMessage("acUsage24")).append(lSep); msg.append(Messages.getMessage("acUsage25")).append(lSep); msg.append(Messages.getMessage("acUsage26")).append(lSep); return msg.toString(); } /** * the object that represents our call */ protected Call call; /** * Construct an admin client w/o a logger. * If the client cannot create a call object, then it does not throw an exception. * Instead it prints a message to {@link System#err}. * This is for 'historical reasons' */ public AdminClient() { try { initAdminClient(); } catch (ServiceException e) { System.err.println(Messages.getMessage("couldntCall00") + ": " + e); call = null; } } /** * this is a somwhat contrived variant constructor, one that throws an exception * if things go wrong. * @param ignored */ public AdminClient(boolean ignored) throws ServiceException { initAdminClient(); } /** * core initialisation routine * * @throws ServiceException */ private void initAdminClient() throws ServiceException { // Initialize our Service - allow the user to override the // default configuration with a thread-local version (see // setDefaultConfiguration() above) EngineConfiguration config = (EngineConfiguration) defaultConfiguration.get(); Service service; if (config != null) { service = new Service(config); } else { service = new Service(); } call = (Call) service.createCall(); } /** * External access to our <code>Call</code> object. * This will be null if the non-excepting constructor was used * and the construction failed. * @return the <code>Call</code> object this instance uses */ public Call getCall() { return call; } /** * process the options then run a list call * @param opts * @return * @throws Exception */ public String list(Options opts) throws Exception { processOpts( opts ); return list(); } /** * send a list command * @return the response from the call * @throws Exception */ public String list() throws Exception { log.debug( Messages.getMessage("doList00") ); String str = "<m:list xmlns:m=\"" + WSDDConstants.URI_WSDD + "\"/>" ; ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); return process(input); } /** * process the command line ops, then send a quit command * @param opts * @return * @throws Exception */ public String quit(Options opts) throws Exception { processOpts( opts ); return quit(); } /** * root element of the undeploy request */ protected static final String ROOT_UNDEPLOY= WSDDConstants.QNAME_UNDEPLOY.getLocalPart(); /** * make a quit command * @return * @throws Exception */ public String quit() throws Exception { log.debug(Messages.getMessage("doQuit00")); String str = "<m:quit xmlns:m=\"" + WSDDConstants.URI_WSDD + "\"/>"; ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); return process(input); } /** * undeploy a handler * @param handlerName name of the handler to undeploy * @return * @throws Exception */ public String undeployHandler(String handlerName) throws Exception { log.debug(Messages.getMessage("doQuit00")); String str = "<m:"+ROOT_UNDEPLOY +" xmlns:m=\"" + WSDDConstants.URI_WSDD + "\">" + "<handler name=\"" + handlerName + "\"/>"+ "</m:"+ROOT_UNDEPLOY +">" ; ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); return process(input); } /** * undeploy a service * @param serviceName name of service * @return * @throws Exception */ public String undeployService(String serviceName) throws Exception { log.debug(Messages.getMessage("doQuit00")); String str = "<m:"+ROOT_UNDEPLOY +" xmlns:m=\"" + WSDDConstants.URI_WSDD + "\">" + "<service name=\"" + serviceName + "\"/>"+ "</m:"+ROOT_UNDEPLOY +">" ; ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); return process(input); } /** * <p>Processes a set of administration commands.</p> * <p>The following commands are available:</p> * <ul> * <li><code>-l<i>url</i></code> sets the AxisServlet URL</li> * <li><code>-h<i>hostName</i></code> sets the AxisServlet host</li> * <li><code>-p<i>portNumber</i></code> sets the AxisServlet port</li> * <li><code>-s<i>servletPath</i></code> sets the path to the * AxisServlet</li> * <li><code>-f<i>fileName</i></code> specifies that a simple file * protocol should be used</li> * <li><code>-u<i>username</i></code> sets the username</li> * <li><code>-w<i>password</i></code> sets the password</li> * <li><code>-d</code> sets the debug flag (for instance, -ddd would * set it to 3)</li> * <li><code>-t<i>name</i></code> sets the transport chain touse</li> * <li><code>list</code> will list the currently deployed services</li> * <li><code>quit</code> will quit (???)</li> * <li><code>passwd <i>value</i></code> changes the admin password</li> * <li><code><i>xmlConfigFile</i></code> deploys or undeploys * Axis components and web services</li> * </ul> * <p>If <code>-l</code> or <code>-h -p -s</code> are not set, the * AdminClient will invoke * <code>http://localhost:8080/axis/servlet/AxisServlet</code>.</p> * * @param args Commands to process * @return XML result or null in case of failure. In the case of multiple * commands, the XML results will be concatenated, separated by \n * @exception Exception Could be an IO exception, an AxisFault or something else */ public String process(String[] args) throws Exception { StringBuffer sb = new StringBuffer(); Options opts = new Options( args ); opts.setDefaultURL("http://localhost:8080/axis/services/AdminService"); if (opts.isFlagSet('d') > 0) { // Set logger properties... !!! } args = opts.getRemainingArgs(); if ( args == null || opts.isFlagSet('?') > 0) { System.out.println(Messages.getMessage("usage00","AdminClient [Options] [list | <deployment-descriptor-files>]")); System.out.println(""); System.out.println(getUsageInfo()); return null; } for ( int i = 0 ; i < args.length ; i++ ) { InputStream input = null; if ( args[i].equals("list") ) sb.append( list(opts) ); else if (args[i].equals("quit")) sb.append( quit(opts) ); else if (args[i].equals("passwd")) { System.out.println(Messages.getMessage("changePwd00")); if (args[i + 1] == null) { System.err.println(Messages.getMessage("needPwd00")); return null; } String str = "<m:passwd xmlns:m=\"http://xml.apache.org/axis/wsdd/\">"; str += args[i + 1]; str += "</m:passwd>"; input = new ByteArrayInputStream(str.getBytes()); i++; sb.append( process(opts, input) ); } else { if(args[i].indexOf(java.io.File.pathSeparatorChar)==-1){ System.out.println( Messages.getMessage("processFile00", args[i]) ); sb.append( process(opts, args[i] ) ); } else { java.util.StringTokenizer tokenizer = null ; tokenizer = new java.util.StringTokenizer(args[i], java.io.File.pathSeparator); while(tokenizer.hasMoreTokens()) { String file = tokenizer.nextToken(); System.out.println( Messages.getMessage("processFile00", file) ); sb.append( process(opts, file) ); if(tokenizer.hasMoreTokens()) sb.append("\n"); } } } } return sb.toString(); } /** * go from the (parsed) command line to setting properties on our call object. * @param opts * @throws Exception if call==null */ public void processOpts(Options opts) throws Exception { if (call == null) { throw new Exception(Messages.getMessage("nullCall00")); } URL address = new URL(opts.getURL()); setTargetEndpointAddress(address); setLogin(opts.getUser(), opts.getPassword()); String tName = opts.isValueSet( 't' ); setTransport(tName); } /** * set the username and password * requires that call!=null * @param user username * @param password password */ public void setLogin(String user, String password) { call.setUsername( user ); call.setPassword( password ); } /** * set the URL to deploy to * requires that call!=null * @param address */ public void setTargetEndpointAddress(URL address) { call.setTargetEndpointAddress( address ); } /** * set the transport to deploy with. * requires that call!=null * @param transportName a null or empty value does not trigger a setting */ public void setTransport(String transportName) { if(transportName != null && !transportName.equals("")) { call.setProperty( Call.TRANSPORT_NAME, transportName ); } } public String process(InputStream input) throws Exception { return process(null, input ); } public String process(URL xmlURL) throws Exception { return process(null, xmlURL.openStream() ); } /** * process an XML file containing a pre-prepared admin message * @param xmlFile file to load * @return * @throws Exception */ public String process(String xmlFile) throws Exception { FileInputStream in = new FileInputStream(xmlFile); String result = process(null, in ); return result ; } public String process(Options opts, String xmlFile) throws Exception { processOpts( opts ); return process( xmlFile ); } /** * submit the input stream's contents to the endpoint, return the results as a string. * The input stream is always closed after the call, whether the request worked or not * @param opts options -can be null * @param input -input stream for request * @return * @throws Exception if the call was null * @throws AxisFault if the invocation returned an empty response */ public String process(Options opts, InputStream input) throws Exception { try { if (call == null) { //validate that the call is not null throw new Exception(Messages.getMessage("nullCall00")); } if ( opts != null ) { //process options if supplied processOpts( opts ); } call.setUseSOAPAction( true); call.setSOAPActionURI( "urn:AdminService"); Vector result = null ; Object[] params = new Object[] { new SOAPBodyElement(input) }; result = (Vector) call.invoke( params ); if (result == null || result.isEmpty()) { throw new AxisFault(Messages.getMessage("nullResponse00")); } SOAPBodyElement body = (SOAPBodyElement) result.elementAt(0); return body.toString(); } finally { input.close(); } } /** * Creates in instance of <code>AdminClient</code> and * invokes <code>process(args)</code>. * <p>Diagnostic output goes to <code>log.info</code>.</p> * @param args Commands to process */ public static void main (String[] args) { try { AdminClient admin = new AdminClient(); String result = admin.process(args); if (result != null) { System.out.println( StringUtils.unescapeNumericChar(result) ); } else { System.exit(1); } } catch (AxisFault ae) { System.err.println(Messages.getMessage("exception00") + " " + ae.dumpToString()); System.exit(1); } catch (Exception e) { System.err.println(Messages.getMessage("exception00") + " " + e.getMessage()); System.exit(1); } } }
7,797
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/Service.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client; import org.apache.axis.AxisEngine; import org.apache.axis.EngineConfiguration; import org.apache.axis.configuration.EngineConfigurationFactoryFinder; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.WSDLUtils; import org.apache.axis.utils.XMLUtils; import org.apache.axis.wsdl.gen.Parser; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.w3c.dom.Document; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.wsdl.Binding; import javax.wsdl.Operation; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.extensions.soap.SOAPAddress; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import javax.xml.rpc.encoding.TypeMappingRegistry; import javax.xml.rpc.handler.HandlerRegistry; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.URL; import java.rmi.Remote; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.WeakHashMap; /** * Axis' JAXRPC Dynamic Invoation Interface implementation of the Service * interface. * * The Service class should be used a the starting point for access * SOAP Web Services. Typically, a Service will be created with a WSDL * document and along with a serviceName you can then ask for a Call * object that will allow you to invoke a Web Service. * * @author Doug Davis (dug@us.ibm.com) */ public class Service implements javax.xml.rpc.Service, Serializable, Referenceable { private transient AxisEngine engine = null; private transient EngineConfiguration config = null; private QName serviceName = null; private String wsdlLocation = null; private javax.wsdl.Service wsdlService = null; private boolean maintainSession = false; private HandlerRegistryImpl registry = new HandlerRegistryImpl(); private Parser wsdlParser = null; private static Map cachedWSDL = new WeakHashMap(); private static boolean cachingWSDL = true; /** * A Hashtable mapping addresses (URLs) to Transports (objects) */ private Hashtable transportImpls = new Hashtable(); protected javax.wsdl.Service getWSDLService() { return (wsdlService); } public Parser getWSDLParser() { return (wsdlParser); } protected AxisClient getAxisClient() { return new AxisClient(getEngineConfiguration()); } /** * Constructs a new Service object - this assumes the caller will set * the appropriate fields by hand rather than getting them from the * WSDL. */ public Service() { engine = getAxisClient(); } /** * Constructs a new Service object - this assumes the caller will set * the appropriate fields by hand rather than getting them from the * WSDL. */ public Service(QName serviceName) { this.serviceName = serviceName; engine = getAxisClient(); } /** * Constructs a Service using the supplied configuration and engine directly. * * @param engineConfiguration * @param axisClient */ public Service(EngineConfiguration engineConfiguration, AxisClient axisClient) { this.config = engineConfiguration; this.engine = axisClient; } /** * Constructs a new Service object as above, but also passing in * the EngineConfiguration which should be used to set up the * AxisClient. */ public Service(EngineConfiguration config) { this.config = config; engine = getAxisClient(); } /** * Constructs a new Service object for the service in the WSDL document * pointed to by the wsdlDoc URL and serviceName parameters. * * @param wsdlDoc URL of the WSDL document * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ public Service(URL wsdlDoc, QName serviceName) throws ServiceException { this.serviceName = serviceName; engine = getAxisClient(); wsdlLocation = wsdlDoc.toString(); Parser parser = null; if (cachingWSDL && (parser = (Parser) cachedWSDL.get(this.wsdlLocation.toString())) != null) { initService(parser, serviceName); } else { initService(wsdlDoc.toString(), serviceName); } } /** * Constructs a new Service object for the service in the WSDL document * * @param parser Parser for this service * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error */ public Service(Parser parser, QName serviceName) throws ServiceException { this.serviceName = serviceName; engine = getAxisClient(); initService(parser, serviceName); } /** * Constructs a new Service object for the service in the WSDL document * pointed to by the wsdlLocation and serviceName parameters. This is * just like the previous constructor but instead of URL the * wsdlLocation parameter points to a file on the filesystem relative * to the current directory. * * @param wsdlLocation Location of the WSDL relative to the current dir * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ public Service(String wsdlLocation, QName serviceName) throws ServiceException { this.serviceName = serviceName; this.wsdlLocation = wsdlLocation; engine = getAxisClient(); // Start by reading in the WSDL using Parser Parser parser = null; if (cachingWSDL && (parser = (Parser) cachedWSDL.get(wsdlLocation)) != null) { initService(parser, serviceName); } else { initService(wsdlLocation, serviceName); } } /** * Constructs a new Service object for the service in the WSDL document * in the wsdlInputStream and serviceName parameters. This is * just like the previous constructor but instead of reading the WSDL * from a file (or from a URL) it is in the passed in InputStream. * * @param wsdlInputStream InputStream containing the WSDL * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ public Service(InputStream wsdlInputStream, QName serviceName) throws ServiceException { engine = getAxisClient(); Document doc = null; try { doc = XMLUtils.newDocument(wsdlInputStream); } catch (Exception exp) { throw new ServiceException( Messages.getMessage("wsdlError00", "" + "", "\n" + exp)); } initService(null, doc, serviceName); } /** * Common code for building up the Service from a WSDL document * * @param url URL for the WSDL document * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ private void initService(String url, QName serviceName) throws ServiceException { try { // Start by reading in the WSDL using Parser Parser parser = new Parser(); parser.run(url); if (cachingWSDL && this.wsdlLocation != null) cachedWSDL.put(url, parser); initService(parser, serviceName); } catch (Exception exp) { throw new ServiceException( Messages.getMessage("wsdlError00", "" + "", "\n" + exp), exp); } } /** * Common code for building up the Service from a WSDL document * * @param context Context URL * @param doc A DOM document containing WSDL * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ private void initService(String context, Document doc, QName serviceName) throws ServiceException { try { // Start by reading in the WSDL using Parser Parser parser = new Parser(); parser.run(context, doc); initService(parser, serviceName); } catch (Exception exp) { throw new ServiceException( Messages.getMessage("wsdlError00", "" + "", "\n" + exp)); } } /** * Code for building up the Service from a Parser * * @param parser Parser for this service * @param serviceName Qualified name of the desired service * @throws ServiceException If there's an error finding or parsing the WSDL */ private void initService(Parser parser, QName serviceName) throws ServiceException { try { this.wsdlParser = parser; ServiceEntry serviceEntry = parser.getSymbolTable().getServiceEntry(serviceName); if (serviceEntry != null) this.wsdlService = serviceEntry.getService(); if (this.wsdlService == null) throw new ServiceException( Messages.getMessage("noService00", "" + serviceName)); } catch (Exception exp) { throw new ServiceException( Messages.getMessage("wsdlError00", "" + "", "\n" + exp)); } } /** * Return either an instance of a generated stub, if it can be * found, or a dynamic proxy for the given proxy interface. * * @param portName The name of the service port * @param proxyInterface The Remote object returned by this * method will also implement the given proxyInterface * @return java.rmi.Remote The stub implementation. * @throws ServiceException If there's an error */ public Remote getPort(QName portName, Class proxyInterface) throws ServiceException { if (wsdlService == null) throw new ServiceException(Messages.getMessage("wsdlMissing00")); Port port = wsdlService.getPort(portName.getLocalPart()); if (port == null) throw new ServiceException(Messages.getMessage("noPort00", "" + portName)); // First, try to find a generated stub. If that // returns null, then find a dynamic stub. Remote stub = getGeneratedStub(portName, proxyInterface); return stub != null ? stub : getPort(null, portName, proxyInterface); } /** * With the proxyInterface and the service's portName, we have * ALMOST enough info to find a generated stub. The generated * stub is named after the binding, which we can get from the * service's port. This binding is likely in the same namespace * (ie, package) that the proxyInterface is in. So try to find * and instantiate <proxyInterfacePackage>.<bindingName>Stub. * If it doesn't exist, return null. */ private Remote getGeneratedStub(QName portName, Class proxyInterface) { try { String pkg = proxyInterface.getName(); pkg = pkg.substring(0, pkg.lastIndexOf('.')); Port port = wsdlService.getPort(portName.getLocalPart()); String binding = port.getBinding().getQName().getLocalPart(); Class stubClass = ClassUtils.forName( pkg + "." + binding + "Stub"); if (proxyInterface.isAssignableFrom(stubClass)) { Class[] formalArgs = {javax.xml.rpc.Service.class}; Object[] actualArgs = {this}; Constructor ctor = stubClass.getConstructor(formalArgs); Stub stub = (Stub) ctor.newInstance(actualArgs); stub._setProperty( Stub.ENDPOINT_ADDRESS_PROPERTY, WSDLUtils.getAddressFromPort(port)); stub.setPortName(portName); return (Remote) stub; } else { return null; } } catch (Throwable t) { return null; } } // getGeneratedStub /** * Return a dynamic proxy for the given proxy interface. * * @param proxyInterface The Remote object returned by this * method will also implement the given proxyInterface * @return java.rmi.Remote The stub implementation * @throws ServiceException If there's an error */ public Remote getPort(Class proxyInterface) throws ServiceException { if (wsdlService == null) throw new ServiceException(Messages.getMessage("wsdlMissing00")); Map ports = wsdlService.getPorts(); if (ports == null || ports.size() <= 0) throw new ServiceException(Messages.getMessage("noPort00", "")); // Get the name of the class (without package name) String clazzName = proxyInterface.getName(); if(clazzName.lastIndexOf('.')!=-1) { clazzName = clazzName.substring(clazzName.lastIndexOf('.')+1); } // Pick the port with the same name as the class Port port = (Port) ports.get(clazzName); if(port == null) { // If not found, just pick the first port. port = (Port) ports.values().iterator().next(); } // First, try to find a generated stub. If that // returns null, then find a dynamic stub. Remote stub = getGeneratedStub(new QName(port.getName()), proxyInterface); return stub != null ? stub : getPort(null, new QName(port.getName()), proxyInterface); } /** * Return an object which acts as a dynamic proxy for the passed * interface class. This is a more "dynamic" version in that it * doesn't actually require WSDL, simply an endpoint address. * * Note: Not part of the JAX-RPC spec. * * @param endpoint the URL which will be used as the SOAP endpoint * @param proxyInterface the interface class which we wish to mimic * via a dynamic proxy * @throws ServiceException */ public Remote getPort(String endpoint, Class proxyInterface) throws ServiceException { return getPort(endpoint, null, proxyInterface); } private Remote getPort(String endpoint, QName portName, Class proxyInterface) throws ServiceException { if (!proxyInterface.isInterface()) { throw new ServiceException(Messages.getMessage("mustBeIface00")); } if (!(Remote.class.isAssignableFrom(proxyInterface))) { throw new ServiceException( Messages.getMessage("mustExtendRemote00")); } // Validate the proxyInterface if (wsdlParser != null) { Port port = wsdlService.getPort(portName.getLocalPart()); if (port == null) throw new ServiceException(Messages.getMessage("noPort00", "" + proxyInterface.getName())); Binding binding = port.getBinding(); SymbolTable symbolTable = wsdlParser.getSymbolTable(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); if(bEntry.getParameters().size() != proxyInterface.getMethods().length) { throw new ServiceException(Messages.getMessage("incompatibleSEI00", "" + proxyInterface.getName())); } // TODO: Check the methods and the parameters as well. } try { Call call = null; if (portName == null) { call = (org.apache.axis.client.Call) createCall(); if (endpoint != null) { call.setTargetEndpointAddress(new URL(endpoint)); } } else { call = (org.apache.axis.client.Call) createCall(portName); } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); javax.xml.rpc.Stub stub = (javax.xml.rpc.Stub) Proxy.newProxyInstance(classLoader, new Class[]{proxyInterface, javax.xml.rpc.Stub.class}, new AxisClientProxy(call, portName)); if(stub instanceof org.apache.axis.client.Stub){ ((org.apache.axis.client.Stub) stub).setPortName(portName); } return (Remote) stub; } catch (Exception e) { throw new ServiceException( Messages.getMessage("wsdlError00", "" + "", "\n" + e)); } } // getPort /** * Creates a new Call object - will prefill as much info from the WSDL * as it can. Right now it's just the target URL of the Web Service. * * @param portName PortName in the WSDL doc to search for * @return Call Used for invoking the Web Service * @throws ServiceException If there's an error */ public javax.xml.rpc.Call createCall(QName portName) throws ServiceException { Call call = (org.apache.axis.client.Call) createCall(); call.setPortName(portName); // We can't prefill information if WSDL is not specified, // So just return the call that we just created. if (wsdlParser == null) return call; Port port = wsdlService.getPort(portName.getLocalPart()); if (port == null) throw new ServiceException(Messages.getMessage("noPort00", "" + portName)); Binding binding = port.getBinding(); PortType portType = binding.getPortType(); if (portType == null) throw new ServiceException(Messages.getMessage("noPortType00", "" + portName)); // Get the URL //////////////////////////////////////////////////////////////////// List list = port.getExtensibilityElements(); for (int i = 0; list != null && i < list.size(); i++) { Object obj = list.get(i); if (obj instanceof SOAPAddress) { try { SOAPAddress addr = (SOAPAddress) obj; URL url = new URL(addr.getLocationURI()); call.setTargetEndpointAddress(url); } catch (Exception exp) { throw new ServiceException( Messages.getMessage("cantSetURI00", "" + exp)); } } } return (call); } /** * Creates a new Call object - will prefill as much info from the WSDL * as it can. Right now it's target URL, SOAPAction, Parameter types, * and return type of the Web Service. * * @param portName PortName in the WSDL doc to search for * @param operationName Operation(method) that's going to be invoked * @return Call Used for invoking the Web Service * @throws ServiceException If there's an error */ public javax.xml.rpc.Call createCall(QName portName, String operationName) throws ServiceException { Call call = (org.apache.axis.client.Call) createCall(); call.setOperation(portName, operationName); return (call); } /** * Creates a new Call object - will prefill as much info from the WSDL * as it can. Right now it's target URL, SOAPAction, Parameter types, * and return type of the Web Service. * * @param portName PortName in the WSDL doc to search for * @param operationName Operation(method) that's going to be invoked * @return Call Used for invoking the Web Service * @throws ServiceException If there's an error */ public javax.xml.rpc.Call createCall(QName portName, QName operationName) throws ServiceException { Call call = (org.apache.axis.client.Call) createCall(); call.setOperation(portName, operationName); return (call); } /** * Creates a new Call object with no prefilled data. This assumes * that the caller will set everything manually - no checking of * any kind will be done against the WSDL. * * @return Call Used for invoking the Web Service * @throws ServiceException If there's an error */ public javax.xml.rpc.Call createCall() throws ServiceException { return new org.apache.axis.client.Call(this); } /** * Gets an array of preconfigured Call objects for invoking operations * on the specified port. There is one Call object per operation that * can be invoked on the specified port. Each Call object is * pre-configured and does not need to be configured using the setter * methods on Call interface. * * This method requires the Service implementation class to have access * to the WSDL related metadata. * * @throws ServiceException - If this Service class does not have access * to the required WSDL metadata or if an illegal portName is specified. */ public javax.xml.rpc.Call[] getCalls(QName portName) throws ServiceException { if (portName == null) throw new ServiceException(Messages.getMessage("badPort00")); if (wsdlService == null) throw new ServiceException(Messages.getMessage("wsdlMissing00")); Port port = wsdlService.getPort(portName.getLocalPart()); if (port == null) throw new ServiceException(Messages.getMessage("noPort00", "" + portName)); Binding binding = port.getBinding(); SymbolTable symbolTable = wsdlParser.getSymbolTable(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); Iterator i = bEntry.getParameters().keySet().iterator(); Vector calls = new Vector(); while (i.hasNext()) { Operation operation = (Operation) i.next(); javax.xml.rpc.Call call = createCall(QName.valueOf(port.getName()), QName.valueOf(operation.getName())); calls.add(call); } javax.xml.rpc.Call[] array = new javax.xml.rpc.Call[calls.size()]; calls.toArray(array); return array; } /** * Returns the configured HandlerRegistry instance for this Service * instance. * * NOTE: This Service currently does not support the configuration * of a HandlerRegistry! It will throw a * java.lang.UnsupportedOperationException. * * @return HandlerRegistry * @throws java.lang.UnsupportedOperationException - if the Service * class does not support the configuration of a * HandlerRegistry. */ public HandlerRegistry getHandlerRegistry() { return registry; } /** * Returns the location of the WSDL document used to prefill the data * (if one was used at all). * * @return URL URL pointing to the WSDL doc */ public URL getWSDLDocumentLocation() { try { return new URL(wsdlLocation); } catch (MalformedURLException e) { return null; } } /** * Returns the qualified name of the service (if one is set). * * @return QName Fully qualified name of this service. */ public QName getServiceName() { if (serviceName != null) return serviceName; if (wsdlService == null) return (null); QName qn = wsdlService.getQName(); return (new QName(qn.getNamespaceURI(), qn.getLocalPart())); } /** * Returns an <code>Iterator</code> for the list of * <code>QName</code>s of service endpoints grouped by this * service * * @return Returns <code>java.util.Iterator</code> with elements * of type <code>javax.xml.namespace.QName</code> * @throws ServiceException If this Service class does not * have access to the required WSDL metadata */ public Iterator getPorts() throws ServiceException { if (wsdlService == null) throw new ServiceException(Messages.getMessage("wsdlMissing00")); if (wsdlService.getPorts() == null) { // Return an empty iterator; return new Vector().iterator(); } Map portmap = wsdlService.getPorts(); List portlist = new java.util.ArrayList(portmap.size()); // we could simply iterate over keys instead and skip // the lookup, but while keys are probably the same as // port names, the documentation does not make any // guarantee on this, so we'll just play it safe // Aaron Hamid Iterator portiterator = portmap.values().iterator(); while (portiterator.hasNext()) { Port port = (Port) portiterator.next(); // maybe we should use Definition.getTargetNamespace() here, // but this class does not hold a reference to the object, // so we'll just use the namespace of the service's QName // (it should all be the same wsdl targetnamespace value, right?) // Aaron Hamid portlist.add(new QName(wsdlService.getQName().getNamespaceURI(), port.getName())); } // ok, return the real list of QNames return portlist.iterator(); } /** * Defines the current Type Mappig Registry. * * @param registry The TypeMappingRegistry * @throws ServiceException if there's an error */ public void setTypeMappingRegistry(TypeMappingRegistry registry) throws ServiceException { } /** * Returns the current TypeMappingRegistry or null. * * @return TypeMappingRegistry The registry */ public TypeMappingRegistry getTypeMappingRegistry() { return (engine.getTypeMappingRegistry()); } /** * Returns a reference to this object. * * @return Reference ... */ public Reference getReference() { String classname = this.getClass().getName(); Reference reference = new Reference(classname, "org.apache.axis.client.ServiceFactory", null); StringRefAddr addr = null; if (!classname.equals("org.apache.axis.client.Service")) { // This is a generated derived class. Don't bother with // all the Service instance variables. addr = new StringRefAddr( ServiceFactory.SERVICE_CLASSNAME, classname); reference.add(addr); } else { if (wsdlLocation != null) { addr = new StringRefAddr( ServiceFactory.WSDL_LOCATION, wsdlLocation.toString()); reference.add(addr); } QName serviceName = getServiceName(); if (serviceName != null) { addr = new StringRefAddr(ServiceFactory.SERVICE_NAMESPACE, serviceName.getNamespaceURI()); reference.add(addr); addr = new StringRefAddr(ServiceFactory.SERVICE_LOCAL_PART, serviceName.getLocalPart()); reference.add(addr); } } if (maintainSession) { addr = new StringRefAddr(ServiceFactory.MAINTAIN_SESSION, "true"); reference.add(addr); } return reference; } /** * Sets this Service's AxisEngine. This engine will be shared by all * Call objects created from this Service object. * * Note: Not part of the JAX-RPC spec. * * @param engine Sets this Service's AxisEngine to the passed in one */ public void setEngine(AxisEngine engine) { this.engine = engine; } /** * Returns the current AxisEngine used by this Service and all of the * Call objects created from this Service object. * * Note: Not part of the JAX-RPC spec. * * @return AxisEngine the engine */ public AxisEngine getEngine() { return (engine); } /** * Set this Service's engine configuration. * * Note that since all of the constructors create the AxisClient right * now, this is basically a no-op. Putting it in now so that we can make * lazy engine instantiation work, and not have to duplicate every single * Service constructor with a EngineConfiguration argument. * <p> * If you need to use a non-default <code>EngineConfiguration</code>, do * the following before calling the Service constructor:<p><code> * * AxisProperties.setProperty(EngineConfigurationFactory.SYSTEM_PROPERTY_NAME, * "classname.of.new.EngineConfigurationFactory"); * </code><p> * Where the second parameter is the name of your new class that implements * <code>EngineConfigurationFactory</code> and a<code><br> * public static EngineConfigurationFactory newFactory(Object param) * </code> * method. See <code>EngineConfigurationFactoryDefault</code> for an example * of how to do this.<p> * * This way, when the Service class constructor calls<br><code> * * EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig() * </code> * the getClientEngineConfig() of your own EngineConfigurationFactory will be * called, and your configuration will be used in the constructed Service object.<p> * * Another way is to use the "discovery" method of * <code>EngineConfigurationFactoryFinder</code>. * * @param config the EngineConfiguration we want to use. */ public void setEngineConfiguration(EngineConfiguration config) { this.config = config; } /** * Constructs a EngineConfig if one is not available. */ protected EngineConfiguration getEngineConfiguration() { if (this.config == null) { this.config = EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig(); } return config; } /** * Determine whether we'd like to track sessions or not. * This information is passed to all Call objects created * from this service. Calling setMaintainSession will * only affect future instantiations of the Call object, * not those that already exist. * * Note: Not part of JAX-RPC specification. * * @param yesno true if session state is desired, false if not. */ public void setMaintainSession(boolean yesno) { maintainSession = yesno; } /** * If true, this service wants to track sessions. */ public boolean getMaintainSession() { return maintainSession; } /** * Tells whether or not we're caching WSDL */ public boolean getCacheWSDL() { return cachingWSDL; } /** * Allows users to turn caching of WSDL documents on or off. * Default is 'true' (on). */ public void setCacheWSDL(boolean flag) { cachingWSDL = flag; } protected static class HandlerRegistryImpl implements HandlerRegistry { Map map = new HashMap(); public List getHandlerChain(QName portName) { // namespace is not significant, so use local part directly String key = portName.getLocalPart(); List list = (List) map.get(key); if (list == null) { list = new java.util.ArrayList(); setHandlerChain(portName, list); } return list; } public void setHandlerChain(QName portName, List chain) { // namespace is not significant, so use local part directly map.put(portName.getLocalPart(), chain); } } /** * Register a Transport for a particular URL. */ void registerTransportForURL(URL url, Transport transport) { transportImpls.put(url.toString(), transport); } /** * Get any registered Transport object for a given URL. */ Transport getTransportForURL(URL url) { return (Transport) transportImpls.get(url.toString()); } /** * Set the typemapping version * @param version */ public void setTypeMappingVersion(String version) { ((TypeMappingRegistryImpl)getTypeMappingRegistry()).doRegisterFromVersion(version); } }
7,798
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/async/IAsyncResult.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.client.async; /** * Access the results of the Async call * * @author Davanum Srinivas (dims@yahoo.com) */ public interface IAsyncResult { /** * Method abort */ public void abort(); /** * Method getStatus * * @return */ public Status getStatus(); /** * Method waitFor * * @param timeout * @throws InterruptedException */ public void waitFor(long timeout) throws InterruptedException; /** * Method getResponse * * @return */ public Object getResponse(); /** * Method getException * * @return */ public Throwable getException(); }
7,799