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 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Month.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.
*/
package org.apache.axis.types;
import org.apache.axis.utils.Messages;
import java.text.NumberFormat;
/**
* Implementation of the XML Schema type gMonth
*
* @author Tom Jordahl (tomj@macromedia.com)
* @see <a href="http://www.w3.org/TR/xmlschema-2/#gMonth">XML Schema 3.2.14</a>
*/
public class Month implements java.io.Serializable {
int month;
String timezone = null;
/**
* Constructs a Month with the given values
* No timezone is specified
*/
public Month(int month) throws NumberFormatException {
setValue(month);
}
/**
* Constructs a Month with the given values, including a timezone string
* The timezone is validated but not used.
*/
public Month(int month, String timezone)
throws NumberFormatException {
setValue(month, timezone);
}
/**
* Construct a Month from a String in the format --MM--[timezone]
*/
public Month(String source) throws NumberFormatException {
if (source.length() < (6)) {
throw new NumberFormatException(
Messages.getMessage("badMonth00"));
}
if (source.charAt(0) != '-' ||
source.charAt(1) != '-' ||
source.charAt(4) != '-' ||
source.charAt(5) != '-' ) {
throw new NumberFormatException(
Messages.getMessage("badMonth00"));
}
setValue(Integer.parseInt(source.substring(2,4)),
source.substring(6));
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
// validate month
if (month < 1 || month > 12) {
throw new NumberFormatException(
Messages.getMessage("badMonth00"));
}
this.month = month;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
// validate timezone
if (timezone != null && timezone.length() > 0) {
// Format [+/-]HH:MM
if (timezone.charAt(0)=='+' || (timezone.charAt(0)=='-')) {
if (timezone.length() != 6 ||
!Character.isDigit(timezone.charAt(1)) ||
!Character.isDigit(timezone.charAt(2)) ||
timezone.charAt(3) != ':' ||
!Character.isDigit(timezone.charAt(4)) ||
!Character.isDigit(timezone.charAt(5)))
throw new NumberFormatException(
Messages.getMessage("badTimezone00"));
} else if (!timezone.equals("Z")) {
throw new NumberFormatException(
Messages.getMessage("badTimezone00"));
}
// if we got this far, its good
this.timezone = timezone;
}
}
public void setValue(int month, String timezone) throws NumberFormatException {
setMonth(month);
setTimezone(timezone);
}
public void setValue(int month) throws NumberFormatException {
setMonth(month);
}
public String toString() {
// use NumberFormat to ensure leading zeros
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
// month
nf.setMinimumIntegerDigits(2);
String s = "--" + nf.format(month) + "--";
// timezone
if (timezone != null) {
s = s + timezone;
}
return s;
}
public boolean equals(Object obj) {
if (!(obj instanceof Month)) return false;
Month other = (Month) obj;
if (obj == null) return false;
if (this == obj) return true;
boolean equals = (this.month == other.month);
if (timezone != null) {
equals = equals && timezone.equals(other.timezone);
}
return equals;
}
/**
* Return the value of month XORed with the hashCode of timezone
* iff one is defined.
*
* @return an <code>int</code> value
*/
public int hashCode() {
return null == timezone ? month : month ^ timezone.hashCode();
}
}
| 7,400 |
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/types/Notation.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.types;
import org.apache.axis.Constants;
import org.apache.axis.description.AttributeDesc;
import org.apache.axis.description.ElementDesc;
import org.apache.axis.description.FieldDesc;
import org.apache.axis.description.TypeDesc;
/**
* Custom class for supporting XSD data type NOTATION.
*
* @author Davanum Srinivas (dims@yahoo.com)
* @see <a href="http://www.w3.org/TR/xmlschema-1/#element-notation">XML Schema Part 1: 3.12 Notation Declarations</a>
*/
public class Notation implements java.io.Serializable {
NCName name;
URI publicURI;
URI systemURI;
public Notation() {
}
public Notation(NCName name, URI publicURI, URI systemURI) {
this.name = name;
this.publicURI = publicURI;
this.systemURI = systemURI;
}
public NCName getName() {
return name;
}
public void setName(NCName name) {
this.name = name;
}
public URI getPublic() {
return publicURI;
}
public void setPublic(URI publicURI) {
this.publicURI = publicURI;
}
public URI getSystem() {
return systemURI;
}
public void setSystem(URI systemURI) {
this.systemURI = systemURI;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Notation))
return false;
Notation other = (Notation) obj;
if (name == null) {
if (other.getName() != null) {
return false;
}
} else if (!name.equals(other.getName())) {
return false;
}
if (publicURI == null) {
if (other.getPublic() != null) {
return false;
}
} else if (!publicURI.equals(other.getPublic())) {
return false;
}
if (systemURI == null) {
if (other.getSystem() != null) {
return false;
}
} else if (!systemURI.equals(other.getSystem())) {
return false;
}
return true;
}
/**
* Returns the sum of the hashcodes of {name,publicURI,systemURI}
* for whichever properties in that set is non null. This is
* consistent with the implementation of equals, as required by
* {@link java.lang.Object#hashCode() Object.hashCode}.
*
* @return an <code>int</code> value
*/
public int hashCode() {
int hash = 0;
if (null != name) {
hash += name.hashCode();
}
if (null != publicURI) {
hash += publicURI.hashCode();
}
if (null != systemURI) {
hash += systemURI.hashCode();
}
return hash;
}
// Type metadata
private static TypeDesc typeDesc;
static {
typeDesc = new TypeDesc(Notation.class);
FieldDesc field;
// An attribute with a specified QName
field = new AttributeDesc();
field.setFieldName("name");
field.setXmlName(Constants.XSD_NCNAME);
typeDesc.addFieldDesc(field);
// An attribute with a default QName
field = new AttributeDesc();
field.setFieldName("public");
field.setXmlName(Constants.XSD_ANYURI);
typeDesc.addFieldDesc(field);
// An element with a specified QName
ElementDesc element = null;
element = new ElementDesc();
element.setFieldName("system");
element.setXmlName(Constants.XSD_ANYURI);
// per, http://www.w3.org/TR/xmlschema-1/#element-notation,
// "system" property can be null
element.setNillable(true);
typeDesc.addFieldDesc(field);
}
public static TypeDesc getTypeDesc() {
return typeDesc;
}
}
| 7,401 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/java/JavaSender.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.transport.java;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.constants.Scope;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.providers.java.MsgProvider;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.commons.logging.Log;
public class JavaSender extends BasicHandler {
protected static Log log =
LogFactory.getLog(JavaSender.class.getName());
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Enter: JavaSender::invoke");
}
SOAPService service = null ;
SOAPService saveService = msgContext.getService();
OperationDesc saveOp = msgContext.getOperation();
Call call = (Call) msgContext.getProperty( MessageContext.CALL );
String url = call.getTargetEndpointAddress();
String cls = url.substring(5);
msgContext.setService( null );
msgContext.setOperation( null );
if ( msgContext.getProperty(MessageContext.IS_MSG) == null )
service = new SOAPService(new RPCProvider());
else
service = new SOAPService(new MsgProvider());
if ( cls.startsWith("//") ) cls = cls.substring(2);
service.setOption(RPCProvider.OPTION_CLASSNAME, cls);
service.setEngine(msgContext.getAxisEngine());
service.setOption( RPCProvider.OPTION_ALLOWEDMETHODS, "*" );
service.setOption( RPCProvider.OPTION_SCOPE, Scope.DEFAULT.getName());
service.getInitializedServiceDesc( msgContext );
service.init();
msgContext.setService( service );
service.invoke( msgContext );
msgContext.setService( saveService );
msgContext.setOperation( saveOp );
if (log.isDebugEnabled()) {
log.debug("Exit: JavaSender::invoke");
}
}
}
| 7,402 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/java/Handler.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.transport.java;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* A stub URLStreamHandler, so the system will recognize our
* custom URLs as valid.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class Handler extends URLStreamHandler
{
protected URLConnection openConnection(URL u)
{
return null;
}
}
| 7,403 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/java/JavaTransport.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.transport.java;
import org.apache.axis.AxisEngine;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Transport;
/**
* A Transport which will cause an invocation via "java"
*
* @author Doug Davis (dug@us.ibm.com)
*/
public class JavaTransport extends Transport
{
public JavaTransport()
{
transportName = "java";
}
/**
* Set up any transport-specific derived properties in the message context.
* @param mc the context to set up
* @param call the Call object
* @param engine the engine containing the registries
*/
public void setupMessageContextImpl(MessageContext mc,
Call call,
AxisEngine engine)
{
}
}
| 7,404 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/local/LocalTransport.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.transport.local;
import org.apache.axis.AxisEngine;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Transport;
import org.apache.axis.server.AxisServer;
/**
* A Transport which will cause an invocation via a "local" AxisServer.
*
* Serialization will still be tested, as the requests and responses
* pass through a String conversion (see LocalSender.java) - this is
* primarily for testing and debugging.
*
* This transport will either allow the LocalSender to create its own
* AxisServer, or if you have one you've configured and wish to use,
* you may pass it in to the constructor here.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@allaire.com)
*/
public class LocalTransport extends Transport
{
public static final String LOCAL_SERVER = "LocalTransport.AxisServer";
public static final String REMOTE_SERVICE = "LocalTransport.RemoteService";
private AxisServer server;
/** The name of a particular remote service to invoke. */
private String remoteServiceName;
/** No-arg constructor, which will use an AxisServer constructed
* by the LocalSender (see LocalSender.java).
*
*/
public LocalTransport()
{
transportName = "local";
}
/** Use this constructor if you have a particular server kicking
* around (perhaps which you've already deployed useful stuff into)
* which you'd like to use.
*
* @param server an AxisServer which will bubble down to the LocalSender
*/
public LocalTransport(AxisServer server)
{
transportName = "local";
this.server = server;
}
/**
* Use this to indicate a particular "remote" service which should be
* invoked on the target AxisServer. This can be used programatically
* in place of a service-specific URL.
*
* @param remoteServiceName the name of the remote service to invoke
*/
public void setRemoteService(String remoteServiceName) {
this.remoteServiceName = remoteServiceName;
}
/**
* Set up any transport-specific derived properties in the message context.
* @param mc the context to set up
* @param call the client service instance
* @param engine the engine containing the registries
*/
public void setupMessageContextImpl(MessageContext mc,
Call call,
AxisEngine engine)
{
if (server != null)
mc.setProperty(LOCAL_SERVER, server);
if (remoteServiceName != null)
mc.setProperty(REMOTE_SERVICE, remoteServiceName);
}
}
| 7,405 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/local/Handler.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.transport.local;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* A stub URLStreamHandler, so the system will recognize our
* custom URLs as valid.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class Handler extends URLStreamHandler
{
protected URLConnection openConnection(URL u)
{
return null;
}
}
| 7,406 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/local/LocalResponder.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.transport.local;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.commons.logging.Log;
/**
* Tiny Handler which just makes sure to Stringize the outgoing
* Message to appropriately use serializers on the server side.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class LocalResponder extends BasicHandler {
protected static Log log =
LogFactory.getLog(LocalResponder.class.getName());
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Enter: LocalResponder::invoke");
}
String msgStr = msgContext.getResponseMessage().getSOAPPartAsString();
if (log.isDebugEnabled()) {
log.debug(msgStr);
log.debug("Exit: LocalResponder::invoke");
}
}
}
| 7,407 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/local/LocalSender.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.transport.local;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.attachments.Attachments;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPFault;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import java.net.URL;
/**
* This is meant to be used on a SOAP Client to call a SOAP server.
*
* @author Sam Ruby (rubys@us.ibm.com)
*/
public class LocalSender extends BasicHandler {
protected static Log log =
LogFactory.getLog(LocalSender.class.getName());
private volatile AxisServer server;
/**
* Allocate an embedded Axis server to process requests and initialize it.
*/
public synchronized void init() {
this.server= new AxisServer();
}
public void invoke(MessageContext clientContext) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Enter: LocalSender::invoke");
}
AxisServer targetServer =
(AxisServer)clientContext.getProperty(LocalTransport.LOCAL_SERVER);
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("usingServer00",
"LocalSender", "" + targetServer));
}
if (targetServer == null) {
// This should have already been done, but it doesn't appear to be
// something that can be relied on. Oh, well...
if (server == null) init();
targetServer = server;
}
// Define a new messageContext per request
MessageContext serverContext = new MessageContext(targetServer);
// copy the request, and force its format to String in order to
// exercise the serializers.
// START FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=17161
Message clientRequest = clientContext.getRequestMessage();
String msgStr = clientRequest.getSOAPPartAsString();
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("sendingXML00", "LocalSender"));
log.debug(msgStr);
}
Message serverRequest = new Message(msgStr);
Attachments serverAttachments = serverRequest.getAttachmentsImpl();
Attachments clientAttachments = clientRequest.getAttachmentsImpl();
if (null != clientAttachments && null != serverAttachments) {
serverAttachments.setAttachmentParts(clientAttachments.getAttachments());
}
serverContext.setRequestMessage(serverRequest);
// END FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=17161
serverContext.setTransportName("local");
// Also copy authentication info if present
String user = clientContext.getUsername();
if (user != null) {
serverContext.setUsername(user);
String pass = clientContext.getPassword();
if (pass != null)
serverContext.setPassword(pass);
}
// set the realpath if possible
String transURL = clientContext.getStrProp(MessageContext.TRANS_URL);
if (transURL != null) {
try {
URL url = new URL(transURL);
String file = url.getFile();
if (file.length()>0 && file.charAt(0)=='/') {
file = file.substring(1);
}
serverContext.setProperty(Constants.MC_REALPATH, file);
serverContext.setProperty(MessageContext.TRANS_URL,
"local:///" + file);
// This enables "local:///AdminService" and the like to work.
serverContext.setTargetService(file);
} catch (Exception e) {
throw AxisFault.makeFault(e);
}
}
// If we've been given an explicit "remote" service to invoke,
// use it. (Note that right now this overrides the setting above;
// is this the correct precedence?)
String remoteService = clientContext.getStrProp(LocalTransport.REMOTE_SERVICE);
if (remoteService != null)
serverContext.setTargetService(remoteService);
// invoke the request
try {
targetServer.invoke(serverContext);
} catch (AxisFault fault) {
Message respMsg = serverContext.getResponseMessage();
if (respMsg == null) {
respMsg = new Message(fault);
serverContext.setResponseMessage(respMsg);
} else {
SOAPFault faultEl = new SOAPFault(fault);
SOAPEnvelope env = respMsg.getSOAPEnvelope();
env.clearBody();
env.addBodyElement(faultEl);
}
}
// copy back the response, and force its format to String in order to
// exercise the deserializers.
clientContext.setResponseMessage(serverContext.getResponseMessage());
clientContext.getResponseMessage().getSOAPPartAsString();
if (log.isDebugEnabled()) {
log.debug("Exit: LocalSender::invoke");
}
}
}
| 7,408 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/HTTPConstants.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.transport.http;
/**
* HTTP protocol and message context constants.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Jacek Kopecky (jacek@idoox.com)
*/
public class HTTPConstants {
/** The MessageContext transport ID of HTTP.
* (Maybe this should be more specific, like "http_servlet",
* whaddya think? - todo by Jacek)
*/
public static final String HEADER_PROTOCOL_10 = "HTTP/1.0";
public static final String HEADER_PROTOCOL_11 = "HTTP/1.1";
public static final String HEADER_PROTOCOL_V10 = "1.0".intern();
public static final String HEADER_PROTOCOL_V11 = "1.1".intern();
public static final String HEADER_POST = "POST";
public static final String HEADER_HOST = "Host";
public static final String HEADER_CONTENT_DESCRIPTION = "Content-Description";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
public static final String HEADER_CONTENT_TYPE_JMS = "ContentType";
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
public static final String HEADER_CONTENT_LOCATION = "Content-Location";
public static final String HEADER_CONTENT_ID = "Content-Id";
public static final String HEADER_SOAP_ACTION = "SOAPAction";
public static final String HEADER_AUTHORIZATION = "Authorization";
public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String HEADER_EXPECT = "Expect";
public static final String HEADER_EXPECT_100_Continue = "100-continue";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_CACHE_CONTROL_NOCACHE = "no-cache";
public static final String HEADER_PRAGMA = "Pragma";
public static final String HEADER_LOCATION = "Location";
public static final String REQUEST_HEADERS = "HTTP-Request-Headers";
public static final String RESPONSE_HEADERS = "HTTP-Response-Headers";
/*http 1.1*/
public static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding".intern();
public static final String HEADER_TRANSFER_ENCODING_CHUNKED = "chunked".intern();
public static final String HEADER_CONNECTION = "Connection";
public static final String HEADER_CONNECTION_CLOSE = "close".intern();
public static final String HEADER_CONNECTION_KEEPALIVE = "Keep-Alive".intern();//The default don't send.
public static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_TEXT_ALL = "text/*";
public static final String HEADER_ACCEPT_APPL_SOAP = "application/soap+xml";
public static final String HEADER_ACCEPT_MULTIPART_RELATED = "multipart/related";
public static final String HEADER_ACCEPT_APPLICATION_DIME = "application/dime";
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
public static final String COMPRESSION_GZIP = "gzip";
/**
* Cookie headers
*/
public static final String HEADER_COOKIE = "Cookie";
public static final String HEADER_COOKIE2 = "Cookie2";
public static final String HEADER_SET_COOKIE = "Set-Cookie";
public static final String HEADER_SET_COOKIE2 = "Set-Cookie2";
/** Integer
*/
public static String MC_HTTP_STATUS_CODE = "transport.http.statusCode";
/** String
*/
public static String MC_HTTP_STATUS_MESSAGE = "transport.http.statusMessage";
/** HttpServlet
*/
public static String MC_HTTP_SERVLET = "transport.http.servlet" ;
/** HttpServletRequest
*/
public static String MC_HTTP_SERVLETREQUEST = "transport.http.servletRequest";
/** HttpServletResponse
*/
public static String MC_HTTP_SERVLETRESPONSE= "transport.http.servletResponse";
public static String MC_HTTP_SERVLETLOCATION= "transport.http.servletLocation";
public static String MC_HTTP_SERVLETPATHINFO= "transport.http.servletPathInfo";
/**
* If you want the HTTP sender to indicate that it can accept a gziped
* response, set this message context property to true. The sender will
* automatically unzip the response if its gzipped.
*/
public static final String MC_ACCEPT_GZIP = "transport.http.acceptGzip";
/**
* by default the HTTP request body is not compressed. set this message
* context property to true to have the request body gzip compressed.
*/
public static final String MC_GZIP_REQUEST = "transport.http.gzipRequest";
/**
* @deprecated Should use javax.xml.rpc.Call.SOAPACTION_URI_PROPERTY instead.
*/
public static String MC_HTTP_SOAPACTION = javax.xml.rpc.Call.SOAPACTION_URI_PROPERTY;
/** HTTP header field values
*/
public static final String HEADER_DEFAULT_CHAR_ENCODING = "iso-8859-1";
/**
* AXIS servlet plugin parameter names.
*/
public static final String PLUGIN_NAME = "transport.http.plugin.pluginName";
public static final String PLUGIN_SERVICE_NAME = "transport.http.plugin.serviceName";
public static final String PLUGIN_IS_DEVELOPMENT = "transport.http.plugin.isDevelopment";
public static final String PLUGIN_ENABLE_LIST = "transport.http.plugin.enableList";
public static final String PLUGIN_ENGINE = "transport.http.plugin.engine";
public static final String PLUGIN_WRITER = "transport.http.plugin.writer";
public static final String PLUGIN_LOG = "transport.http.plugin.log";
public static final String PLUGIN_EXCEPTION_LOG = "transport.http.plugin.exceptionLog";
}
| 7,409 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/SocketHolder.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.transport.http;
import java.net.Socket;
/**
* hold a Socket.
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class SocketHolder {
/** Field value */
private Socket value = null;
public SocketHolder(Socket value) {
this.value = value;
}
public Socket getSocket() {
return value;
}
public void setSocket(Socket value) {
this.value = value;
}
}
| 7,410 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/FilterPrintWriter.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.transport.http;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* simple wrapper around PrintWriter class. It creates the PrintWriter
* object on demand, thus allowing to have a ResponseWriter class for
* structural reasons, while actually creating the writer on demand.
* This solves the problem of having to have a PrintWriter object available and being forced
* to set the contentType of the response object after creation.
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class FilterPrintWriter extends PrintWriter {
private PrintWriter _writer = null;
private HttpServletResponse _response = null;
private static OutputStream _sink = new NullOutputStream();
public FilterPrintWriter(HttpServletResponse aResponse) {
super(_sink);
_response = aResponse;
}
private PrintWriter getPrintWriter() {
if (_writer == null) {
try {
_writer = _response.getWriter();
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
return _writer;
}
public void write(int i) {
getPrintWriter().write(i);
}
public void write(char[] chars) {
getPrintWriter().write(chars);
}
public void write(char[] chars, int i, int i1) {
getPrintWriter().write(chars, i, i1);
}
public void write(String string) {
getPrintWriter().write(string);
}
public void write(String string, int i, int i1) {
getPrintWriter().write(string, i, i1);
}
public void flush() {
getPrintWriter().flush();
}
public void close() {
getPrintWriter().close();
}
public boolean checkError() {
return getPrintWriter().checkError();
}
public void print(boolean b) {
getPrintWriter().print(b);
}
public void print(char c) {
getPrintWriter().print(c);
}
public void print(int i) {
getPrintWriter().print(i);
}
public void print(long l) {
getPrintWriter().print(l);
}
public void print(float v) {
getPrintWriter().print(v);
}
public void print(double v) {
getPrintWriter().print(v);
}
public void print(char[] chars) {
getPrintWriter().print(chars);
}
public void print(String string) {
getPrintWriter().print(string);
}
public void print(Object object) {
getPrintWriter().print(object);
}
public void println() {
getPrintWriter().println();
}
public void println(boolean b) {
getPrintWriter().println(b);
}
public void println(char c) {
getPrintWriter().println(c);
}
public void println(int i) {
getPrintWriter().println(i);
}
public void println(long l) {
getPrintWriter().println(l);
}
public void println(float v) {
getPrintWriter().println(v);
}
public void println(double v) {
getPrintWriter().println(v);
}
public void println(char[] chars) {
getPrintWriter().println(chars);
}
public void println(String string) {
getPrintWriter().println(string);
}
public void println(Object object) {
getPrintWriter().println(object);
}
static public class NullOutputStream extends OutputStream {
public void write(int b) {
// no code -- no output
}
}
}
| 7,411 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/HTTPSender.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.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.Constants;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.components.net.BooleanHolder;
import org.apache.axis.components.net.SocketFactory;
import org.apache.axis.components.net.SocketFactoryFactory;
import org.apache.axis.components.net.DefaultSocketFactory;
import org.apache.axis.encoding.Base64;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.soap.SOAP12Constants;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.TeeOutputStream;
import org.apache.commons.logging.Log;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ArrayList;
/**
* This is meant to be used on a SOAP Client to call a SOAP server.
*
* @author Doug Davis (dug@us.ibm.com)
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class HTTPSender extends BasicHandler {
protected static Log log = LogFactory.getLog(HTTPSender.class.getName());
private static final String ACCEPT_HEADERS =
HTTPConstants.HEADER_ACCEPT + //Limit to the types that are meaningful to us.
": " +
HTTPConstants.HEADER_ACCEPT_APPL_SOAP +
", " +
HTTPConstants.HEADER_ACCEPT_APPLICATION_DIME +
", " +
HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED +
", " +
HTTPConstants.HEADER_ACCEPT_TEXT_ALL +
"\r\n" +
HTTPConstants.HEADER_USER_AGENT + //Tell who we are.
": " +
Messages.getMessage("axisUserAgent") +
"\r\n";
private static final String CACHE_HEADERS =
HTTPConstants.HEADER_CACHE_CONTROL + //Stop caching proxies from caching SOAP reqeuest.
": " +
HTTPConstants.HEADER_CACHE_CONTROL_NOCACHE +
"\r\n" +
HTTPConstants.HEADER_PRAGMA +
": " +
HTTPConstants.HEADER_CACHE_CONTROL_NOCACHE +
"\r\n";
private static final String CHUNKED_HEADER =
HTTPConstants.HEADER_TRANSFER_ENCODING +
": " +
HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED +
"\r\n";
private static final String HEADER_CONTENT_TYPE_LC =
HTTPConstants.HEADER_CONTENT_TYPE.toLowerCase();
private static final String HEADER_LOCATION_LC =
HTTPConstants.HEADER_LOCATION.toLowerCase();
private static final String HEADER_CONTENT_LOCATION_LC =
HTTPConstants.HEADER_CONTENT_LOCATION.toLowerCase();
private static final String HEADER_CONTENT_LENGTH_LC =
HTTPConstants.HEADER_CONTENT_LENGTH.toLowerCase();
private static final String HEADER_TRANSFER_ENCODING_LC =
HTTPConstants.HEADER_TRANSFER_ENCODING.toLowerCase();
/**
* the url; used for error reporting
*/
URL targetURL;
/**
* invoke creates a socket connection, sends the request SOAP message and then
* reads the response SOAP message back from the SOAP server
*
* @param msgContext the messsage context
*
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("enter00", "HTTPSender::invoke"));
}
SocketHolder socketHolder = new SocketHolder(null);
try {
BooleanHolder useFullURL = new BooleanHolder(false);
StringBuffer otherHeaders = new StringBuffer();
targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
String host = targetURL.getHost();
int port = targetURL.getPort();
// Send the SOAP request to the server
InputStream inp = writeToSocket(socketHolder, msgContext, targetURL,
otherHeaders, host, port, msgContext.getTimeout(), useFullURL);
// Read the response back from the server
Hashtable headers = new Hashtable();
inp = readHeadersFromSocket(socketHolder, msgContext, inp, headers);
readFromSocket(socketHolder, msgContext, inp, headers);
} catch (Exception e) {
log.debug(e);
try {
if (socketHolder.getSocket() != null ) {
socketHolder.getSocket().close();
}
} catch (IOException ie) {
// we shouldn't get here.
}
throw AxisFault.makeFault(e);
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("exit00",
"HTTPDispatchHandler::invoke"));
}
}
/**
* Creates a socket connection to the SOAP server
*
* @param protocol "http" for standard, "https" for ssl.
* @param host host name
* @param port port to connect to
* @param otherHeaders buffer for storing additional headers that need to be sent
* @param useFullURL flag to indicate if the complete URL has to be sent
*
* @throws IOException
*/
protected void getSocket(SocketHolder sockHolder,
MessageContext msgContext,
String protocol,
String host, int port, int timeout,
StringBuffer otherHeaders,
BooleanHolder useFullURL)
throws Exception {
Hashtable options = getOptions();
if(timeout > 0) {
if(options == null) {
options = new Hashtable();
}
options.put(DefaultSocketFactory.CONNECT_TIMEOUT,Integer.toString(timeout));
}
SocketFactory factory = SocketFactoryFactory.getFactory(protocol, options);
if (factory == null) {
throw new IOException(Messages.getMessage("noSocketFactory", protocol));
}
Socket sock = factory.create(host, port, otherHeaders, useFullURL);
if(timeout > 0) {
sock.setSoTimeout(timeout);
}
sockHolder.setSocket(sock);
}
/**
* Send the soap request message to the server
*
* @param msgContext message context
* @param tmpURL url to connect to
* @param otherHeaders other headers if any
* @param host host name
* @param port port
* @param useFullURL flag to indicate if the whole url needs to be sent
*
* @throws IOException
*/
private InputStream writeToSocket(SocketHolder sockHolder,
MessageContext msgContext, URL tmpURL,
StringBuffer otherHeaders, String host, int port, int timeout,
BooleanHolder useFullURL)
throws Exception {
String userID = msgContext.getUsername();
String passwd = msgContext.getPassword();
// Get SOAPAction, default to ""
String action = msgContext.useSOAPAction()
? msgContext.getSOAPActionURI()
: "";
if (action == null) {
action = "";
}
// if UserID is not part of the context, but is in the URL, use
// the one in the URL.
if ((userID == null) && (tmpURL.getUserInfo() != null)) {
String info = tmpURL.getUserInfo();
int sep = info.indexOf(':');
if ((sep >= 0) && (sep + 1 < info.length())) {
userID = info.substring(0, sep);
passwd = info.substring(sep + 1);
} else {
userID = info;
}
}
if (userID != null) {
StringBuffer tmpBuf = new StringBuffer();
tmpBuf.append(userID).append(":").append((passwd == null)
? ""
: passwd);
otherHeaders.append(HTTPConstants.HEADER_AUTHORIZATION)
.append(": Basic ")
.append(Base64.encode(tmpBuf.toString().getBytes()))
.append("\r\n");
}
// don't forget the cookies!
// mmm... cookies
if (msgContext.getMaintainSession()) {
fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE, otherHeaders);
fillHeaders(msgContext, HTTPConstants.HEADER_COOKIE2, otherHeaders);
}
StringBuffer header2 = new StringBuffer();
String webMethod = null;
boolean posting = true;
Message reqMessage = msgContext.getRequestMessage();
boolean http10 = true; //True if this is to use HTTP 1.0 / false HTTP 1.1
boolean httpChunkStream = false; //Use HTTP chunking or not.
boolean httpContinueExpected = false; //Under HTTP 1.1 if false you *MAY* need to wait for a 100 rc,
// if true the server MUST reply with 100 continue.
String httpConnection = null;
String httpver = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
if (null == httpver) {
httpver = HTTPConstants.HEADER_PROTOCOL_V10;
}
httpver = httpver.trim();
if (httpver.equals(HTTPConstants.HEADER_PROTOCOL_V11)) {
http10 = false;
}
//process user defined headers for information.
Hashtable userHeaderTable = (Hashtable) msgContext.
getProperty(HTTPConstants.REQUEST_HEADERS);
if (userHeaderTable != null) {
if (null == otherHeaders) {
otherHeaders = new StringBuffer(1024);
}
for (java.util.Iterator e = userHeaderTable.entrySet().iterator();
e.hasNext();) {
java.util.Map.Entry me = (java.util.Map.Entry) e.next();
Object keyObj = me.getKey();
if (null == keyObj) continue;
String key = keyObj.toString().trim();
if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING)) {
if (!http10) {
String val = me.getValue().toString();
if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED))
httpChunkStream = true;
}
} else if (key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
if (!http10) {
String val = me.getValue().toString();
if (val.trim().equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION_CLOSE))
httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
}
//HTTP 1.0 will always close.
//HTTP 1.1 will use persistent. //no need to specify
} else {
if( !http10 && key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
String val = me.getValue().toString();
if (null != val && val.trim().equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue))
httpContinueExpected = true;
}
otherHeaders.append(key).append(": ").append(me.getValue()).append("\r\n");
}
}
}
if (!http10) {
//Force close for now.
//TODO HTTP/1.1
httpConnection = HTTPConstants.HEADER_CONNECTION_CLOSE;
}
header2.append(" ");
header2.append(http10 ? HTTPConstants.HEADER_PROTOCOL_10 :
HTTPConstants.HEADER_PROTOCOL_11)
.append("\r\n");
MimeHeaders mimeHeaders = reqMessage.getMimeHeaders();
if (posting) {
String contentType;
final String[] header = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if (header != null && header.length > 0) {
contentType = mimeHeaders.getHeader(HTTPConstants.HEADER_CONTENT_TYPE)[0];
} else {
contentType = reqMessage.getContentType(msgContext.getSOAPConstants());
}
//fix for AXIS-2027
if (contentType == null || contentType.equals("")) {
throw new Exception(Messages.getMessage("missingContentType"));
}
header2.append(HTTPConstants.HEADER_CONTENT_TYPE)
.append(": ")
.append(contentType)
.append("\r\n");
}
header2.append(ACCEPT_HEADERS)
.append(HTTPConstants.HEADER_HOST) //used for virtual connections
.append(": ")
.append(host)
.append((port == -1)?(""):(":" + port))
.append("\r\n")
.append(CACHE_HEADERS)
.append(HTTPConstants.HEADER_SOAP_ACTION) //The SOAP action.
.append(": \"")
.append(action)
.append("\"\r\n");
if (posting) {
if (!httpChunkStream) {
//Content length MUST be sent on HTTP 1.0 requests.
header2.append(HTTPConstants.HEADER_CONTENT_LENGTH)
.append(": ")
.append(reqMessage.getContentLength())
.append("\r\n");
} else {
//Do http chunking.
header2.append(CHUNKED_HEADER);
}
}
// Transfer MIME headers of SOAPMessage to HTTP headers.
if (mimeHeaders != null) {
for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader mimeHeader = (MimeHeader) i.next();
String headerName = mimeHeader.getName();
if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
|| headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
continue;
}
header2.append(mimeHeader.getName())
.append(": ")
.append(mimeHeader.getValue())
.append("\r\n");
}
}
if (null != httpConnection) {
header2.append(HTTPConstants.HEADER_CONNECTION);
header2.append(": ");
header2.append(httpConnection);
header2.append("\r\n");
}
getSocket(sockHolder, msgContext, targetURL.getProtocol(),
host, port, timeout, otherHeaders, useFullURL);
if (null != otherHeaders) {
//Add other headers to the end.
//for pre java1.4 support, we have to turn the string buffer argument into
//a string before appending.
header2.append(otherHeaders.toString());
}
header2.append("\r\n"); //The empty line to start the BODY.
StringBuffer header = new StringBuffer();
// If we're SOAP 1.2, allow the web method to be set from the
// MessageContext.
if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
}
if (webMethod == null) {
webMethod = HTTPConstants.HEADER_POST;
} else {
posting = webMethod.equals(HTTPConstants.HEADER_POST);
}
header.append(webMethod).append(" ");
if (useFullURL.value) {
header.append(tmpURL.toExternalForm());
} else {
header.append((((tmpURL.getFile() == null)
|| tmpURL.getFile().equals(""))
? "/"
: tmpURL.getFile()));
}
header.append(header2.toString());
OutputStream out = sockHolder.getSocket().getOutputStream();
if (!posting) {
out.write(header.toString()
.getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
out.flush();
return null;
}
InputStream inp = null;
if (httpChunkStream || httpContinueExpected) {
out.write(header.toString()
.getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
}
if(httpContinueExpected ){ //We need to get a reply from the server as to whether
// it wants us send anything more.
out.flush();
Hashtable cheaders= new Hashtable ();
inp = readHeadersFromSocket(sockHolder, msgContext, null, cheaders);
int returnCode= -1;
Integer Irc= (Integer)msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
if(null != Irc) {
returnCode= Irc.intValue();
}
if(100 == returnCode){ // got 100 we may continue.
//Need todo a little msgContext house keeping....
msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
}
else{ //If no 100 Continue then we must not send anything!
String statusMessage= (String)
msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
AxisFault fault = new AxisFault("HTTP", "(" + returnCode+ ")" + statusMessage, null, null);
fault.setFaultDetailString(Messages.getMessage("return01",
"" + returnCode, ""));
throw fault;
}
}
ByteArrayOutputStream baos = null;
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("xmlSent00"));
log.debug("---------------------------------------------------");
baos = new ByteArrayOutputStream();
}
if (httpChunkStream) {
ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(out);
out = new BufferedOutputStream(chunkedOutputStream, Constants.HTTP_TXR_BUFFER_SIZE);
try {
if(baos != null) {
out = new TeeOutputStream(out, baos);
}
reqMessage.writeTo(out);
} catch (SOAPException e) {
log.error(Messages.getMessage("exception00"), e);
}
out.flush();
chunkedOutputStream.eos();
} else {
out = new BufferedOutputStream(out, Constants.HTTP_TXR_BUFFER_SIZE);
try {
if (!httpContinueExpected) {
out.write(header.toString()
.getBytes(HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING));
}
if(baos != null) {
out = new TeeOutputStream(out, baos);
}
reqMessage.writeTo(out);
} catch (SOAPException e) {
log.error(Messages.getMessage("exception00"), e);
}
// Flush ONLY once.
out.flush();
}
if (log.isDebugEnabled()) {
log.debug(header + new String(baos.toByteArray()));
}
return inp;
}
/**
* Get cookies from message context and add it to the headers
* @param msgContext
* @param header
* @param otherHeaders
*/
private void fillHeaders(MessageContext msgContext, String header, StringBuffer otherHeaders) {
Object ck1 = msgContext.getProperty(header);
if (ck1 != null) {
if (ck1 instanceof String[]) {
String [] cookies = (String[]) ck1;
for (int i = 0; i < cookies.length; i++) {
addCookie(otherHeaders, header, cookies[i]);
}
} else {
addCookie(otherHeaders, header, (String) ck1);
}
}
}
/**
* add cookie to headers
* @param otherHeaders
* @param header
* @param cookie
*/
private void addCookie(StringBuffer otherHeaders, String header, String cookie) {
otherHeaders.append(header).append(": ")
.append(cookie).append("\r\n");
}
private InputStream readHeadersFromSocket(SocketHolder sockHolder,
MessageContext msgContext,
InputStream inp,
Hashtable headers)
throws IOException {
byte b = 0;
int len = 0;
int colonIndex = -1;
String name, value;
int returnCode = 0;
if(null == inp) {
inp = new BufferedInputStream(sockHolder.getSocket().getInputStream());
}
if (headers == null) {
headers = new Hashtable();
}
// Should help performance. Temporary fix only till its all stream oriented.
// Need to add logic for getting the version # and the return code
// but that's for tomorrow!
/* Logic to read HTTP response headers */
boolean readTooMuch = false;
for (ByteArrayOutputStream buf = new ByteArrayOutputStream(4097); ;) {
if (!readTooMuch) {
b = (byte) inp.read();
}
if (b == -1) {
break;
}
readTooMuch = false;
if ((b != '\r') && (b != '\n')) {
if ((b == ':') && (colonIndex == -1)) {
colonIndex = len;
}
len++;
buf.write(b);
} else if (b == '\r') {
continue;
} else { // b== '\n'
if (len == 0) {
break;
}
b = (byte) inp.read();
readTooMuch = true;
// A space or tab at the begining of a line means the header continues.
if ((b == ' ') || (b == '\t')) {
continue;
}
buf.close();
byte[] hdata = buf.toByteArray();
buf.reset();
if (colonIndex != -1) {
name =
new String(hdata, 0, colonIndex,
HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING);
value =
new String(hdata, colonIndex + 1, len - 1 - colonIndex,
HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING);
colonIndex = -1;
} else {
name =
new String(hdata, 0, len,
HTTPConstants.HEADER_DEFAULT_CHAR_ENCODING);
value = "";
}
if (log.isDebugEnabled()) {
log.debug(name + value);
}
if (msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE)
== null) {
// Reader status code
int start = name.indexOf(' ') + 1;
String tmp = name.substring(start).trim();
int end = tmp.indexOf(' ');
if (end != -1) {
tmp = tmp.substring(0, end);
}
returnCode = Integer.parseInt(tmp);
msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE,
new Integer(returnCode));
msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE,
name.substring(start + end + 1));
} else {
// if we are maintaining session state,
// handle cookies (if any)
if (msgContext.getMaintainSession()) {
final String nameLowerCase = name.toLowerCase();
if (nameLowerCase.equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
handleCookie(HTTPConstants.HEADER_COOKIE, null, value, msgContext);
} else if (nameLowerCase.equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
handleCookie(HTTPConstants.HEADER_COOKIE2, null, value, msgContext);
} else {
headers.put(name.toLowerCase(), value);
}
} else {
headers.put(name.toLowerCase(), value);
}
}
len = 0;
}
}
return inp;
}
/**
* Reads the SOAP response back from the server
*
* @param msgContext message context
*
* @throws IOException
*/
private InputStream readFromSocket(SocketHolder socketHolder,
MessageContext msgContext,
InputStream inp,
Hashtable headers)
throws IOException {
Message outMsg = null;
byte b;
Integer rc = (Integer)msgContext.getProperty(
HTTPConstants.MC_HTTP_STATUS_CODE);
int returnCode = 0;
if (rc != null) {
returnCode = rc.intValue();
} else {
// No return code?? Should have one by now.
}
/* All HTTP headers have been read. */
String contentType = (String) headers.get(HEADER_CONTENT_TYPE_LC);
contentType = (null == contentType)
? null
: contentType.trim();
String location = (String) headers.get(HEADER_LOCATION_LC);
location = (null == location)
? null
: location.trim();
if ((returnCode > 199) && (returnCode < 300)) {
if (returnCode == 202) {
return inp;
}
// SOAP return is OK - so fall through
} else if (msgContext.getSOAPConstants() ==
SOAPConstants.SOAP12_CONSTANTS) {
// For now, if we're SOAP 1.2, fall through, since the range of
// valid result codes is much greater
} else if ((contentType != null) && !contentType.startsWith("text/html")
&& ((returnCode > 499) && (returnCode < 600))) {
// SOAP Fault should be in here - so fall through
} else if ((location != null) &&
((returnCode == 302) || (returnCode == 307))) {
// Temporary Redirect (HTTP: 302/307)
// close old connection
inp.close();
socketHolder.getSocket().close();
// remove former result and set new target url
msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
msgContext.setProperty(MessageContext.TRANS_URL, location);
// next try
invoke(msgContext);
return inp;
} else if (returnCode == 100) {
msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
readHeadersFromSocket(socketHolder, msgContext, inp, headers);
return readFromSocket(socketHolder, msgContext, inp, headers);
} else {
// Unknown return code - so wrap up the content into a
// SOAP Fault.
ByteArrayOutputStream buf = new ByteArrayOutputStream(4097);
while (-1 != (b = (byte) inp.read())) {
buf.write(b);
}
String statusMessage = msgContext.getStrProp(
HTTPConstants.MC_HTTP_STATUS_MESSAGE);
AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" +
statusMessage, null, null);
fault.setFaultDetailString(Messages.getMessage("return01",
"" + returnCode, buf.toString()));
fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
Integer.toString(returnCode));
throw fault;
}
String contentLocation =
(String) headers.get(HEADER_CONTENT_LOCATION_LC);
contentLocation = (null == contentLocation)
? null
: contentLocation.trim();
String contentLength =
(String) headers.get(HEADER_CONTENT_LENGTH_LC);
contentLength = (null == contentLength)
? null
: contentLength.trim();
String transferEncoding =
(String) headers.get(HEADER_TRANSFER_ENCODING_LC);
if (null != transferEncoding) {
transferEncoding = transferEncoding.trim().toLowerCase();
if (transferEncoding.equals(
HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
inp = new ChunkedInputStream(inp);
}
}
outMsg = new Message( new SocketInputStream(inp, socketHolder.getSocket()), false,
contentType, contentLocation);
// Transfer HTTP headers of HTTP message to MIME headers of SOAP message
MimeHeaders mimeHeaders = outMsg.getMimeHeaders();
for (Enumeration e = headers.keys(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
mimeHeaders.addHeader(key, ((String) headers.get(key)).trim());
}
outMsg.setMessageType(Message.RESPONSE);
msgContext.setResponseMessage(outMsg);
if (log.isDebugEnabled()) {
if (null == contentLength) {
log.debug("\n"
+ Messages.getMessage("no00", "Content-Length"));
}
log.debug("\n" + Messages.getMessage("xmlRecd00"));
log.debug("-----------------------------------------------");
log.debug(outMsg.getSOAPEnvelope().toString());
}
return inp;
}
/**
* little helper function for cookies. fills up the message context with
* a string or an array of strings (if there are more than one Set-Cookie)
*
* @param cookieName
* @param setCookieName
* @param cookie
* @param msgContext
*/
public void handleCookie(String cookieName, String setCookieName,
String cookie, MessageContext msgContext) {
cookie = cleanupCookie(cookie);
int keyIndex = cookie.indexOf("=");
String key = (keyIndex != -1) ? cookie.substring(0, keyIndex) : cookie;
ArrayList cookies = new ArrayList();
Object oldCookies = msgContext.getProperty(cookieName);
boolean alreadyExist = false;
if(oldCookies != null) {
if(oldCookies instanceof String[]) {
String[] oldCookiesArray = (String[])oldCookies;
for(int i = 0; i < oldCookiesArray.length; i++) {
String anOldCookie = oldCookiesArray[i];
if (key != null && anOldCookie.indexOf(key) == 0) { // same cookie key
anOldCookie = cookie; // update to new one
alreadyExist = true;
}
cookies.add(anOldCookie);
}
} else {
String oldCookie = (String)oldCookies;
if (key != null && oldCookie.indexOf(key) == 0) { // same cookie key
oldCookie = cookie; // update to new one
alreadyExist = true;
}
cookies.add(oldCookie);
}
}
if (!alreadyExist) {
cookies.add(cookie);
}
if(cookies.size()==1) {
msgContext.setProperty(cookieName, cookies.get(0));
} else if (cookies.size() > 1) {
msgContext.setProperty(cookieName, cookies.toArray(new String[cookies.size()]));
}
}
/**
* cleanup the cookie value.
*
* @param cookie initial cookie value
*
* @return a cleaned up cookie value.
*/
private String cleanupCookie(String cookie) {
cookie = cookie.trim();
// chop after first ; a la Apache SOAP (see HTTPUtils.java there)
int index = cookie.indexOf(';');
if (index != -1) {
cookie = cookie.substring(0, index);
}
return cookie;
}
}
| 7,412 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/ChunkedInputStream.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.transport.http;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Rick Rineholt
*/
public class ChunkedInputStream extends java.io.FilterInputStream {
protected long chunkSize = 0l;
protected volatile boolean closed = false;
private static final int maxCharLong =
(Long.toHexString(Long.MAX_VALUE)).toString().length();
private byte[] buf = new byte[maxCharLong + 2];
private ChunkedInputStream () {
super(null);
}
public ChunkedInputStream (InputStream is) {
super(is);
}
public synchronized int read()
throws IOException {
if (closed) {
return -1;
}
try {
if (chunkSize < 1L) {
if (0l == getChunked()) {
return -1;
}
}
int rc = in.read();
if (rc > 0) {
chunkSize--;
}
return rc;
} catch (IOException e) {
closed = true;
throw e;
}
}
public int read(byte[] b)
throws IOException {
return read(b, 0, b.length);
}
public synchronized int read(byte[] b,
int off,
int len)
throws IOException {
if (closed) {
return -1;
}
int totalread = 0;
int bytesread = 0;
try {
do {
if (chunkSize < 1L) {
if (0l == getChunked()) {
if (totalread == 0) return -1;
else return totalread;
}
}
bytesread = in.read(b, off + totalread, Math.min(len - totalread,
(int) Math.min(chunkSize, Integer.MAX_VALUE)));
if (bytesread > 0) {
totalread += bytesread;
chunkSize -= bytesread;
}
}
while (len - totalread > 0 && bytesread > -1);
} catch (IOException e) {
closed = true;
throw e;
}
return totalread;
}
public long skip(final long n)
throws IOException {
if (closed) {
return 0;
}
long skipped = 0l;
byte[] b = new byte[1024];
int bread = -1;
do {
bread = read(b, 0, b.length);
if (bread > 0) skipped += bread;
}
while (bread != -1 && skipped < n);
return skipped;
}
public int available()
throws IOException {
if (closed) {
return 0;
}
int rc = (int) Math.min(chunkSize, Integer.MAX_VALUE);
return Math.min(rc, in.available());
}
protected long getChunked()throws IOException {
int bufsz = 0;
chunkSize = -1L;
int c = -1;
do {
c = in.read();
if (c > -1) {
if (c != '\r' && c != '\n' && c != ' ' && c != '\t') {
buf[bufsz++] = ((byte) c);
}
}
}
while (c > -1 && (c != '\n' || bufsz == 0) && bufsz < buf.length);
if (c < 0) {
closed = true;
}
String sbuf = new String(buf, 0, bufsz);
if (bufsz > maxCharLong) {
closed = true;
throw new IOException("Chunked input stream failed to receive valid chunk size:" + sbuf);
}
try {
chunkSize = Long.parseLong(sbuf, 16);
} catch (NumberFormatException ne) {
closed = true;
throw new IOException("'" + sbuf + "' " + ne.getMessage());
}
if (chunkSize < 0L) {
closed = true;
} if (chunkSize == 0) {
closed = true;
// consume last \r\n tokens of 0\r\n\r\n chunk
if (in.read() != -1) {
in.read();
}
}
if (chunkSize != 0L && c < 0) {
//If chunk size is zero try and be tolerant that there maybe no cr or lf at the end.
throw new IOException("HTTP Chunked stream closed in middle of chunk.");
}
if (chunkSize < 0L) {
throw new IOException("HTTP Chunk size received " +
chunkSize + " is less than zero.");
}
return chunkSize;
}
public void close() throws IOException {
synchronized (this) {
if (closed) {
return;
}
closed = true;
}
byte[] b = new byte[1024];
int bread = -1;
do {
bread = read(b, 0, b.length);
}
while (bread != -1);
}
/*
public void mark(int readlimit)
{
}
*/
public void reset()
throws IOException {
throw new IOException("Don't support marked streams");
}
public boolean markSupported() {
return false;
}
}
| 7,413 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AxisHttpSession.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.transport.http;
import org.apache.axis.session.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
/**
* An HTTP/Servlet implementation of Axis sessions.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class AxisHttpSession implements Session
{
public static final String AXIS_SESSION_MARKER = "axis.isAxisSession";
private HttpSession rep;
private HttpServletRequest req;
public AxisHttpSession(HttpServletRequest realRequest)
{
req = realRequest;
}
public AxisHttpSession(HttpSession realSession)
{
if (realSession != null)
setRep(realSession);
}
/** Get the internal HttpSession.
*/
public HttpSession getRep()
{
ensureSession();
return rep;
}
/** Set our internal HttpSession to the passed
* servlet HttpSession. Not sure if we'll really
* need this method...
*/
private void setRep(HttpSession realSession)
{
rep = realSession;
rep.setAttribute(AXIS_SESSION_MARKER, Boolean.TRUE);
}
/** Get a property from the session
*
* @param key the name of the property desired.
*/
public Object get(String key)
{
ensureSession();
return rep.getAttribute(key);
}
/** Set a property in the session
*
* @param key the name of the property to set.
* @param value the value of the property.
*/
public void set(String key, Object value)
{
ensureSession();
rep.setAttribute(key, value);
}
/** Remove a property from the session
*
* @param key the name of the property desired.
*/
public void remove(String key)
{
ensureSession();
rep.removeAttribute(key);
}
/**
* Get an enumeration of the keys in this session
*/
public Enumeration getKeys() {
ensureSession();
return rep.getAttributeNames();
}
/** Set the session's time-to-live.
*
* This is implementation-specific, but basically should be the #
* of seconds of inactivity which will cause the session to time
* out and invalidate. "inactivity" is implementation-specific.
*/
public void setTimeout(int timeout)
{
ensureSession();
rep.setMaxInactiveInterval(timeout);
}
/**
* Return the sessions' time-to-live.
*
* @return the timeout value for this session.
*/
public int getTimeout() {
ensureSession();
return rep.getMaxInactiveInterval();
}
/**
* "Touch" the session (mark it recently used)
*/
public void touch() {
// ???
}
/**
* invalidate the session
*/
public void invalidate() {
rep.invalidate();
}
protected void ensureSession() {
if (rep == null) {
setRep(req.getSession());
}
}
/**
* Get an Object suitable for synchronizing the session. This method
* exists because different session implementations might provide
* different ways of getting at shared data. For a simple hashtable-
* based session, this would just be the hashtable, but for sessions
* which use database connections, etc. it might be an object wrapping
* a table ID or somesuch.
*/
public Object getLockObject() {
ensureSession();
return rep;
}
}
| 7,414 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AbstractQueryStringHandler.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.transport.http;
import org.apache.axis.MessageContext;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.XMLUtils;
import org.apache.commons.logging.Log;
import org.w3c.dom.Element;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* An optional base class for query string handlers; provides various helper methods
* and extracts things from the the message context
*/
public abstract class AbstractQueryStringHandler implements QSHandler {
/** cache of development flag */
private boolean development;
/** log for exceptions */
protected Log exceptionLog;
/** the other log */
protected Log log;
/**
* probe for the system being 'production'
* @return true for a dev system.
*/
protected boolean isDevelopment () {
return this.development;
}
/**
* configure our elements from the context. Call this in the invoke()
* implementation to set up the base class
* @param msgContext
*/
protected void configureFromContext(MessageContext msgContext) {
this.development = ((Boolean) msgContext.getProperty
(HTTPConstants.PLUGIN_IS_DEVELOPMENT)).booleanValue();
this.exceptionLog = (Log) msgContext.getProperty
(HTTPConstants.PLUGIN_EXCEPTION_LOG);
this.log = (Log) msgContext.getProperty(HTTPConstants.PLUGIN_LOG);
}
/**
* routine called whenever an axis fault is caught; where they
* are logged and any other business. The method may modify the fault
* in the process
* @param fault what went wrong.
*/
protected void processAxisFault (AxisFault fault) {
//log the fault
Element runtimeException = fault.lookupFaultDetail
(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
if (runtimeException != null) {
exceptionLog.info (Messages.getMessage ("axisFault00"), fault);
//strip runtime details
fault.removeFaultDetail
(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
}
else if (exceptionLog.isDebugEnabled()) {
exceptionLog.debug (Messages.getMessage ("axisFault00"), fault);
}
//dev systems only give fault dumps
if (!isDevelopment()) {
//strip out the stack trace
fault.removeFaultDetail (Constants.QNAME_FAULTDETAIL_STACKTRACE);
}
}
/**
* Configure the servlet response status code and maybe other headers
* from the fault info.
* @param response response to configure
* @param fault what went wrong
*/
protected void configureResponseFromAxisFault (HttpServletResponse response,
AxisFault fault) {
// then get the status code
// It's been suggested that a lack of SOAPAction
// should produce some other error code (in the 400s)...
int status = getHttpServletResponseStatus (fault);
if (status == HttpServletResponse.SC_UNAUTHORIZED) {
// unauth access results in authentication request
// TODO: less generic realm choice?
response.setHeader ("WWW-Authenticate", "Basic realm=\"AXIS\"");
}
response.setStatus (status);
}
/**
* turn any Exception into an AxisFault, log it, set the response
* status code according to what the specifications say and
* return a response message for posting. This will be the response
* message passed in if non-null; one generated from the fault otherwise.
*
* @param exception what went wrong
* @param responseMsg what response we have (if any)
* @return a response message to send to the user
*/
protected Message convertExceptionToAxisFault (Exception exception,
Message responseMsg) {
logException (exception);
if (responseMsg == null) {
AxisFault fault = AxisFault.makeFault (exception);
processAxisFault (fault);
responseMsg = new Message (fault);
}
return responseMsg;
}
/**
* Extract information from AxisFault and map it to a HTTP Status code.
*
* @param af Axis Fault
* @return HTTP Status code.
*/
private int getHttpServletResponseStatus (AxisFault af) {
// TODO: Should really be doing this with explicit AxisFault
// subclasses... --Glen
return af.getFaultCode().getLocalPart().startsWith ("Server.Unauth")
? HttpServletResponse.SC_UNAUTHORIZED
: HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
// This will raise a 401 for both
// "Unauthenticated" & "Unauthorized"...
}
/**
* log any exception to our output log, at our chosen level
* @param e what went wrong
*/
private void logException (Exception e) {
exceptionLog.info (Messages.getMessage ("exception00"), e);
}
/**
* this method writes a fault out to an HTML stream. This includes
* escaping the strings to defend against cross-site scripting attacks
* @param writer
* @param axisFault
*/
protected void writeFault (PrintWriter writer, AxisFault axisFault) {
String localizedMessage = XMLUtils.xmlEncodeString
(axisFault.getLocalizedMessage());
writer.println ("<pre>Fault - " + localizedMessage + "<br>");
writer.println (axisFault.dumpToString());
writer.println ("</pre>");
}
}
| 7,415 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AdminServlet.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.transport.http ;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.axis.AxisFault;
import org.apache.axis.ConfigurationException;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.description.ServiceDesc;
import org.apache.commons.logging.Log;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.util.Iterator;
/**
* Proof-of-concept "management" servlet for Axis.
*
* Point a browser here to administer the Axis installation.
*
* Right now just starts and stops the server.
*
* @author Glen Daniels (gdaniels@apache.org)
* @author Steve Loughran
*/
public class AdminServlet extends AxisServletBase {
private static Log log =
LogFactory.getLog(AxisServlet.class.getName());
/**
* handle a GET request. Commands are only valid when not in production mode
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
StringBuffer buffer=new StringBuffer(512);
buffer.append("<html><head><title>Axis</title></head><body>\n");
//REVISIT: what happens if there is no engine?
AxisServer server = getEngine();
//process command
String cmd = request.getParameter("cmd");
if (cmd != null) {
//who called?
String callerIP=request.getRemoteAddr();
if (isDevelopment()) {
//only in dev mode do these command work
if (cmd.equals("start")) {
log.info(Messages.getMessage("adminServiceStart", callerIP));
server.start();
}
else if (cmd.equals("stop")) {
log.info(Messages.getMessage("adminServiceStop", callerIP));
server.stop();
}
else if (cmd.equals("suspend")) {
String name = request.getParameter("service");
log.info(Messages.getMessage("adminServiceSuspend", name, callerIP));
SOAPService service = server.getConfig().getService(new QName("",name));
service.stop();
}
else if (cmd.equals("resume")) {
String name = request.getParameter("service");
log.info(Messages.getMessage("adminServiceResume", name, callerIP));
SOAPService service = server.getConfig().getService(new QName("",name));
service.start();
}
} else {
//in production we log a hostile probe. Remember: logs can be
//used for DoS attacks themselves.
log.info(Messages.getMessage("adminServiceDeny", callerIP));
}
}
// display status
if (server.isRunning()) {
buffer.append("<H2>");
buffer.append(Messages.getMessage("serverRun00"));
buffer.append("</H2>");
}
else {
buffer.append("<H2>");
buffer.append(Messages.getMessage("serverStop00"));
buffer.append("</H2>");
}
//add commands
if(isDevelopment()) {
buffer.append("<p><a href=\"AdminServlet?cmd=start\">start server</a>\n");
buffer.append("<p><a href=\"AdminServlet?cmd=stop\">stop server</a>\n");
Iterator i;
try {
i = server.getConfig().getDeployedServices();
} catch (ConfigurationException configException) {
//turn any internal configuration exceptions back into axis faults
//if that is what they are
if(configException.getContainedException() instanceof AxisFault) {
throw (AxisFault) configException.getContainedException();
} else {
throw configException;
}
}
buffer.append("<p><h2>Services</h2>");
buffer.append("<ul>");
while (i.hasNext()) {
ServiceDesc sd = (ServiceDesc)i.next();
StringBuffer sb = new StringBuffer();
sb.append("<li>");
String name = sd.getName();
sb.append(name);
SOAPService service = server.getConfig().getService(new QName("",name));
if(service.isRunning()) {
sb.append(" <a href=\"AdminServlet?cmd=suspend&service=" + name + "\">suspend</a>\n");
} else {
sb.append(" <a href=\"AdminServlet?cmd=resume&service=" + name + "\">resume</a>\n");
}
sb.append("</li>");
buffer.append(sb.toString());
}
buffer.append("</ul>");
}
//print load
buffer.append("<p>");
buffer.append(Messages.getMessage("adminServiceLoad",
Integer.toString(getLoadCounter())));
buffer.append("\n</body></html>\n");
response.getWriter().print( new String(buffer) );
}
}
| 7,416 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/SocketInputStream.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.transport.http;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Rick Rineholt
*/
/**
* The ONLY reason for this is so we can clean up sockets quicker/cleaner.
*/
public class SocketInputStream extends java.io.FilterInputStream {
protected volatile boolean closed = false;
java.net.Socket socket= null;
private SocketInputStream() {
super(null);
}
public SocketInputStream(InputStream is, java.net.Socket socket) {
super(is);
this.socket= socket;
}
public void close() throws IOException {
synchronized(this){
if(closed) return;
closed= true;
}
in.close();
in= null;
socket.close();
socket= null;
}
}
| 7,417 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AutoRegisterServlet.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.transport.http;
import org.apache.commons.logging.Log;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.deployment.wsdd.WSDDDocument;
import org.apache.axis.deployment.wsdd.WSDDDeployment;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.ConfigurationException;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.WSDDEngineConfiguration;
import org.apache.axis.i18n.Messages;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
/**
* Servlet that autoregisters
* @author Steve Loughran
*/
public class AutoRegisterServlet extends AxisServletBase {
private static Log log =
LogFactory.getLog(AutoRegisterServlet.class.getName());
/**
* init by registering
*/
public void init() throws javax.servlet.ServletException {
log.debug(Messages.getMessage("autoRegServletInit00"));
autoRegister();
}
/**
* register an open stream, which we close afterwards
* @param instream
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public void registerStream(InputStream instream) throws SAXException, ParserConfigurationException, IOException {
try {
Document doc=XMLUtils.newDocument(instream);
WSDDDocument wsddDoc = new WSDDDocument(doc);
WSDDDeployment deployment;
deployment = getDeployment();
if(deployment!=null) {
wsddDoc.deploy(deployment);
}
} finally {
instream.close();
}
}
/**
* register a resource
* @param resourcename
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public void registerResource(String resourcename)
throws SAXException, ParserConfigurationException, IOException {
InputStream in=getServletContext().getResourceAsStream(resourcename);
if(in==null) {
throw new FileNotFoundException(resourcename);
}
registerStream(in);
}
/**
* register a file
* @param file
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public void registerFile(File file) throws IOException, SAXException, ParserConfigurationException {
InputStream in=new BufferedInputStream(new FileInputStream(file));
registerStream(in);
}
/**
* subclass this to return an array of resource names.
* @return array of resource names of wsdd files, or null
*/
public String[] getResourcesToRegister() {
return null;
}
/**
* get deployment
* @return
* @throws AxisFault
*/
private WSDDDeployment getDeployment() throws AxisFault {
WSDDDeployment deployment;
AxisEngine engine = getEngine();
EngineConfiguration config = engine.getConfig();
if (config instanceof WSDDEngineConfiguration) {
deployment = ((WSDDEngineConfiguration) config).getDeployment();
} else {
deployment=null;
}
return deployment;
}
/**
* handler for logging success, defaults to handing off to logging
* at debug level
* @param item what were we loading?
*/
protected void logSuccess(String item) {
log.debug(Messages.getMessage("autoRegServletLoaded01",item));
}
/**
* register classes, log exceptions
*/
protected void autoRegister() {
String[] resources=getResourcesToRegister();
if(resources==null || resources.length==0) {
return;
}
for(int i=0;i<resources.length;i++) {
final String resource = resources[i];
registerAndLogResource(resource);
}
registerAnythingElse();
try {
applyAndSaveSettings();
} catch (Exception e) {
log.error(Messages.getMessage("autoRegServletApplyAndSaveSettings00"), e);
}
}
/**
* override point for subclasses to add other registration stuff
*/
protected void registerAnythingElse() {
}
/**
* register a single resource; log trouble and success.
* @param resource
*/
public void registerAndLogResource(final String resource) {
try {
registerResource(resource);
logSuccess(resource);
} catch (Exception e) {
log.error(Messages.getMessage("autoRegServletLoadFailed01",resource),e);
}
}
/**
* actually update the engine and save the settings
* @throws AxisFault
* @throws ConfigurationException
*/
protected void applyAndSaveSettings()
throws AxisFault, ConfigurationException {
AxisEngine engine = getEngine();
engine.refreshGlobalOptions();
engine.saveConfiguration();
}
}
| 7,418 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/ServletEndpointContextImpl.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.
*/
package org.apache.axis.transport.http;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.server.ServletEndpointContext;
import java.security.Principal;
public class ServletEndpointContextImpl implements ServletEndpointContext {
public HttpSession getHttpSession() {
HttpServletRequest srvreq = (HttpServletRequest)
getMessageContext().getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
return (srvreq == null) ? null : srvreq.getSession();
}
public MessageContext getMessageContext() {
return org.apache.axis.MessageContext.getCurrentContext();
}
public ServletContext getServletContext() {
HttpServlet srv = (HttpServlet)
getMessageContext().getProperty(HTTPConstants.MC_HTTP_SERVLET);
return (srv == null) ? null : srv.getServletContext();
}
public boolean isUserInRole(String role) {
HttpServletRequest srvreq = (HttpServletRequest)
getMessageContext().getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
return (srvreq == null) ? false : srvreq.isUserInRole(role);
}
public Principal getUserPrincipal() {
HttpServletRequest srvreq = (HttpServletRequest)
getMessageContext().getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
return (srvreq == null) ? null : srvreq.getUserPrincipal();
}
}
| 7,419 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AxisHTTPSessionListener.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.transport.http;
import org.apache.commons.logging.Log;
import org.apache.axis.components.logger.LogFactory;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSession;
import javax.xml.rpc.server.ServiceLifecycle;
import java.util.Enumeration;
/**
* A simple listener for Servlet 2.3 session lifecycle events.
* @author Glen Daniels (gdaniels@apache.org)
*/
public class AxisHTTPSessionListener implements HttpSessionListener {
protected static Log log =
LogFactory.getLog(AxisHTTPSessionListener.class.getName());
/**
* Static method to destroy all ServiceLifecycle objects within an
* Axis session.
*/
static void destroySession(HttpSession session)
{
// Check for our marker so as not to do unneeded work
if (session.getAttribute(AxisHttpSession.AXIS_SESSION_MARKER) == null)
return;
if (log.isDebugEnabled()) {
log.debug("Got destroySession event : " + session);
}
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
Object next = e.nextElement();
if (next instanceof ServiceLifecycle) {
((ServiceLifecycle)next).destroy();
}
}
}
/** No-op for now */
public void sessionCreated(HttpSessionEvent event) {
}
/**
* Called when a session is destroyed by the servlet engine. We use
* the relevant HttpSession to look up an AxisHttpSession, and destroy
* all the appropriate objects stored therein.
*
* @param event the event descriptor passed in by the servlet engine
*/
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
destroySession(session);
}
}
| 7,420 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/HTTPTransport.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.transport.http;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Transport;
/**
* Extends Transport by implementing the setupMessageContext function to
* set HTTP-specific message context fields and transport chains.
* May not even be necessary if we arrange things differently somehow.
* Can hold state relating to URL properties.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@allaire.com)
*/
public class HTTPTransport extends Transport
{
public static final String DEFAULT_TRANSPORT_NAME = "http";
/**
* HTTP properties
*/
public static final String URL = MessageContext.TRANS_URL;
private Object cookie;
private Object cookie2;
private String action;
public HTTPTransport () {
transportName = DEFAULT_TRANSPORT_NAME;
}
/**
* helper constructor
*/
public HTTPTransport (String url, String action)
{
transportName = DEFAULT_TRANSPORT_NAME;
this.url = url;
this.action = action;
}
/**
* Set up any transport-specific derived properties in the message context.
* @param mc the context to set up
* @param call the call (unused?)
* @param engine the engine containing the registries
* @throws AxisFault if service cannot be found
*/
public void setupMessageContextImpl(MessageContext mc,
Call call,
AxisEngine engine)
throws AxisFault
{
if (action != null) {
mc.setUseSOAPAction(true);
mc.setSOAPActionURI(action);
}
// Set up any cookies we know about
if (cookie != null)
mc.setProperty(HTTPConstants.HEADER_COOKIE, cookie);
if (cookie2 != null)
mc.setProperty(HTTPConstants.HEADER_COOKIE2, cookie2);
// Allow the SOAPAction to determine the service, if the service
// (a) has not already been determined, and (b) if a service matching
// the soap action has been deployed.
if (mc.getService() == null) {
mc.setTargetService( (String)mc.getSOAPActionURI() );
}
}
public void processReturnedMessageContext(MessageContext context) {
cookie = context.getProperty(HTTPConstants.HEADER_COOKIE);
cookie2 = context.getProperty(HTTPConstants.HEADER_COOKIE2);
}
}
| 7,421 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/QSHandler.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.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
/**
* The QSHandler interface defines an interface for classes that handle the
* actions necessary when a particular query string is encountered in an AXIS
* servlet invocation.
*
* @author Curtiss Howard
*/
public interface QSHandler {
/**
* Performs the action associated with this particular query string
* handler.
*
* @param msgContext a MessageContext object containing message context
* information for this query string handler.
* @throws AxisFault if an error occurs.
*/
public void invoke (MessageContext msgContext) throws AxisFault;
}
| 7,422 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/QSMethodHandler.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.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* The QSMethodHandler class is a handler which executes a given method from an
* an AXIS service's WSDL definition when the query string "method" is
* encountered in an AXIS servlet invocation.
*
* @author Curtiss Howard (code mostly from AxisServlet class)
* @author Doug Davis (dug@us.ibm.com)
* @author Steve Loughran
*/
public class QSMethodHandler extends AbstractQueryStringHandler {
/**
* Performs the action associated with this particular query string
* handler.
*
* @param msgContext a MessageContext object containing message context
* information for this query string handler.
* @throws AxisFault if an error occurs.
*/
public void invoke (MessageContext msgContext) throws AxisFault {
// Obtain objects relevant to the task at hand from the provided
// MessageContext's bag.
configureFromContext(msgContext);
AxisServer engine = (AxisServer) msgContext.getProperty
(HTTPConstants.PLUGIN_ENGINE);
PrintWriter writer = (PrintWriter) msgContext.getProperty
(HTTPConstants.PLUGIN_WRITER);
HttpServletRequest request = (HttpServletRequest)
msgContext.getProperty (HTTPConstants.MC_HTTP_SERVLETREQUEST);
HttpServletResponse response = (HttpServletResponse)
msgContext.getProperty (HTTPConstants.MC_HTTP_SERVLETRESPONSE);
String method = null;
String args = "";
Enumeration e = request.getParameterNames();
while (e.hasMoreElements()) {
String param = (String) e.nextElement();
if (param.equalsIgnoreCase ("method")) {
method = request.getParameter (param);
}
else {
args += "<" + param + ">" + request.getParameter (param) +
"</" + param + ">";
}
}
if (method == null) {
response.setContentType ("text/html");
response.setStatus (HttpServletResponse.SC_BAD_REQUEST);
writer.println ("<h2>" + Messages.getMessage ("error00") +
": " + Messages.getMessage ("invokeGet00") + "</h2>");
writer.println ("<p>" + Messages.getMessage ("noMethod01") +
"</p>");
}
else {
invokeEndpointFromGet (msgContext, response, writer, method, args);
}
}
/**
* invoke an endpoint from a get request by building an XML request and
* handing it down. If anything goes wrong, we generate an XML formatted
* axis fault
* @param msgContext current message
* @param response to return data
* @param writer output stream
* @param method method to invoke (may be null)
* @param args argument list in XML form
* @throws AxisFault iff something goes wrong when turning the response message
* into a SOAP string.
*/
private void invokeEndpointFromGet (MessageContext msgContext,
HttpServletResponse response, PrintWriter writer, String method,
String args) throws AxisFault {
String body = "<" + method + ">" + args + "</" + method + ">";
String msgtxt = "<SOAP-ENV:Envelope" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
Message responseMsg = null;
try {
AxisServer engine = (AxisServer) msgContext.getProperty
(HTTPConstants.PLUGIN_ENGINE);
Message msg = new Message (msgtxt, false);
msgContext.setRequestMessage (msg);
engine.invoke (msgContext);
responseMsg = msgContext.getResponseMessage();
//turn off caching for GET requests
response.setHeader ("Cache-Control", "no-cache");
response.setHeader ("Pragma", "no-cache");
if (responseMsg == null) {
//tell everyone that something is wrong
throw new Exception (Messages.getMessage ("noResponse01"));
}
}
catch (AxisFault fault) {
processAxisFault (fault);
configureResponseFromAxisFault (response, fault);
if (responseMsg == null) {
responseMsg = new Message (fault);
responseMsg.setMessageContext(msgContext);
}
}
catch (Exception e) {
response.setStatus (HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
responseMsg = convertExceptionToAxisFault (e, responseMsg);
}
//this call could throw an AxisFault. We delegate it up, because
//if we cant write the message there is not a lot we can do in pure SOAP terms.
response.setContentType ("text/xml");
writer.println (responseMsg.getSOAPPartAsString());
}
}
| 7,423 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AxisServletBase.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.
*/
package org.apache.axis.transport.http;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.AxisProperties;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.EngineConfigurationFactoryFinder;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.JavaUtils;
import org.apache.commons.logging.Log;
/**
* Base class for servlets used in axis, has common methods
* to get and save the engine to a common location, currently the
* webapp's context, though some alternate persistence mechanism is always
* possible. Also has a load counter shared by all servlets; tracks the
* # of active http requests open to any of the subclasses.
* @author Steve Loughran
*/
public class AxisServletBase extends HttpServlet {
/**
* per-instance cache of the axis server
*/
protected AxisServer axisServer = null;
private static Log log =
LogFactory.getLog(AxisServlet.class.getName());
private static boolean isDebug = false;
/**
* count number of service requests in progress
*/
private static int loadCounter = 0;
/**
* and a lock
*/
private static Object loadCounterLock = new Object();
/**
* name of the axis engine to use in the servlet context
*/
protected static final String ATTR_AXIS_ENGINE =
"AxisEngine" ;
/**
* Cached path to our WEB-INF directory
*/
private String webInfPath = null;
/**
* Cached path to our "root" dir
*/
private String homeDir = null;
/**
* flag set to true for a 'production' server
*/
private boolean isDevelopment;
/**
* property name for a production server
*/
private static final String INIT_PROPERTY_DEVELOPMENT_SYSTEM=
"axis.development.system";
/**
* our initialize routine; subclasses should call this if they override it
*/
public void init() throws javax.servlet.ServletException {
ServletContext context = getServletConfig().getServletContext();
webInfPath = context.getRealPath("/WEB-INF");
homeDir = context.getRealPath("/");
isDebug = log.isDebugEnabled();
if(log.isDebugEnabled()) log.debug("In AxisServletBase init");
isDevelopment= JavaUtils.isTrueExplicitly(getOption(context,
INIT_PROPERTY_DEVELOPMENT_SYSTEM, null));
}
/**
* Destroy method is called when the servlet is going away. Pass this
* down to the AxisEngine to let it clean up... But don't create the
* engine if it hasn't already been created.
* TODO: Fixme for multiple servlets.
* This has always been slightly broken
* (the context's copy stayed around), but now we have extracted it into
* a superclass it is blatantly broken.
*/
public void destroy() {
super.destroy();
//if we have had anything to do with creating an axis server
if (axisServer != null) {
//then we lock it
synchronized(axisServer) {
if (axisServer != null) {
//clean it up
axisServer.cleanup();
//and erase our history of it
axisServer =null;
storeEngine(this,null);
}
}
}
}
/**
* get the engine for this servlet from cache or context
* @return
* @throws AxisFault
*/
public AxisServer getEngine() throws AxisFault {
if (axisServer == null)
axisServer = getEngine(this);
return axisServer;
}
/**
* This is a uniform method of initializing AxisServer in a servlet
* context.
* TODO: add catch for not being able to cast the context attr to an
* engine and reinit the engine if so.
*/
public static AxisServer getEngine(HttpServlet servlet) throws AxisFault
{
AxisServer engine = null;
if (isDebug)
log.debug("Enter: getEngine()");
ServletContext context = servlet.getServletContext();
synchronized (context) {
engine = retrieveEngine(servlet);
if (engine == null) {
Map environment = getEngineEnvironment(servlet);
// Obtain an AxisServer by using whatever AxisServerFactory is
// registered. The default one will just use the provider we
// passed in, and presumably JNDI ones will use the ServletContext
// to figure out a JNDI name to look up.
//
// The point of doing this rather than just creating the server
// manually with the provider above is that we will then support
// configurations where the server instance is managed by the
// container, and pre-registered in JNDI at deployment time. It
// also means we put the standard configuration pattern in one
// place.
engine = AxisServer.getServer(environment);
// attach the AxisServer with the current Servlet
engine.setName(servlet.getServletName());
storeEngine(servlet, engine);
}
}
if (isDebug)
log.debug("Exit: getEngine()");
return engine;
}
/**
* put the engine back in to the context.
* @param context servlet context to use
* @param engine reference to the engine. If null, the engine is removed
*/
private static void storeEngine(HttpServlet servlet, AxisServer engine) {
ServletContext context = servlet.getServletContext();
String axisServletName = servlet.getServletName();
if (engine == null) {
context.removeAttribute(axisServletName + ATTR_AXIS_ENGINE);
// find if there is other AxisEngine in Context
AxisServer server = (AxisServer) context.getAttribute(ATTR_AXIS_ENGINE);
// no other AxisEngine in ServletContext
if (server != null && servlet.getServletName().equals(server.getName())) {
context.removeAttribute(ATTR_AXIS_ENGINE);
}
} else {
if (context.getAttribute(ATTR_AXIS_ENGINE) == null) {
// first Axis servlet to store its AxisEngine
// use default name
context.setAttribute(ATTR_AXIS_ENGINE, engine);
}
context.setAttribute(axisServletName + ATTR_AXIS_ENGINE, engine);
}
}
/**
* Get an engine from the servlet context; robust againt serialization
* issues of hot-updated webapps. Remember than if a webapp is marked
* as distributed, there is more than 1 servlet context, hence more than
* one AxisEngine instance
* @param servlet
* @return the engine or null if either the engine couldnt be found or
* the attribute wasnt of the right type
*/
private static AxisServer retrieveEngine(HttpServlet servlet) {
Object contextObject = servlet.getServletContext().getAttribute(servlet.getServletName() + ATTR_AXIS_ENGINE);
if (contextObject == null) {
// if AxisServer not found :
// fall back to the "default" AxisEngine
contextObject = servlet.getServletContext().getAttribute(ATTR_AXIS_ENGINE);
}
if (contextObject instanceof AxisServer) {
AxisServer server = (AxisServer) contextObject;
// if this is "our" Engine
if (server != null && servlet.getServletName().equals(server.getName())) {
return server;
}
return null;
} else {
return null;
}
}
/**
* extract information from the servlet configuration files
* @param servlet
* @return
*/
protected static Map getEngineEnvironment(HttpServlet servlet) {
Map environment = new HashMap();
String attdir = AxisProperties.getProperty(AxisEngine.ENV_ATTACHMENT_DIR);
if (attdir == null) {
attdir = servlet.getInitParameter(AxisEngine.ENV_ATTACHMENT_DIR);
}
if (attdir == null) {
attdir = servlet.getServletContext().getInitParameter(AxisEngine.ENV_ATTACHMENT_DIR);
}
if (attdir != null)
environment.put(AxisEngine.ENV_ATTACHMENT_DIR, attdir);
ServletContext context = servlet.getServletContext();
environment.put(AxisEngine.ENV_SERVLET_CONTEXT, context);
String webInfPath = context.getRealPath("/WEB-INF");
if (webInfPath != null)
environment.put(AxisEngine.ENV_SERVLET_REALPATH,
webInfPath + File.separator + "attachments");
EngineConfiguration config =
EngineConfigurationFactoryFinder.newFactory(servlet)
.getServerEngineConfig();
if (config != null) {
environment.put(EngineConfiguration.PROPERTY_NAME, config);
}
return environment;
}
/**
* get a count of the # of services running. This is only
* ever an approximate number in a busy system
*
* @return The TotalServiceCount value
*/
public static int getLoadCounter() {
return loadCounter;
}
/**
* thread safe lock counter increment
*/
protected static void incLockCounter() {
synchronized(loadCounterLock) {
loadCounter++;
}
}
/**
* thread safe lock counter decrement
*/
protected static void decLockCounter() {
synchronized(loadCounterLock) {
loadCounter--;
}
}
/**
* subclass of service method that tracks entry count; calls the
* parent's implementation to have the http method cracked and delegated
* to the doGet, doPost method.
* @param req request
* @param resp response
* @throws ServletException something went wrong
* @throws IOException something different went wrong
*/
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
incLockCounter();
try {
super.service(req, resp);
}
finally {
decLockCounter();
}
}
/**
* extract the base of our webapp from an inbound request
*
* @param request request containing http://foobar/axis/services/something
* @return some URL like http://foobar:8080/axis/
*/
protected String getWebappBase(HttpServletRequest request) {
StringBuffer baseURL=new StringBuffer(128);
baseURL.append(request.getScheme());
baseURL.append("://");
baseURL.append(request.getServerName());
if(request.getServerPort()!=80) {
baseURL.append(":");
baseURL.append(request.getServerPort());
}
baseURL.append(request.getContextPath());
return baseURL.toString();
}
/**
* what is the servlet context
* @return get the context from the servlet config
*/
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
/**
* accessor to webinf
* @return path to WEB-INF/ in the local filesystem
*/
protected String getWebInfPath() {
return webInfPath;
}
/**
* what is the root dir of the applet?
* @return path of root dir
*/
protected String getHomeDir() {
return homeDir;
}
/**
* Retrieve option, in order of precedence:
* (Managed) System property (see discovery.ManagedProperty),
* servlet init param, context init param.
* Use of system properties is discouraged in production environments,
* as it overrides everything else.
*/
protected String getOption(ServletContext context,
String param,
String dephault)
{
String value = AxisProperties.getProperty(param);
if (value == null)
value = getInitParameter(param);
if (value == null)
value = context.getInitParameter(param);
try {
AxisServer engine = getEngine(this);
if (value == null && engine != null)
value = (String) engine.getOption(param);
} catch (AxisFault axisFault) {
}
return (value != null) ? value : dephault;
}
/**
* probe for the system being 'production'
* @return true for a dev system.
*/
public boolean isDevelopment() {
return isDevelopment;
}
}
| 7,424 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/AxisServlet.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.transport.http;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpUtils;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.ConfigurationException;
import org.apache.axis.Constants;
import org.apache.axis.Handler;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.security.servlet.ServletSecurityProvider;
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.Element;
/**
*
* @author Doug Davis (dug@us.ibm.com)
* @author Steve Loughran
* xdoclet tags are not active yet; keep web.xml in sync.
* To change the location of the services, change url-pattern in web.xml and
* set parameter axis.servicesPath in server-config.wsdd. For more information see
* <a href="http://ws.apache.org/axis/java/reference.html">Axis Reference Guide</a>.
*/
public class AxisServlet extends AxisServletBase {
protected static Log log =
LogFactory.getLog(AxisServlet.class.getName());
/**
* this log is for timing
*/
private static Log tlog =
LogFactory.getLog(Constants.TIME_LOG_CATEGORY);
/**
* a separate log for exceptions lets users route them
* differently from general low level debug info
*/
private static Log exceptionLog =
LogFactory.getLog(Constants.EXCEPTION_LOG_CATEGORY);
public static final String INIT_PROPERTY_TRANSPORT_NAME =
"transport.name";
public static final String INIT_PROPERTY_USE_SECURITY =
"use-servlet-security";
public static final String INIT_PROPERTY_ENABLE_LIST =
"axis.enableListQuery";
public static final String INIT_PROPERTY_JWS_CLASS_DIR =
"axis.jws.servletClassDir";
// This will turn off the list of available services
public static final String INIT_PROPERTY_DISABLE_SERVICES_LIST =
"axis.disableServiceList";
// Location of the services as defined by the servlet-mapping in web.xml
public static final String INIT_PROPERTY_SERVICES_PATH =
"axis.servicesPath";
// These have default values.
private String transportName;
private Handler transport;
private ServletSecurityProvider securityProvider = null;
private String servicesPath;
/**
* cache of logging debug option; only evaluated at init time.
* So no dynamic switching of logging options with this servlet.
*/
private static boolean isDebug = false;
/**
* Should we enable the "?list" functionality on GETs? (off by
* default because deployment information is a potential security
* hole)
*/
private boolean enableList = false;
/**
* Should we turn off the list of services when we receive a GET
* at the servlet root?
*/
private boolean disableServicesList = false;
/**
* Cached path to JWS output directory
*/
private String jwsClassDir = null;
protected String getJWSClassDir() {return jwsClassDir;
}
/**
* create a new servlet instance
*/
public AxisServlet() {
}
/**
* Initialization method.
*/
public void init() throws javax.servlet.ServletException {
super.init();
ServletContext context = getServletConfig().getServletContext();
isDebug = log.isDebugEnabled();
if (isDebug) {
log.debug("In servlet init");
}
transportName = getOption(context,
INIT_PROPERTY_TRANSPORT_NAME,
HTTPTransport.DEFAULT_TRANSPORT_NAME);
if (JavaUtils.isTrueExplicitly(getOption(context,
INIT_PROPERTY_USE_SECURITY, null))) {
securityProvider = new ServletSecurityProvider();
}
enableList =
JavaUtils.isTrueExplicitly(getOption(context,
INIT_PROPERTY_ENABLE_LIST, null));
jwsClassDir = getOption(context, INIT_PROPERTY_JWS_CLASS_DIR, null);
// Should we list services?
disableServicesList = JavaUtils.isTrue(getOption(context,
INIT_PROPERTY_DISABLE_SERVICES_LIST, "false"));
servicesPath = getOption(context, INIT_PROPERTY_SERVICES_PATH,
"/services/");
/**
* There are DEFINATE problems here if
* getHomeDir and/or getDefaultJWSClassDir return null
* (as they could with WebLogic).
* This needs to be reexamined in the future, but this
* should fix any NPE's in the mean time.
*/
if (jwsClassDir != null) {
if (getHomeDir() != null && !new File(jwsClassDir).isAbsolute()) {
jwsClassDir = getHomeDir() + jwsClassDir;
}
} else {
jwsClassDir = getDefaultJWSClassDir();
}
initQueryStringHandlers();
}
/**
* Process GET requests. This includes handoff of pseudo-SOAP requests
*
* @param request request in
* @param response request out
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
if (isDebug) {
log.debug("Enter: doGet()");
}
PrintWriter writer = new FilterPrintWriter(response);
try {
AxisEngine engine = getEngine();
ServletContext servletContext =
getServletConfig().getServletContext();
String pathInfo = request.getPathInfo();
String realpath = servletContext.getRealPath(request.getServletPath());
if (realpath == null) {
realpath = request.getServletPath();
}
//JWS pages are special; they are the servlet path and there
//is no pathinfo...we map the pathinfo to the servlet path to keep
//it happy
boolean isJWSPage = request.getRequestURI().endsWith(".jws");
if (isJWSPage) {
pathInfo = request.getServletPath();
}
// Try to execute a query string plugin and return upon success.
if (processQuery(request, response, writer) == true) {
return;
}
boolean hasNoPath = (pathInfo == null || pathInfo.equals(""));
if (!disableServicesList) {
if(hasNoPath) {
// If the user requested the servlet (i.e. /axis/servlet/AxisServlet)
// with no service name, present the user with a list of deployed
// services to be helpful
// Don't do this if has been turned off
reportAvailableServices(response, writer, request);
} else if (realpath != null) {
// We have a pathname, so now we perform WSDL or list operations
// get message context w/ various properties set
MessageContext msgContext = createMessageContext(engine,
request, response);
// NOTE: HttpUtils.getRequestURL has been deprecated.
// This line SHOULD be:
// String url = req.getRequestURL().toString()
// HOWEVER!!!! DON'T REPLACE IT! There's a bug in
// req.getRequestURL that is not in HttpUtils.getRequestURL
// req.getRequestURL returns "localhost" in the remote
// scenario rather than the actual host name.
//
// But more importantly, getRequestURL() is a servlet 2.3
// API and to support servlet 2.2 (aka WebSphere 4)
// we need to leave this in for a while longer. tomj 10/14/2004
//
String url = HttpUtils.getRequestURL(request).toString();
msgContext.setProperty(MessageContext.TRANS_URL, url);
// See if we can locate the desired service. If we
// can't, return a 404 Not Found. Otherwise, just
// print the placeholder message.
String serviceName;
if (pathInfo.startsWith("/")) {
serviceName = pathInfo.substring(1);
} else {
serviceName = pathInfo;
}
SOAPService s = engine.getService(serviceName);
if (s == null) {
//no service: report it
if (isJWSPage) {
reportCantGetJWSService(request, response, writer);
} else {
reportCantGetAxisService(request, response, writer);
}
} else {
//print a snippet of service info.
reportServiceInfo(response, writer, s, serviceName);
}
}
} else {
// We didn't have a real path in the request, so just
// print a message informing the user that they reached
// the servlet.
response.setContentType("text/html; charset=utf-8");
writer.println("<html><h1>Axis HTTP Servlet</h1>");
writer.println(Messages.getMessage("reachedServlet00"));
writer.println("<p>" +
Messages.getMessage("transportName00",
"<b>" + transportName + "</b>"));
writer.println("</html>");
}
} catch (AxisFault fault) {
reportTroubleInGet(fault, response, writer);
} catch (Exception e) {
reportTroubleInGet(e, response, writer);
} finally {
writer.close();
if (isDebug) {
log.debug("Exit: doGet()");
}
}
}
/**
* when we get an exception or an axis fault in a GET, we handle
* it almost identically: we go 'something went wrong', set the response
* code to 500 and then dump info. But we dump different info for an axis fault
* or subclass thereof.
* @param exception what went wrong
* @param response current response
* @param writer open writer to response
*/
private void reportTroubleInGet(Throwable exception,
HttpServletResponse response,
PrintWriter writer) {
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
writer.println("<h2>" +
Messages.getMessage("error00") +
"</h2>");
writer.println("<p>" +
Messages.getMessage("somethingWrong00") +
"</p>");
if (exception instanceof AxisFault) {
AxisFault fault = (AxisFault) exception;
processAxisFault(fault);
writeFault(writer, fault);
} else {
logException(exception);
writer.println("<pre>Exception - " + exception + "<br>");
//dev systems only give fault dumps
if (isDevelopment()) {
writer.println(JavaUtils.stackToString(exception));
}
writer.println("</pre>");
}
}
/**
* routine called whenever an axis fault is caught; where they
* are logged and any other business. The method may modify the fault
* in the process
* @param fault what went wrong.
*/
protected void processAxisFault(AxisFault fault) {
//log the fault
Element runtimeException = fault.lookupFaultDetail(
Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
if (runtimeException != null) {
exceptionLog.info(Messages.getMessage("axisFault00"), fault);
//strip runtime details
fault.removeFaultDetail(Constants.
QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
} else if (exceptionLog.isDebugEnabled()) {
exceptionLog.debug(Messages.getMessage("axisFault00"), fault);
}
//dev systems only give fault dumps
if (!isDevelopment()) {
//strip out the stack trace
fault.removeFaultDetail(Constants.QNAME_FAULTDETAIL_STACKTRACE);
}
}
/**
* log any exception to our output log, at our chosen level
* @param e what went wrong
*/
protected void logException(Throwable e) {
exceptionLog.info(Messages.getMessage("exception00"), e);
}
/**
* this method writes a fault out to an HTML stream. This includes
* escaping the strings to defend against cross-site scripting attacks
* @param writer
* @param axisFault
*/
private void writeFault(PrintWriter writer, AxisFault axisFault) {
String localizedMessage = XMLUtils.xmlEncodeString(axisFault.
getLocalizedMessage());
writer.println("<pre>Fault - " + localizedMessage + "<br>");
writer.println(axisFault.dumpToString());
writer.println("</pre>");
}
/**
* print a snippet of service info.
* @param service service
* @param writer output channel
* @param serviceName where to put stuff
*/
protected void reportServiceInfo(HttpServletResponse response,
PrintWriter writer, SOAPService service,
String serviceName) {
response.setContentType("text/html; charset=utf-8");
writer.println("<h1>"
+ service.getName()
+ "</h1>");
writer.println(
"<p>" +
Messages.getMessage("axisService00") +
"</p>");
writer.println(
"<i>" +
Messages.getMessage("perhaps00") +
"</i>");
}
/**
* report that we have no WSDL
*
* This method was moved to the querystring handler QSWSDLHandler. The
* method reportNoWSDL in AxisServlet is never called. Perhaps the method
* is overwritten in subclasses of AxisServlet so the method wasn't
* removed. See the discussion in
*
* http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23845
*
* @param res
* @param writer
* @param moreDetailCode optional name of a message to provide more detail
* @param axisFault optional fault string, for extra info at debug time only
*/
protected void reportNoWSDL(HttpServletResponse res, PrintWriter writer,
String moreDetailCode, AxisFault axisFault) {
}
/**
* This method lists the available services; it is called when there is
* nothing to execute on a GET
* @param response
* @param writer
* @param request
* @throws ConfigurationException
* @throws AxisFault
*/
protected void reportAvailableServices(HttpServletResponse response,
PrintWriter writer,
HttpServletRequest request) throws
ConfigurationException, AxisFault {
AxisEngine engine = getEngine();
response.setContentType("text/html; charset=utf-8");
writer.println("<h2>And now... Some Services</h2>");
Iterator i;
try {
i = engine.getConfig().getDeployedServices();
} catch (ConfigurationException configException) {
//turn any internal configuration exceptions back into axis faults
//if that is what they are
if (configException.getContainedException() instanceof AxisFault) {
throw (AxisFault) configException.getContainedException();
} else {
throw configException;
}
}
// baseURL may change if <endpointURL> tag is used for
// custom deployment at a different location
String defaultBaseURL = getWebappBase(request) + servicesPath;
writer.println("<ul>");
while (i.hasNext()) {
ServiceDesc sd = (ServiceDesc) i.next();
StringBuffer sb = new StringBuffer();
sb.append("<li>");
String name = sd.getName();
sb.append(name);
sb.append(" <a href=\"");
String endpointURL = sd.getEndpointURL();
String baseURL = (endpointURL == null) ? defaultBaseURL :
endpointURL;
sb.append(baseURL);
sb.append(name);
sb.append("?wsdl\"><i>(wsdl)</i></a></li>");
writer.println(sb.toString());
ArrayList operations = sd.getOperations();
if (!operations.isEmpty()) {
writer.println("<ul>");
for (Iterator it = operations.iterator(); it.hasNext(); ) {
OperationDesc desc = (OperationDesc) it.next();
writer.println("<li>" + desc.getName());
}
writer.println("</ul>");
}
}
writer.println("</ul>");
}
/**
* generate the error response to indicate that there is apparently no endpoint there
* @param request the request that didnt have an edpoint
* @param response response we are generating
* @param writer open writer for the request
*/
protected void reportCantGetAxisService(HttpServletRequest request,
HttpServletResponse response,
PrintWriter writer) {
// no such service....
response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
response.setContentType("text/html; charset=utf-8");
writer.println("<h2>" +
Messages.getMessage("error00") + "</h2>");
writer.println("<p>" +
Messages.getMessage("noService06") +
"</p>");
}
/**
* probe for a JWS page and report 'no service' if one is not found there
* @param request the request that didnt have an edpoint
* @param response response we are generating
* @param writer open writer for the request
*/
protected void reportCantGetJWSService(HttpServletRequest request,
HttpServletResponse response,
PrintWriter writer) {
// first look to see if there is a service
// requestPath is a work around to support serving .jws web services
// from services URL - see AXIS-843 for more information
String requestPath = request.getServletPath() + ((request.getPathInfo() != null) ?
request.getPathInfo() : "");
String realpath = getServletConfig().getServletContext()
.getRealPath(requestPath);
log.debug("JWS real path: " + realpath);
boolean foundJWSFile = (new File(realpath).exists()) &&
(realpath.endsWith(Constants.
JWS_DEFAULT_FILE_EXTENSION));
response.setContentType("text/html; charset=utf-8");
if (foundJWSFile) {
response.setStatus(HttpURLConnection.HTTP_OK);
writer.println(Messages.getMessage("foundJWS00") + "<p>");
String url = request.getRequestURI();
String urltext = Messages.getMessage("foundJWS01");
writer.println("<a href='" + url + "?wsdl'>" + urltext + "</a>");
} else {
response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
writer.println(Messages.getMessage("noService06"));
}
}
/**
* Process a POST to the servlet by handing it off to the Axis Engine.
* Here is where SOAP messages are received
* @param req posted request
* @param res respose
* @throws ServletException trouble
* @throws IOException different trouble
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
String soapAction = null;
MessageContext msgContext = null;
if (isDebug) {
log.debug("Enter: doPost()");
}
if (tlog.isDebugEnabled()) {
t0 = System.currentTimeMillis();
}
Message responseMsg = null;
String contentType = null;
try {
AxisEngine engine = getEngine();
if (engine == null) {
// !!! should return a SOAP fault...
ServletException se =
new ServletException(Messages.getMessage("noEngine00"));
log.debug("No Engine!", se);
throw se;
}
res.setBufferSize(1024 * 8); // provide performance boost.
/** get message context w/ various properties set
*/
msgContext = createMessageContext(engine, req, res);
// ? OK to move this to 'getMessageContext',
// ? where it would also be picked up for 'doGet()' ?
if (securityProvider != null) {
if (isDebug) {
log.debug("securityProvider:" + securityProvider);
}
msgContext.setProperty(MessageContext.SECURITY_PROVIDER,
securityProvider);
}
/* Get request message
*/
Message requestMsg =
new Message(req.getInputStream(),
false,
req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
req.getHeader(HTTPConstants.
HEADER_CONTENT_LOCATION));
// Transfer HTTP headers to MIME headers for request message.
MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
for (Enumeration e = req.getHeaderNames(); e.hasMoreElements(); ) {
String headerName = (String) e.nextElement();
for (Enumeration f = req.getHeaders(headerName);
f.hasMoreElements(); ) {
String headerValue = (String) f.nextElement();
requestMimeHeaders.addHeader(headerName, headerValue);
}
}
if (isDebug) {
log.debug("Request Message:" + requestMsg);
/* Set the request(incoming) message field in the context */
/**********************************************************/
}
msgContext.setRequestMessage(requestMsg);
String url = HttpUtils.getRequestURL(req).toString();
msgContext.setProperty(MessageContext.TRANS_URL, url);
// put character encoding of request to message context
// in order to reuse it during the whole process.
String requestEncoding;
try {
requestEncoding = (String) requestMsg.getProperty(SOAPMessage.
CHARACTER_SET_ENCODING);
if (requestEncoding != null) {
msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
requestEncoding);
}
} catch (SOAPException e1) {
}
try {
/**
* Save the SOAPAction header in the MessageContext bag.
* This will be used to tell the Axis Engine which service
* is being invoked. This will save us the trouble of
* having to parse the Request message - although we will
* need to double-check later on that the SOAPAction header
* does in fact match the URI in the body.
*/
// (is this last stmt true??? (I don't think so - Glen))
/********************************************************/
soapAction = getSoapAction(req);
if (soapAction != null) {
msgContext.setUseSOAPAction(true);
msgContext.setSOAPActionURI(soapAction);
}
// Create a Session wrapper for the HTTP session.
// These can/should be pooled at some point.
// (Sam is Watching! :-)
msgContext.setSession(new AxisHttpSession(req));
if (tlog.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
/* Invoke the Axis engine... */
/*****************************/
if (isDebug) {
log.debug("Invoking Axis Engine.");
//here we run the message by the engine
}
engine.invoke(msgContext);
if (isDebug) {
log.debug("Return from Axis Engine.");
}
if (tlog.isDebugEnabled()) {
t2 = System.currentTimeMillis();
}
responseMsg = msgContext.getResponseMessage();
// We used to throw exceptions on null response messages.
// They are actually OK in certain situations (asynchronous
// services), so fall through here and return an ACCEPTED
// status code below. Might want to install a configurable
// error check for this later.
} catch (AxisFault fault) {
//log and sanitize
processAxisFault(fault);
configureResponseFromAxisFault(res, fault);
responseMsg = msgContext.getResponseMessage();
if (responseMsg == null) {
responseMsg = new Message(fault);
((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).
getMessage().setMessageContext(msgContext);
}
} catch (Exception e) {
//other exceptions are internal trouble
responseMsg = msgContext.getResponseMessage();
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
responseMsg = convertExceptionToAxisFault(e, responseMsg);
((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).
getMessage().setMessageContext(msgContext);
} catch (Throwable t) {
logException(t);
//other exceptions are internal trouble
responseMsg = msgContext.getResponseMessage();
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
responseMsg = new Message(new AxisFault(t.toString(),t));
((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).
getMessage().setMessageContext(msgContext);
}
} catch (AxisFault fault) {
processAxisFault(fault);
configureResponseFromAxisFault(res, fault);
responseMsg = msgContext.getResponseMessage();
if (responseMsg == null) {
responseMsg = new Message(fault);
((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).
getMessage().setMessageContext(msgContext);
}
}
if (tlog.isDebugEnabled()) {
t3 = System.currentTimeMillis();
}
/* Send response back along the wire... */
/***********************************/
if (responseMsg != null) {
// Transfer MIME headers to HTTP headers for response message.
MimeHeaders responseMimeHeaders = responseMsg.getMimeHeaders();
for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader responseMimeHeader = (MimeHeader) i.next();
res.addHeader(responseMimeHeader.getName(),
responseMimeHeader.getValue());
}
// synchronize the character encoding of request and response
String responseEncoding = (String) msgContext.getProperty(
SOAPMessage.CHARACTER_SET_ENCODING);
if (responseEncoding != null) {
try {
responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
responseEncoding);
} catch (SOAPException e) {
}
}
//determine content type from message response
contentType = responseMsg.getContentType(msgContext.
getSOAPConstants());
sendResponse(contentType, res, responseMsg);
} else {
// No content, so just indicate accepted
res.setStatus(HttpServletResponse.SC_ACCEPTED);
}
if (isDebug) {
log.debug("Response sent.");
log.debug("Exit: doPost()");
}
if (tlog.isDebugEnabled()) {
t4 = System.currentTimeMillis();
tlog.debug("axisServlet.doPost: " + soapAction +
" pre=" + (t1 - t0) +
" invoke=" + (t2 - t1) +
" post=" + (t3 - t2) +
" send=" + (t4 - t3) +
" " + msgContext.getTargetService() + "." +
((msgContext.getOperation() == null) ?
"" : msgContext.getOperation().getName()));
}
}
/**
* Configure the servlet response status code and maybe other headers
* from the fault info.
* @param response response to configure
* @param fault what went wrong
*/
private void configureResponseFromAxisFault(HttpServletResponse response,
AxisFault fault) {
// then get the status code
// It's been suggested that a lack of SOAPAction
// should produce some other error code (in the 400s)...
int status = getHttpServletResponseStatus(fault);
if (status == HttpServletResponse.SC_UNAUTHORIZED) {
// unauth access results in authentication request
// TODO: less generic realm choice?
response.setHeader("WWW-Authenticate", "Basic realm=\"AXIS\"");
}
response.setStatus(status);
}
/**
* turn any Exception into an AxisFault, log it, set the response
* status code according to what the specifications say and
* return a response message for posting. This will be the response
* message passed in if non-null; one generated from the fault otherwise.
*
* @param exception what went wrong
* @param responseMsg what response we have (if any)
* @return a response message to send to the user
*/
private Message convertExceptionToAxisFault(Exception exception,
Message responseMsg) {
logException(exception);
if (responseMsg == null) {
AxisFault fault = AxisFault.makeFault(exception);
processAxisFault(fault);
responseMsg = new Message(fault);
}
return responseMsg;
}
/**
* Extract information from AxisFault and map it to a HTTP Status code.
*
* @param af Axis Fault
* @return HTTP Status code.
*/
protected int getHttpServletResponseStatus(AxisFault af) {
// TODO: Should really be doing this with explicit AxisFault
// subclasses... --Glen
return af.getFaultCode().getLocalPart().startsWith("Server.Unauth")
? HttpServletResponse.SC_UNAUTHORIZED
: HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
// This will raise a 401 for both
// "Unauthenticated" & "Unauthorized"...
}
/**
* write a message to the response, set appropriate headers for content
* type..etc.
* @param res response
* @param responseMsg message to write
* @throws AxisFault
* @throws IOException if the response stream can not be written to
*/
private void sendResponse(String contentType,
HttpServletResponse res,
Message responseMsg) throws AxisFault,
IOException {
if (responseMsg == null) {
res.setStatus(HttpServletResponse.SC_NO_CONTENT);
if (isDebug) {
log.debug("NO AXIS MESSAGE TO RETURN!");
//String resp = Messages.getMessage("noData00");
//res.setContentLength((int) resp.getBytes().length);
//res.getWriter().print(resp);
}
} else {
if (isDebug) {
log.debug("Returned Content-Type:" +
contentType);
// log.debug("Returned Content-Length:" +
// responseMsg.getContentLength());
}
try {
res.setContentType(contentType);
/* My understand of Content-Length
* HTTP 1.0
* -Required for requests, but optional for responses.
* HTTP 1.1
* - Either Content-Length or HTTP Chunking is required.
* Most servlet engines will do chunking if content-length is not specified.
*
*
*/
//if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary.
// res.setContentLength(responseMsg.getContentLength());
responseMsg.writeTo(res.getOutputStream());
} catch (SOAPException e) {
logException(e);
}
}
if (!res.isCommitted()) {
res.flushBuffer(); // Force it right now.
}
}
/**
* Place the Request message in the MessagContext object - notice
* that we just leave it as a 'ServletRequest' object and let the
* Message processing routine convert it - we don't do it since we
* don't know how it's going to be used - perhaps it might not
* even need to be parsed.
* @return a message context
*/
private MessageContext createMessageContext(AxisEngine engine,
HttpServletRequest req,
HttpServletResponse res) {
MessageContext msgContext = new MessageContext(engine);
String requestPath = getRequestPath(req);
if (isDebug) {
log.debug("MessageContext:" + msgContext);
log.debug("HEADER_CONTENT_TYPE:" +
req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE));
log.debug("HEADER_CONTENT_LOCATION:" +
req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
log.debug("Constants.MC_HOME_DIR:" + String.valueOf(getHomeDir()));
log.debug("Constants.MC_RELATIVE_PATH:" + requestPath);
log.debug("HTTPConstants.MC_HTTP_SERVLETLOCATION:" +
String.valueOf(getWebInfPath()));
log.debug("HTTPConstants.MC_HTTP_SERVLETPATHINFO:" +
req.getPathInfo());
log.debug("HTTPConstants.HEADER_AUTHORIZATION:" +
req.getHeader(HTTPConstants.HEADER_AUTHORIZATION));
log.debug("Constants.MC_REMOTE_ADDR:" + req.getRemoteAddr());
log.debug("configPath:" + String.valueOf(getWebInfPath()));
}
/* Set the Transport */
/*********************/
msgContext.setTransportName(transportName);
/* Save some HTTP specific info in the bag in case someone needs it */
/********************************************************************/
msgContext.setProperty(Constants.MC_JWS_CLASSDIR, jwsClassDir);
msgContext.setProperty(Constants.MC_HOME_DIR, getHomeDir());
msgContext.setProperty(Constants.MC_RELATIVE_PATH, requestPath);
msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLET, this);
msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST, req);
msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE, res);
msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETLOCATION,
getWebInfPath());
msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO,
req.getPathInfo());
msgContext.setProperty(HTTPConstants.HEADER_AUTHORIZATION,
req.getHeader(HTTPConstants.HEADER_AUTHORIZATION));
msgContext.setProperty(Constants.MC_REMOTE_ADDR, req.getRemoteAddr());
// Set up a javax.xml.rpc.server.ServletEndpointContext
ServletEndpointContextImpl sec = new ServletEndpointContextImpl();
msgContext.setProperty(Constants.MC_SERVLET_ENDPOINT_CONTEXT, sec);
/* Save the real path */
/**********************/
String realpath = getServletConfig().getServletContext()
.getRealPath(requestPath);
if (realpath != null) {
msgContext.setProperty(Constants.MC_REALPATH, realpath);
}
msgContext.setProperty(Constants.MC_CONFIGPATH, getWebInfPath());
return msgContext;
}
/**
* Extract the SOAPAction header.
* if SOAPAction is null then we'll we be forced to scan the body for it.
* if SOAPAction is "" then use the URL
* @param req incoming request
* @return the action
* @throws AxisFault
*/
private String getSoapAction(HttpServletRequest req) throws AxisFault {
String soapAction = req.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (soapAction == null) {
String contentType = req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if(contentType != null) {
int index = contentType.indexOf("action");
if(index != -1){
soapAction = contentType.substring(index + 7);
}
}
}
if (isDebug) {
log.debug("HEADER_SOAP_ACTION:" + soapAction);
/**
* Technically, if we don't find this header, we should probably fault.
* It's required in the SOAP HTTP binding.
*/
}
if (soapAction == null) {
AxisFault af = new AxisFault("Client.NoSOAPAction",
Messages.getMessage("noHeader00",
"SOAPAction"),
null, null);
exceptionLog.error(Messages.getMessage("genFault00"), af);
throw af;
}
// the SOAP 1.1 spec & WS-I 1.0 says:
// soapaction = "SOAPAction" ":" [ <"> URI-reference <"> ]
// some implementations leave off the quotes
// we strip them if they are present
if (soapAction.startsWith("\"") && soapAction.endsWith("\"")
&& soapAction.length() >= 2) {
int end = soapAction.length() - 1;
soapAction = soapAction.substring(1, end);
}
if (soapAction.length() == 0) {
soapAction = req.getContextPath(); // Is this right?
}
return soapAction;
}
/**
* Provided to allow overload of default JWSClassDir
* by derived class.
* @return directory for JWS files
*/
protected String getDefaultJWSClassDir() {
return (getWebInfPath() == null)
? null // ??? what is a good FINAL default for WebLogic?
: getWebInfPath() + File.separator + "jwsClasses";
}
/**
* Initialize a Handler for the transport defined in the Axis server config.
* This includes optionally filling in query string handlers.
*/
public void initQueryStringHandlers() {
try {
this.transport = getEngine().getTransport(this.transportName);
if (this.transport == null) {
// No transport by this name is defined. Therefore, fill in default
// query string handlers.
this.transport = new SimpleTargetedChain();
this.transport.setOption("qs.list",
"org.apache.axis.transport.http.QSListHandler");
this.transport.setOption("qs.method",
"org.apache.axis.transport.http.QSMethodHandler");
this.transport.setOption("qs.wsdl",
"org.apache.axis.transport.http.QSWSDLHandler");
return;
}
else {
// See if we should use the default query string handlers.
// By default, set this to true (for backwards compatibility).
boolean defaultQueryStrings = true;
String useDefaults = (String)this.transport.getOption(
"useDefaultQueryStrings");
if ((useDefaults != null) &&
useDefaults.toLowerCase().equals("false")) {
defaultQueryStrings = false;
}
if (defaultQueryStrings == true) {
// We should use defaults, so fill them in.
this.transport.setOption("qs.list",
"org.apache.axis.transport.http.QSListHandler");
this.transport.setOption("qs.method",
"org.apache.axis.transport.http.QSMethodHandler");
this.transport.setOption("qs.wsdl",
"org.apache.axis.transport.http.QSWSDLHandler");
}
}
}
catch (AxisFault e) {
// Some sort of problem occurred, let's just make a default transport.
this.transport = new SimpleTargetedChain();
this.transport.setOption("qs.list",
"org.apache.axis.transport.http.QSListHandler");
this.transport.setOption("qs.method",
"org.apache.axis.transport.http.QSMethodHandler");
this.transport.setOption("qs.wsdl",
"org.apache.axis.transport.http.QSWSDLHandler");
return;
}
}
/**
* Attempts to invoke a plugin for the query string supplied in the URL.
*
* @param request the servlet's HttpServletRequest object.
* @param response the servlet's HttpServletResponse object.
* @param writer the servlet's PrintWriter object.
*/
private boolean processQuery(HttpServletRequest request,
HttpServletResponse response,
PrintWriter writer) throws AxisFault {
// Attempt to instantiate a plug-in handler class for the query string
// handler classes defined in the HTTP transport.
String path = request.getServletPath();
String queryString = request.getQueryString();
String serviceName;
AxisEngine engine = getEngine();
Iterator i = this.transport.getOptions().keySet().iterator();
if (queryString == null) {
return false;
}
String servletURI = request.getContextPath() + path;
String reqURI = request.getRequestURI();
// chop off '/'.
if (servletURI.length() + 1 < reqURI.length()) {
serviceName = reqURI.substring(servletURI.length() + 1);
} else {
serviceName = "";
} while (i.hasNext() == true) {
String queryHandler = (String) i.next();
if (queryHandler.startsWith("qs.") == true) {
// Only attempt to match the query string with transport
// parameters prefixed with "qs:".
String handlerName = queryHandler.substring
(queryHandler.indexOf(".") + 1).
toLowerCase();
// Determine the name of the plugin to invoke by using all text
// in the query string up to the first occurence of &, =, or the
// whole string if neither is present.
int length = 0;
boolean firstParamFound = false;
while (firstParamFound == false && length < queryString.length()) {
char ch = queryString.charAt(length++);
if (ch == '&' || ch == '=') {
firstParamFound = true;
--length;
}
}
if (length < queryString.length()) {
queryString = queryString.substring(0, length);
}
if (queryString.toLowerCase().equals(handlerName) == true) {
// Query string matches a defined query string handler name.
// If the defined class name for this query string handler is blank,
// just return (the handler is "turned off" in effect).
if (this.transport.getOption(queryHandler).equals("")) {
return false;
}
try {
// Attempt to dynamically load the query string handler
// and its "invoke" method.
MessageContext msgContext = createMessageContext(engine,
request, response);
Class plugin = Class.forName((String)this.transport.
getOption(queryHandler));
Method pluginMethod = plugin.getDeclaredMethod("invoke",
new Class[] {msgContext.getClass()});
String url = HttpUtils.getRequestURL(request).toString();
// Place various useful servlet-related objects in
// the MessageContext object being delivered to the
// plugin.
msgContext.setProperty(MessageContext.TRANS_URL, url);
msgContext.setProperty(HTTPConstants.
PLUGIN_SERVICE_NAME, serviceName);
msgContext.setProperty(HTTPConstants.PLUGIN_NAME,
handlerName);
msgContext.setProperty(HTTPConstants.
PLUGIN_IS_DEVELOPMENT,
new Boolean(isDevelopment()));
msgContext.setProperty(HTTPConstants.PLUGIN_ENABLE_LIST,
new Boolean(enableList));
msgContext.setProperty(HTTPConstants.PLUGIN_ENGINE,
engine);
msgContext.setProperty(HTTPConstants.PLUGIN_WRITER,
writer);
msgContext.setProperty(HTTPConstants.PLUGIN_LOG, log);
msgContext.setProperty(HTTPConstants.
PLUGIN_EXCEPTION_LOG,
exceptionLog);
// Invoke the plugin.
pluginMethod.invoke(plugin.newInstance(),
new Object[] {msgContext});
writer.close();
return true;
} catch (InvocationTargetException ie) {
reportTroubleInGet(ie.getTargetException(), response,
writer);
// return true to prevent any further processing
return true;
} catch (Exception e) {
reportTroubleInGet(e, response, writer);
// return true to prevent any further processing
return true;
}
}
}
}
return false;
}
/**
* getRequestPath a returns request path for web service padded with
* request.getPathInfo for web services served from /services directory.
* This is a required to support serving .jws web services from /services
* URL. See AXIS-843 for more information.
*
* @param request HttpServletRequest
* @return String
*/
private static String getRequestPath(HttpServletRequest request) {
return request.getServletPath() + ((request.getPathInfo() != null) ?
request.getPathInfo() : "");
}
}
| 7,425 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/ChunkedOutputStream.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.transport.http;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* @author Rick Rineholt
*/
public class ChunkedOutputStream extends FilterOutputStream {
boolean eos = false;
private ChunkedOutputStream() {
super(null);
}
public ChunkedOutputStream(OutputStream os) {
super(os);
}
public void write(int b)
throws IOException {
write(new byte[] {(byte) b}, 0, 1);
}
public void write(byte[] b)
throws IOException {
write(b, 0, b.length);
}
static final byte[] CRLF = "\r\n".getBytes();
static final byte[] LAST_TOKEN = "0\r\n\r\n".getBytes();
public void write(byte[] b,
int off,
int len)
throws IOException {
if (len == 0) return;
out.write((Integer.toHexString(len)).getBytes());
out.write(CRLF);
out.write(b, off, len);
out.write(CRLF);
}
/*
public void flush()
throws IOException {
out.flush();
}
*/
public void eos()throws IOException {
synchronized (this) {
if (eos) return;
eos = true;
}
out.write(LAST_TOKEN);
out.flush();
}
public void close()
throws IOException {
eos();
out.close();
}
}
| 7,426 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/QSListHandler.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.transport.http;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import javax.servlet.http.HttpServletResponse;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Admin;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
/**
* The QSListHandler class is a handler which lists the AXIS Server's
* configuration when the query string "list" is encountered in an AXIS servlet
* invocation.
*
* @author Curtiss Howard (code mostly from AxisServlet class)
* @author Doug Davis (dug@us.ibm.com)
* @author Steve Loughran
*/
public class QSListHandler extends AbstractQueryStringHandler {
/**
* Performs the action associated with this particular query string
* handler.
*
* @param msgContext a MessageContext object containing message context
* information for this query string handler.
* @throws AxisFault if an error occurs.
*/
public void invoke (MessageContext msgContext) throws AxisFault {
// Obtain objects relevant to the task at hand from the provided
// MessageContext's bag.
boolean enableList = ((Boolean) msgContext.getProperty
(HTTPConstants.PLUGIN_ENABLE_LIST)).booleanValue();
AxisServer engine = (AxisServer) msgContext.getProperty
(HTTPConstants.PLUGIN_ENGINE);
PrintWriter writer = (PrintWriter) msgContext.getProperty
(HTTPConstants.PLUGIN_WRITER);
HttpServletResponse response = (HttpServletResponse)
msgContext.getProperty (HTTPConstants.MC_HTTP_SERVLETRESPONSE);
if (enableList) {
Document doc = Admin.listConfig (engine);
if (doc != null) {
response.setContentType ("text/xml");
XMLUtils.DocumentToWriter (doc, writer);
}
else {
//error code is 404
response.setStatus (HttpURLConnection.HTTP_NOT_FOUND);
response.setContentType ("text/html");
writer.println ("<h2>" + Messages.getMessage ("error00") +
"</h2>");
writer.println ("<p>" + Messages.getMessage ("noDeploy00") +
"</p>");
}
}
else {
// list not enable, return error
//error code is, what, 401
response.setStatus (HttpURLConnection.HTTP_FORBIDDEN);
response.setContentType ("text/html");
writer.println ("<h2>" + Messages.getMessage ("error00") +
"</h2>");
writer.println ("<p><i>?list</i> " +
Messages.getMessage ("disabled00") + "</p>");
}
}
}
| 7,427 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/transport/http/QSWSDLHandler.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.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.ConfigurationException;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
/**
* The QSWSDLHandler class is a handler which provides an AXIS service's WSDL
* document when the query string "wsdl" (ignoring case) is encountered in an
* AXIS servlet invocation.
*
* @author Curtiss Howard (code mostly from AxisServlet class)
* @author Doug Davis (dug@us.ibm.com)
* @author Steve Loughran
* @author Ian P. Springer, Sal Campana
*/
public class QSWSDLHandler extends AbstractQueryStringHandler {
/**
* Performs the action associated with this particular query string handler.
*
* @param msgContext a MessageContext object containing message context
* information for this query string handler.
* @throws AxisFault if an error occurs
*/
public void invoke(MessageContext msgContext) throws AxisFault {
// Obtain objects relevant to the task at hand from the provided
// MessageContext's bag.
configureFromContext(msgContext);
AxisServer engine = (AxisServer) msgContext.getProperty
(HTTPConstants.PLUGIN_ENGINE);
PrintWriter writer = (PrintWriter) msgContext.getProperty
(HTTPConstants.PLUGIN_WRITER);
HttpServletResponse response = (HttpServletResponse)
msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE);
try {
engine.generateWSDL(msgContext);
Document wsdlDoc = (Document) msgContext.getProperty("WSDL");
if (wsdlDoc != null) {
try {
updateSoapAddressLocationURLs(wsdlDoc, msgContext);
} catch (RuntimeException re) {
log.warn(
"Failed to update soap:address location URL(s) in WSDL.",
re);
}
response.setContentType(
"text/xml; charset=" +
XMLUtils.getEncoding().toLowerCase());
reportWSDL(wsdlDoc, writer);
} else {
if (log.isDebugEnabled()) {
log.debug("processWsdlRequest: failed to create WSDL");
}
reportNoWSDL(response, writer, "noWSDL02", null);
}
} catch (AxisFault axisFault) {
//the no-service fault is mapped to a no-wsdl error
if (axisFault.getFaultCode().equals
(Constants.QNAME_NO_SERVICE_FAULT_CODE)) {
//which we log
processAxisFault(axisFault);
//then report under a 404 error
response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
reportNoWSDL(response, writer, "noWSDL01", axisFault);
} else {
//all other faults get thrown
throw axisFault;
}
}
}
/**
* Report WSDL.
*
* @param doc
* @param writer
*/
public void reportWSDL(Document doc, PrintWriter writer) {
XMLUtils.PrettyDocumentToWriter(doc, writer);
}
/**
* Report that we have no WSDL.
*
* @param res
* @param writer
* @param moreDetailCode optional name of a message to provide more detail
* @param axisFault optional fault string, for extra info at debug time only
*/
public void reportNoWSDL(HttpServletResponse res, PrintWriter writer,
String moreDetailCode, AxisFault axisFault) {
res.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
res.setContentType("text/html");
writer.println("<h2>" + Messages.getMessage("error00") + "</h2>");
writer.println("<p>" + Messages.getMessage("noWSDL00") + "</p>");
if (moreDetailCode != null) {
writer.println("<p>" + Messages.getMessage(moreDetailCode)
+ "</p>");
}
if (axisFault != null && isDevelopment()) {
//only dev systems give fault dumps
writeFault(writer, axisFault);
}
}
/**
* Updates the soap:address locations for all ports in the WSDL using the URL from the request as
* the base portion for the updated locations, ensuring the WSDL returned to the client contains
* the correct location URL.
*
* @param wsdlDoc the WSDL as a DOM document
* @param msgContext the current Axis JAX-RPC message context
* @throws AxisFault if we fail to obtain the list of deployed service names from the server config
*/
protected void updateSoapAddressLocationURLs(Document wsdlDoc,
MessageContext msgContext)
throws AxisFault {
Set deployedServiceNames;
try {
deployedServiceNames = getDeployedServiceNames(msgContext);
}
catch (ConfigurationException ce) {
throw new AxisFault("Failed to determine deployed service names.", ce);
}
NodeList wsdlPorts = wsdlDoc.getDocumentElement().getElementsByTagNameNS(Constants.NS_URI_WSDL11, "port");
if (wsdlPorts != null) {
String endpointURL = getEndpointURL(msgContext);
String baseEndpointURL = endpointURL.substring(0, endpointURL.lastIndexOf("/") + 1);
for (int i = 0; i < wsdlPorts.getLength(); i++) {
Element portElem = (Element) wsdlPorts.item(i);
Node portNameAttrib = portElem.getAttributes().getNamedItem("name");
if (portNameAttrib == null) {
continue;
}
String portName = portNameAttrib.getNodeValue();
NodeList soapAddresses = portElem.getElementsByTagNameNS(Constants.URI_WSDL11_SOAP, "address");
if (soapAddresses == null || soapAddresses.getLength() == 0) {
soapAddresses = portElem.getElementsByTagNameNS(Constants.URI_WSDL12_SOAP, "address");
}
if (soapAddresses != null) {
for (int j = 0; j < soapAddresses.getLength(); j++) {
Element addressElem = (Element) soapAddresses.item(j);
Node addressLocationAttrib = addressElem.getAttributes().getNamedItem("location");
if ( addressLocationAttrib == null )
{
continue;
}
String addressLocation = addressLocationAttrib.getNodeValue();
String addressServiceName = addressLocation.substring(addressLocation.lastIndexOf("/") + 1);
String newServiceName = getNewServiceName(deployedServiceNames, addressServiceName, portName);
if (newServiceName != null) {
String newAddressLocation = baseEndpointURL + newServiceName;
addressLocationAttrib.setNodeValue(newAddressLocation);
log.debug("Setting soap:address location values in WSDL for port " +
portName +
" to: " +
newAddressLocation);
}
else
{
log.debug("For WSDL port: " + portName + ", unable to match port name or the last component of " +
"the SOAP address url with a " +
"service name deployed in server-config.wsdd. Leaving SOAP address: " +
addressLocation + " unmodified.");
}
}
}
}
}
}
private String getNewServiceName(Set deployedServiceNames, String currentServiceEndpointName, String portName) {
String endpointName = null;
if (deployedServiceNames.contains(currentServiceEndpointName)) {
endpointName = currentServiceEndpointName;
}
else if (deployedServiceNames.contains(portName)) {
endpointName = portName;
}
return endpointName;
}
private Set getDeployedServiceNames(MessageContext msgContext) throws ConfigurationException {
Set serviceNames = new HashSet();
Iterator deployedServicesIter = msgContext.getAxisEngine().getConfig().getDeployedServices();
while (deployedServicesIter.hasNext()) {
ServiceDesc serviceDesc = (ServiceDesc) deployedServicesIter.next();
serviceNames.add(serviceDesc.getName());
}
return serviceNames;
}
/**
* Returns the endpoint URL that should be used in the returned WSDL.
*
* @param msgContext the current Axis JAX-RPC message context
* @return the endpoint URL that should be used in the returned WSDL
* @throws AxisFault if we fail to obtain the {@link org.apache.axis.description.ServiceDesc} for this service
*/
protected String getEndpointURL(MessageContext msgContext)
throws AxisFault {
// First see if a location URL is explicitly set in the MC.
String locationUrl = msgContext.getStrProp(
MessageContext.WSDLGEN_SERV_LOC_URL);
if (locationUrl == null) {
// If nothing, try what's explicitly set in the ServiceDesc.
locationUrl =
msgContext.getService().getInitializedServiceDesc(
msgContext)
.getEndpointURL();
}
if (locationUrl == null) {
// If nothing, use the actual transport URL.
locationUrl = msgContext.getStrProp(MessageContext.TRANS_URL);
}
return locationUrl;
}
}
| 7,428 |
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/security/AuthenticatedUser.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.security;
/** A small (mostly marker) interface for wrapping provider-specific
* user classes.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public interface AuthenticatedUser
{
/** Return a string representation of the user's name.
*
* @return the user's name as a String.
*/
public String getName();
}
| 7,429 |
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/security/SecurityProvider.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.security;
import org.apache.axis.MessageContext;
/** The Axis security provider interface
*
* As Axis is designed for use in embedded environments, those
* environments will often contain their own security databases and
* potentially authentication managers. This interface allows Axis
* to obtain authentication information from an opaque source which
* will presumably be configured into the engine at startup time.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public interface SecurityProvider
{
/** Authenticate a user from a username/password pair.
*
* @param msgContext the MessageContext containing authentication info
* @return an AuthenticatedUser or null
*/
public AuthenticatedUser authenticate(MessageContext msgContext);
/** See if a user matches a principal name. The name might be a user
* or a group.
*
* @return true if the user matches the passed name
*/
public boolean userMatches(AuthenticatedUser user, String principal);
}
| 7,430 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security/servlet/ServletAuthenticatedUser.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.security.servlet;
import org.apache.axis.security.AuthenticatedUser;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
/**
* ServletAuthenticatedUser is a sligtly odd implementation of
* AuthenticatedUser. It serves to store an HttpServletRequest,
* so that request can be used by the ServletSecurityProvider to
* check roles.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class ServletAuthenticatedUser implements AuthenticatedUser {
private String name;
private HttpServletRequest req;
public ServletAuthenticatedUser(HttpServletRequest req)
{
this.req = req;
Principal principal = req.getUserPrincipal();
this.name = (principal == null) ? null : principal.getName();
}
/** Return a string representation of the user's name.
*
* @return the user's name as a String.
*/
public String getName() {
return name;
}
public HttpServletRequest getRequest()
{
return req;
}
}
| 7,431 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security/servlet/ServletSecurityProvider.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.security.servlet;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;
import org.apache.axis.transport.http.HTTPConstants;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
/**
* A ServletSecurityProvider, combined with the ServletAuthenticatedUser
* class, allows the standard servlet security mechanisms (isUserInRole(),
* etc.) to integrate with Axis' access control mechanism.
*
* By utilizing this class (which the AxisServlet can be configured to
* do automatically), authentication and role information will come from
* your servlet engine.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class ServletSecurityProvider implements SecurityProvider {
protected static Log log =
LogFactory.getLog(ServletSecurityProvider.class.getName());
static HashMap users = null;
/** Authenticate a user from a username/password pair.
*
* @return an AuthenticatedUser or null
*/
public AuthenticatedUser authenticate(MessageContext msgContext) {
HttpServletRequest req = (HttpServletRequest)msgContext.getProperty(
HTTPConstants.MC_HTTP_SERVLETREQUEST);
if (req == null)
return null;
log.debug(Messages.getMessage("got00", "HttpServletRequest"));
Principal principal = req.getUserPrincipal();
if (principal == null) {
log.debug(Messages.getMessage("noPrincipal00"));
return null;
}
log.debug(Messages.getMessage("gotPrincipal00", principal.getName()));
return new ServletAuthenticatedUser(req);
}
/** See if a user matches a principal name. The name might be a user
* or a group.
*
* @return true if the user matches the passed name
*/
public boolean userMatches(AuthenticatedUser user, String principal) {
if (user == null) return principal == null;
if (user instanceof ServletAuthenticatedUser) {
ServletAuthenticatedUser servletUser = (ServletAuthenticatedUser)user;
return servletUser.getRequest().isUserInRole(principal);
}
return false;
}
}
| 7,432 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security/simple/SimpleSecurityProvider.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.security.simple;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* SimpleSecurityProvider
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class SimpleSecurityProvider implements SecurityProvider {
protected static Log log =
LogFactory.getLog(SimpleSecurityProvider.class.getName());
HashMap users = null;
HashMap perms = null;
boolean initialized = false;
// load the users list
private synchronized void initialize(MessageContext msgContext)
{
if (initialized) return;
String configPath = msgContext.getStrProp(Constants.MC_CONFIGPATH);
if (configPath == null) {
configPath = "";
} else {
configPath += File.separator;
}
File userFile = new File(configPath + "users.lst");
if (userFile.exists()) {
users = new HashMap();
try {
FileReader fr = new FileReader( userFile );
LineNumberReader lnr = new LineNumberReader( fr );
String line = null ;
// parse lines into user and passwd tokens and add result to hash table
while ( (line = lnr.readLine()) != null ) {
StringTokenizer st = new StringTokenizer( line );
if ( st.hasMoreTokens() ) {
String userID = st.nextToken();
String passwd = (st.hasMoreTokens()) ? st.nextToken() : "";
if (log.isDebugEnabled()) {
log.debug( Messages.getMessage("fromFile00",
userID, passwd) );
}
users.put(userID, passwd);
}
}
lnr.close();
} catch( Exception e ) {
log.error( Messages.getMessage("exception00"), e );
return;
}
}
initialized = true;
}
/** Authenticate a user from a username/password pair.
*
* @return an AuthenticatedUser or null
*/
public AuthenticatedUser authenticate(MessageContext msgContext) {
if (!initialized) {
initialize(msgContext);
}
String username = msgContext.getUsername();
String password = msgContext.getPassword();
if (users != null) {
if (log.isDebugEnabled()) {
log.debug( Messages.getMessage("user00", username) );
}
// in order to authenticate, the user must exist
if ( username == null ||
username.equals("") ||
!users.containsKey(username) )
return null;
String valid = (String) users.get(username);
if (log.isDebugEnabled()) {
log.debug( Messages.getMessage("password00", password) );
}
// if a password is defined, then it must match
if ( valid.length()>0 && !valid.equals(password) )
return null;
if (log.isDebugEnabled()) {
log.debug( Messages.getMessage("auth00", username) );
}
return new SimpleAuthenticatedUser(username);
}
return null;
}
/** See if a user matches a principal name. The name might be a user
* or a group.
*
* @return true if the user matches the passed name
*/
public boolean userMatches(AuthenticatedUser user, String principal) {
if (user == null) return principal == null;
return user.getName().compareToIgnoreCase(principal) == 0;
}
}
| 7,433 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/security/simple/SimpleAuthenticatedUser.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.security.simple;
import org.apache.axis.security.AuthenticatedUser;
/**
* SimpleAuthenticatedUser is a trivial implementation of the
* AuthenticatedUser interface, for use with a default Axis installation
* and the SimpleSecurityProvider.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class SimpleAuthenticatedUser implements AuthenticatedUser {
private String name;
public SimpleAuthenticatedUser(String name)
{
this.name = name;
}
/** Return a string representation of the user's name.
*
* @return the user's name as a String.
*/
public String getName() {
return name;
}
}
| 7,434 |
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/strategies/InvocationStrategy.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.strategies;
import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.HandlerIterationStrategy;
import org.apache.axis.MessageContext;
/**
* A Strategy which calls invoke() on the specified Handler, passing
* it the specified MessageContext.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class InvocationStrategy implements HandlerIterationStrategy {
public void visit(Handler handler, MessageContext msgContext)
throws AxisFault {
handler.invoke(msgContext);
}
}
| 7,435 |
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/strategies/WSDLGenStrategy.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.strategies;
import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.HandlerIterationStrategy;
import org.apache.axis.MessageContext;
/**
* A Strategy which calls generateWSDL() on the specified Handler, passing
* it the specified MessageContext.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class WSDLGenStrategy implements HandlerIterationStrategy {
public void visit(Handler handler, MessageContext msgContext)
throws AxisFault {
handler.generateWSDL(msgContext);
}
}
| 7,436 |
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/constants/Use.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.constants;
import org.apache.axis.Constants;
/**
* Use enum description
* @author Richard Scheuerle
*/
public class Use extends Enum {
/**
* See Style.java for a description of the combination
* of style and use.
*/
private static final Type type = new Type();
public static final String ENCODED_STR = "encoded";
public static final String LITERAL_STR = "literal";
public static final Use ENCODED = type.getUse(ENCODED_STR);
public static final Use LITERAL = type.getUse(LITERAL_STR);
public static final Use DEFAULT = ENCODED;
static { type.setDefault(DEFAULT); }
private String encoding;
public static Use getDefault() { return (Use)type.getDefault(); }
public final String getEncoding() { return encoding; }
public static final Use getUse(int style) {
return type.getUse(style);
}
public static final Use getUse(String style) {
return type.getUse(style);
}
public static final Use getUse(String style, Use dephault) {
return type.getUse(style, dephault);
}
public static final boolean isValid(String style) {
return type.isValid(style);
}
public static final int size() {
return type.size();
}
public static final String[] getUses() {
return type.getEnumNames();
}
private Object readResolve() throws java.io.ObjectStreamException {
return type.getUse(value);
}
public static class Type extends Enum.Type {
private Type() {
super("style", new Enum[] {
new Use(0, ENCODED_STR,
Constants.URI_DEFAULT_SOAP_ENC),
new Use(1, LITERAL_STR,
Constants.URI_LITERAL_ENC),
});
}
public final Use getUse(int style) {
return (Use)this.getEnum(style);
}
public final Use getUse(String style) {
return (Use)this.getEnum(style);
}
public final Use getUse(String style, Use dephault) {
return (Use)this.getEnum(style, dephault);
}
}
private Use(int value, String name, String encoding) {
super(type, value, name);
this.encoding = encoding;
}
protected Use() {
super(type, DEFAULT.getValue(), DEFAULT.getName());
this.encoding = DEFAULT.getEncoding();
}
}
| 7,437 |
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/constants/Style.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.constants;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import javax.xml.namespace.QName;
/**
* Description of the different styles
* <br>
* <b>style=rpc, use=encoded</b><br>
* First element of the SOAP body is the
* operation. The operation contains
* elements describing the parameters, which
* are serialized as encoded (possibly multi-ref)
* <pre>
* <soap:body>
* <operation>
* <arg1>...</arg1>
* <arg2>...</arg2>
* </operation>
* </pre>
* <br>
* <b>style=RPC, use=literal</b><br>
* First element of the SOAP body is the
* operation. The operation contains elements
* describing the parameters, which are serialized
* as encoded (no multi-ref)\
* <pre>
* <soap:body>
* <operation>
* <arg1>...</arg1>
* <arg2>...</arg2>
* </operation>
* </pre>
* <br>
* <b>style=document, use=literal</b><br>
* Elements of the SOAP body are the names of the parameters
* (there is no wrapper operation...no multi-ref)
* <pre>
* <soap:body>
* <arg1>...</arg1>
* <arg2>...</arg2>
* </pre>
* <br>
* <b>style=wrapped</b><br>
* Special case of DOCLIT where there is only one parameter
* and it has the same qname as the operation. In
* such cases, there is no actual type with the name...the
* elements are treated as parameters to the operation
* <pre>
* <soap:body>
* <one-arg-same-name-as-operation>
* <elemofarg1>...</elemofarg1>
* <elemofarg2>...</elemofarg2>
* </pre>
* <br>
* <b>style=document, use=encoded</b><br>
* There is not an enclosing operation name element, but
* the parmeterss are encoded using SOAP encoding
* This mode is not (well?) supported by Axis.
*
* @author Richard Sitze
*/
public class Style extends Enum {
private static final Type type = new Type();
public static final String RPC_STR = "rpc";
public static final String DOCUMENT_STR = "document";
public static final String WRAPPED_STR = "wrapped";
public static final String MESSAGE_STR = "message";
public static final Style RPC = type.getStyle(RPC_STR);
public static final Style DOCUMENT = type.getStyle(DOCUMENT_STR);
public static final Style WRAPPED = type.getStyle(WRAPPED_STR);
public static final Style MESSAGE = type.getStyle(MESSAGE_STR);
public static final Style DEFAULT = RPC;
static { type.setDefault(DEFAULT); }
private QName provider;
public static Style getDefault() { return (Style)type.getDefault(); }
public final QName getProvider() { return provider; }
public static final Style getStyle(int style) {
return type.getStyle(style);
}
public static final Style getStyle(String style) {
return type.getStyle(style);
}
public static final Style getStyle(String style, Style dephault) {
return type.getStyle(style, dephault);
}
public static final boolean isValid(String style) {
return type.isValid(style);
}
public static final int size() {
return type.size();
}
public static final String[] getStyles() {
return type.getEnumNames();
}
private Object readResolve() throws java.io.ObjectStreamException {
return type.getStyle(value);
}
public static class Type extends Enum.Type {
private Type() {
super("style", new Enum[] {
new Style(0, RPC_STR,
WSDDConstants.QNAME_JAVARPC_PROVIDER),
new Style(1, DOCUMENT_STR,
WSDDConstants.QNAME_JAVARPC_PROVIDER),
new Style(2, WRAPPED_STR,
WSDDConstants.QNAME_JAVARPC_PROVIDER),
new Style(3, MESSAGE_STR,
WSDDConstants.QNAME_JAVAMSG_PROVIDER),
});
}
public final Style getStyle(int style) {
return (Style)this.getEnum(style);
}
public final Style getStyle(String style) {
return (Style)this.getEnum(style);
}
public final Style getStyle(String style, Style dephault) {
return (Style)this.getEnum(style, dephault);
}
}
private Style(int value, String name, QName provider) {
super(type, value, name);
this.provider = provider;
}
protected Style() {
super(type, DEFAULT.getValue(), DEFAULT.getName());
this.provider = DEFAULT.getProvider();
}
}
| 7,438 |
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/constants/Enum.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.constants;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import java.util.Hashtable;
/**
* General support for 'enumerated' data types.
* Name searches are case insensitive.
*
* @author Richard Sitze (rsitze@apache.org)
*/
public abstract class Enum implements java.io.Serializable {
private static final Hashtable types = new Hashtable(13);
protected static Log log =
LogFactory.getLog(Enum.class.getName());
private final Type type;
public final int value;
public final String name;
protected Enum(Type type, int value, String name) {
this.type = type;
this.value = value;
this.name = name.intern();
}
public final int getValue() { return value; }
public final String getName() { return name; }
public final Type getType() { return type; }
public String toString() {
return name;
}
public final boolean equals(Object obj) {
return (obj != null && obj instanceof Enum)
? _equals((Enum)obj)
: false;
}
public int hashCode() {
return value;
}
public final boolean equals(Enum obj) {
return (obj != null) ? _equals(obj) : false;
}
/**
* The 'equals' logic assumes that there is a one-to-one
* relationship between value & name. If this isn't true,
* then expect to be confused when using this class with
* Collections.
*/
private final boolean _equals(Enum obj) {
return (//obj.name == name && // names are internalized
obj.type == type &&
obj.value == value);
}
public abstract static class Type implements java.io.Serializable {
private final String name;
private final Enum[] enums;
private Enum dephault = null;
protected Type(String name, Enum[] enums) {
this.name = name.intern();
this.enums = enums;
synchronized (types) {
types.put(name, this);
}
}
public void setDefault(Enum dephault) {
this.dephault = dephault;
}
public Enum getDefault() {
return dephault;
}
public final String getName() {
return name;
}
public final boolean isValid(String enumName) {
for (int enumElt = 0; enumElt < enums.length; enumElt++) {
if (enums[enumElt].getName().equalsIgnoreCase(enumName))
return true;
}
return false;
}
public final int size() {
return enums.length;
}
/**
* Returns array of names for enumerated values
*/
public final String[] getEnumNames() {
String[] nms = new String[ size() ];
for (int idx = 0; idx < enums.length; idx++)
nms[idx] = enums[idx].getName();
return nms;
}
/**
* Returns name of enumerated value
*/
public final Enum getEnum(int enumElt) {
return (enumElt >= 0 && enumElt < enums.length) ? enums[enumElt] : null;
}
/**
* Returns enumerated value of name
*/
public final Enum getEnum(String enumName) {
Enum e = getEnum(enumName, null);
if (e == null) {
log.error(Messages.getMessage("badEnum02", name, enumName));
}
return e;
}
/**
* Returns enumerated value of name
*
* For large sets of enumerated values, a HashMap could
* be used to retrieve. It's not clear if there is any
* benefit for small (3 to 4) sets, as used now.
*/
public final Enum getEnum(String enumName, Enum dephault) {
if (enumName != null && enumName.length() > 0) {
for (int enumElt = 0; enumElt < enums.length; enumElt++) {
Enum e = enums[enumElt];
if (e.getName().equalsIgnoreCase(enumName))
return e;
}
}
return dephault;
}
private Object readResolve() throws java.io.ObjectStreamException {
Object type = types.get(name);
if (type == null) {
type = this;
types.put(name, type);
}
return type;
}
}
}
| 7,439 |
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/constants/Scope.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.constants;
/**
* @author rsitze
*/
public class Scope extends Enum {
private static final Type type = new Type();
public static final String REQUEST_STR = "Request";
public static final String APPLICATION_STR = "Application";
public static final String SESSION_STR = "Session";
public static final String FACTORY_STR = "Factory";
public static final Scope REQUEST = type.getScope(REQUEST_STR);
public static final Scope APPLICATION = type.getScope(APPLICATION_STR);
public static final Scope SESSION = type.getScope(SESSION_STR);
public static final Scope FACTORY = type.getScope(FACTORY_STR);
public static final Scope DEFAULT = REQUEST;
static { type.setDefault(DEFAULT); }
// public int getValue();
// public String getName();
// public Type getType();
public static Scope getDefault() { return (Scope)type.getDefault(); }
public static final Scope getScope(int scope) {
return type.getScope(scope);
}
public static final Scope getScope(String scope) {
return type.getScope(scope);
}
public static final Scope getScope(String scope, Scope dephault) {
return type.getScope(scope, dephault);
}
public static final boolean isValid(String scope) {
return type.isValid(scope);
}
public static final int size() {
return type.size();
}
public static final String[] getScopes() {
return type.getEnumNames();
}
private Object readResolve() throws java.io.ObjectStreamException {
return type.getScope(value);
}
public static class Type extends Enum.Type {
private Type() {
super("scope", new Enum[] {
new Scope(0, REQUEST_STR),
new Scope(1, APPLICATION_STR),
new Scope(2, SESSION_STR),
new Scope(3, FACTORY_STR)
});
}
public final Scope getScope(int scope) {
return (Scope)this.getEnum(scope);
}
public final Scope getScope(String scope) {
return (Scope)this.getEnum(scope);
}
public final Scope getScope(String scope, Scope dephault) {
return (Scope)this.getEnum(scope, dephault);
}
}
private Scope(int value, String name) {
super(type, value, name);
}
protected Scope() {
super(type, DEFAULT.getValue(), DEFAULT.getName());
}
}
| 7,440 |
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/providers/BasicProvider.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.providers;
import java.util.Hashtable;
import javax.xml.namespace.QName;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.AxisEngine;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.description.JavaServiceDesc;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.utils.Messages;
import org.apache.axis.wsdl.fromJava.Emitter;
import org.apache.commons.logging.Log;
import org.w3c.dom.Document;
/**
* This class has one way of keeping track of the
* operations declared for a particular service
* provider. I'm not exactly married to this though.
*/
public abstract class BasicProvider extends BasicHandler {
public static final String OPTION_WSDL_PORTTYPE = "wsdlPortType";
public static final String OPTION_WSDL_SERVICEELEMENT = "wsdlServiceElement";
public static final String OPTION_WSDL_SERVICEPORT = "wsdlServicePort";
public static final String OPTION_WSDL_TARGETNAMESPACE = "wsdlTargetNamespace";
public static final String OPTION_WSDL_INPUTSCHEMA = "wsdlInputSchema";
public static final String OPTION_WSDL_SOAPACTION_MODE = "wsdlSoapActionMode";
public static final String OPTION_EXTRACLASSES = "extraClasses";
protected static Log log =
LogFactory.getLog(BasicProvider.class.getName());
// 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);
/**
* This method returns a ServiceDesc that contains the correct
* implimentation class.
*/
public abstract void initServiceDesc(SOAPService service,
MessageContext msgContext)
throws AxisFault;
public void addOperation(String name, QName qname) {
Hashtable operations = (Hashtable)getOption("Operations");
if (operations == null) {
operations = new Hashtable();
setOption("Operations", operations);
}
operations.put(qname, name);
}
public String getOperationName(QName qname) {
Hashtable operations = (Hashtable)getOption("Operations");
if (operations == null) return null;
return (String)operations.get(qname);
}
public QName[] getOperationQNames() {
Hashtable operations = (Hashtable)getOption("Operations");
if (operations == null) return null;
Object[] keys = operations.keySet().toArray();
QName[] qnames = new QName[keys.length];
System.arraycopy(keys,0,qnames,0,keys.length);
return qnames;
}
public String[] getOperationNames() {
Hashtable operations = (Hashtable)getOption("Operations");
if (operations == null) return null;
Object[] values = operations.values().toArray();
String[] names = new String[values.length];
System.arraycopy(values,0,names,0,values.length);
return names;
}
/**
* Generate the WSDL for this service.
*
* Put in the "WSDL" property of the message context
* as a org.w3c.dom.Document
*/
public void generateWSDL(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: BasicProvider::generateWSDL (" + this +")");
/* Find the service we're invoking so we can grab it's options */
/***************************************************************/
SOAPService service = msgContext.getService();
ServiceDesc serviceDesc = service.getInitializedServiceDesc(msgContext);
// Calculate the appropriate namespaces for the WSDL we're going
// to put out.
//
// If we've been explicitly told which namespaces to use, respect
// that. If not:
//
// The "interface namespace" should be either:
// 1) The namespace of the ServiceDesc
// 2) The transport URL (if there's no ServiceDesc ns)
try {
// Location URL is whatever is explicitly set in the MC
String locationUrl = msgContext.getStrProp(MessageContext.WSDLGEN_SERV_LOC_URL);
if (locationUrl == null) {
// If nothing, try what's explicitly set in the ServiceDesc
locationUrl = serviceDesc.getEndpointURL();
}
if (locationUrl == null) {
// If nothing, use the actual transport URL
locationUrl = msgContext.getStrProp(MessageContext.TRANS_URL);
}
// Interface namespace is whatever is explicitly set
String interfaceNamespace = msgContext.getStrProp(MessageContext.WSDLGEN_INTFNAMESPACE);
if (interfaceNamespace == null) {
// If nothing, use the default namespace of the ServiceDesc
interfaceNamespace = serviceDesc.getDefaultNamespace();
}
if (interfaceNamespace == null) {
// If nothing still, use the location URL determined above
interfaceNamespace = locationUrl;
}
//Do we want to do this?
//
// if (locationUrl == null) {
// locationUrl = url;
// } else {
// try {
// URL urlURL = new URL(url);
// URL locationURL = new URL(locationUrl);
// URL urlTemp = new URL(urlURL.getProtocol(),
// locationURL.getHost(),
// locationURL.getPort(),
// urlURL.getFile());
// interfaceNamespace += urlURL.getFile();
// locationUrl = urlTemp.toString();
// } catch (Exception e) {
// locationUrl = url;
// interfaceNamespace = url;
// }
// }
Emitter emitter = new Emitter();
// This seems like a good idea, but in fact isn't because the
// emitter will figure out a reasonable name (<classname>Service)
// for the WSDL service element name. We provide the 'alias'
// setting to explicitly set this name. See bug 13262 for more info.
//emitter.setServiceElementName(serviceDesc.getName());
// service alias may be provided if exact naming is required,
// otherwise Axis will name it according to the implementing class name
String alias = (String) service.getOption("alias");
if (alias != null)
emitter.setServiceElementName(alias);
// Set style/use
emitter.setStyle(serviceDesc.getStyle());
emitter.setUse(serviceDesc.getUse());
if (serviceDesc instanceof JavaServiceDesc) {
emitter.setClsSmart(((JavaServiceDesc)serviceDesc).getImplClass(),
locationUrl);
}
// If a wsdl target namespace was provided, use the targetNamespace.
// Otherwise use the interfaceNamespace constructed above.
String targetNamespace = (String) service.getOption(OPTION_WSDL_TARGETNAMESPACE);
if (targetNamespace == null || targetNamespace.length() == 0) {
targetNamespace = interfaceNamespace;
}
emitter.setIntfNamespace(targetNamespace);
emitter.setLocationUrl(locationUrl);
emitter.setServiceDesc(serviceDesc);
emitter.setTypeMappingRegistry(msgContext.getTypeMappingRegistry());
String wsdlPortType = (String) service.getOption(OPTION_WSDL_PORTTYPE);
String wsdlServiceElement = (String) service.getOption(OPTION_WSDL_SERVICEELEMENT);
String wsdlServicePort = (String) service.getOption(OPTION_WSDL_SERVICEPORT);
String wsdlInputSchema = (String) service.getOption(OPTION_WSDL_INPUTSCHEMA);
String wsdlSoapActinMode = (String) service.getOption(OPTION_WSDL_SOAPACTION_MODE);
String extraClasses = (String) service.getOption(OPTION_EXTRACLASSES);
if (wsdlPortType != null && wsdlPortType.length() > 0) {
emitter.setPortTypeName(wsdlPortType);
}
if (wsdlServiceElement != null && wsdlServiceElement.length() > 0) {
emitter.setServiceElementName(wsdlServiceElement);
}
if (wsdlServicePort != null && wsdlServicePort.length() > 0) {
emitter.setServicePortName(wsdlServicePort);
}
if (wsdlInputSchema != null && wsdlInputSchema.length() > 0) {
emitter.setInputSchema(wsdlInputSchema);
}
if (wsdlSoapActinMode != null && wsdlSoapActinMode.length() > 0) {
emitter.setSoapAction(wsdlSoapActinMode);
}
if (extraClasses != null && extraClasses.length() > 0) {
emitter.setExtraClasses(extraClasses, msgContext.getClassLoader());
}
if (msgContext.isPropertyTrue(AxisEngine.PROP_EMIT_ALL_TYPES)) {
emitter.setEmitAllTypes(true);
}
Document doc = emitter.emit(Emitter.MODE_ALL);
msgContext.setProperty("WSDL", doc);
} catch (NoClassDefFoundError e) {
entLog.info(Messages.getMessage("toAxisFault00"), e);
throw new AxisFault(e.toString(), e);
} catch (Exception e) {
entLog.info(Messages.getMessage("toAxisFault00"), e);
throw AxisFault.makeFault(e);
}
if (log.isDebugEnabled())
log.debug("Exit: BasicProvider::generateWSDL (" + this +")");
}
}
| 7,441 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/RMIProvider.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.providers.java;
import org.apache.axis.Constants;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
/**
* A basic RMI Provider
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class RMIProvider extends RPCProvider {
protected static Log log =
LogFactory.getLog(RMIProvider.class.getName());
// 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);
public static final String OPTION_NAMING_LOOKUP = "NamingLookup";
public static final String OPTION_INTERFACE_CLASSNAME = "InterfaceClassName";
/**
* Return a object which implements the service.
*
* @param msgContext the message context
* @param clsName The JNDI name of the EJB home class
* @return an object that implements the service
*/
protected Object makeNewServiceObject(MessageContext msgContext,
String clsName)
throws Exception {
// Read deployment descriptor options
String namingLookup = getStrOption(OPTION_NAMING_LOOKUP, msgContext.getService());
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
Object targetObject = Naming.lookup(namingLookup);
return targetObject;
}
/**
* Return the option in the configuration that contains the service class
* name.
*/
protected String getServiceClassNameOptionName() {
return OPTION_INTERFACE_CLASSNAME;
}
/**
* Get a String option by looking first in the service options,
* and then at the Handler's options. This allows defaults to be
* specified at the provider level, and then overriden for particular
* services.
*
* @param optionName the option to retrieve
* @return String the value of the option or null if not found in
* either scope
*/
protected String getStrOption(String optionName, Handler service) {
String value = null;
if (service != null)
value = (String) service.getOption(optionName);
if (value == null)
value = (String) getOption(optionName);
return value;
}
}
| 7,442 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/CORBAProvider.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.providers.java;
import org.apache.axis.Constants;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.ClassUtils;
import org.apache.commons.logging.Log;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* A basic CORBA Provider
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class CORBAProvider extends RPCProvider
{
protected static Log log =
LogFactory.getLog(CORBAProvider.class.getName());
private static final String DEFAULT_ORB_INITIAL_HOST = "localhost";
private static final String DEFAULT_ORB_INITIAL_PORT = "900";
// 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);
public static final String OPTION_ORB_INITIAL_HOST = "ORBInitialHost";
public static final String OPTION_ORB_INITIAL_PORT = "ORBInitialPort";
public static final String OPTION_NAME_ID = "NameID";
public static final String OPTION_NAME_KIND = "NameKind";
public static final String OPTION_INTERFACE_CLASSNAME = "InterfaceClassName";
public static final String OPTION_HELPER_CLASSNAME = "HelperClassName";
/**
* Return a object which implements the service.
*
* @param msgContext the message context
* @param clsName The JNDI name of the EJB home class
* @return an object that implements the service
*/
protected Object makeNewServiceObject(MessageContext msgContext,
String clsName)
throws Exception
{
// Read deployment descriptor options
String orbInitialHost = getStrOption(OPTION_ORB_INITIAL_HOST,msgContext.getService());
if (orbInitialHost == null)
orbInitialHost = DEFAULT_ORB_INITIAL_HOST;
String orbInitialPort = getStrOption(OPTION_ORB_INITIAL_PORT,msgContext.getService());
if (orbInitialPort == null)
orbInitialPort = DEFAULT_ORB_INITIAL_PORT;
String nameId = getStrOption(OPTION_NAME_ID,msgContext.getService());
String nameKind = getStrOption(OPTION_NAME_KIND,msgContext.getService());
String helperClassName = getStrOption(OPTION_HELPER_CLASSNAME,msgContext.getService());
// Initialize ORB
Properties orbProps = new Properties();
orbProps.put("org.omg.CORBA.ORBInitialHost", orbInitialHost);
orbProps.put("org.omg.CORBA.ORBInitialPort", orbInitialPort);
ORB orb = ORB.init(new String[0], orbProps);
// Find the object
NamingContext root = NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
NameComponent nc = new NameComponent(nameId, nameKind);
NameComponent[] ncs = {nc};
org.omg.CORBA.Object corbaObject = root.resolve(ncs);
Class helperClass = ClassUtils.forName(helperClassName);
// Narrow the object reference
Method narrowMethod = helperClass.getMethod("narrow", CORBA_OBJECT_CLASS);
Object targetObject = narrowMethod.invoke(null, new Object[] {corbaObject});
return targetObject;
}
private static final Class[] CORBA_OBJECT_CLASS = new Class[] {org.omg.CORBA.Object.class};
/**
* Return the option in the configuration that contains the service class
* name.
*/
protected String getServiceClassNameOptionName()
{
return OPTION_INTERFACE_CLASSNAME;
}
/**
* Get a String option by looking first in the service options,
* and then at the Handler's options. This allows defaults to be
* specified at the provider level, and then overriden for particular
* services.
*
* @param optionName the option to retrieve
* @return String the value of the option or null if not found in
* either scope
*/
protected String getStrOption(String optionName, Handler service)
{
String value = null;
if (service != null)
value = (String)service.getOption(optionName);
if (value == null)
value = (String)getOption(optionName);
return value;
}
}
| 7,443 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/JavaProvider.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.providers.java;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Handler;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.JavaServiceDesc;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.constants.Scope;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.providers.BasicProvider;
import org.apache.axis.session.Session;
import org.apache.axis.utils.ClassUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.utils.cache.ClassCache;
import org.apache.axis.utils.cache.JavaClass;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import javax.xml.rpc.holders.IntHolder;
import javax.xml.rpc.server.ServiceLifecycle;
import javax.xml.soap.SOAPMessage;
import javax.wsdl.OperationType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Base class for Java dispatching. Fetches various fields out of envelope,
* looks up service object (possibly using session state), and delegates
* envelope body processing to subclass via abstract processMessage method.
*
* @author Doug Davis (dug@us.ibm.com)
* @author Carl Woolf (cwoolf@macromedia.com)
*/
public abstract class JavaProvider extends BasicProvider
{
protected static Log log =
LogFactory.getLog(JavaProvider.class.getName());
// 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);
public static final String OPTION_CLASSNAME = "className";
public static final String OPTION_ALLOWEDMETHODS = "allowedMethods";
public static final String OPTION_SCOPE = "scope";
/**
* Get the service object whose method actually provides the service.
* May look up in session table.
*/
public Object getServiceObject (MessageContext msgContext,
Handler service,
String clsName,
IntHolder scopeHolder)
throws Exception
{
String serviceName = msgContext.getService().getName();
// scope can be "Request", "Session", "Application", "Factory"
Scope scope = Scope.getScope((String)service.getOption(OPTION_SCOPE), Scope.DEFAULT);
scopeHolder.value = scope.getValue();
if (scope == Scope.REQUEST) {
// make a one-off
return getNewServiceObject(msgContext, clsName);
} else if (scope == Scope.SESSION) {
// What do we do if serviceName is null at this point???
if (serviceName == null)
serviceName = msgContext.getService().toString();
// look in incoming session
Session session = msgContext.getSession();
if (session != null) {
return getSessionServiceObject(session, serviceName,
msgContext, clsName);
} else {
// was no incoming session, sigh, treat as request scope
scopeHolder.value = Scope.DEFAULT.getValue();
return getNewServiceObject(msgContext, clsName);
}
} else if (scope == Scope.APPLICATION) {
// MUST be AxisEngine here!
return getApplicationScopedObject(msgContext, serviceName, clsName, scopeHolder);
} else if (scope == Scope.FACTORY) {
String objectID = msgContext.getStrProp("objectID");
if (objectID == null) {
return getApplicationScopedObject(msgContext, serviceName, clsName, scopeHolder);
}
SOAPService svc = (SOAPService)service;
Object ret = svc.serviceObjects.get(objectID);
if (ret == null) {
throw new AxisFault("NoSuchObject", null, null, null);
}
return ret;
}
// NOTREACHED
return null;
}
private Object getApplicationScopedObject(MessageContext msgContext, String serviceName, String clsName, IntHolder scopeHolder) throws Exception {
AxisEngine engine = msgContext.getAxisEngine();
Session appSession = engine.getApplicationSession();
if (appSession != null) {
return getSessionServiceObject(appSession, serviceName,
msgContext, clsName);
} else {
// was no application session - log an error and
// treat as request scope
log.error(Messages.getMessage("noAppSession"));
scopeHolder.value = Scope.DEFAULT.getValue();
return getNewServiceObject(msgContext, clsName);
}
}
/**
* Simple utility class for dealing with synchronization issues.
*/
class LockObject implements Serializable {
private boolean completed = false;
synchronized void waitUntilComplete() throws InterruptedException {
while (!completed) {
wait();
}
}
synchronized void complete() {
completed = true;
notifyAll();
}
}
/**
* Get a service object from a session. Handles threading / locking
* issues when multiple threads might be accessing the same session
* object, and ensures only one thread gets to create the service
* object if there isn't one already.
*/
private Object getSessionServiceObject(Session session,
String serviceName,
MessageContext msgContext,
String clsName) throws Exception {
Object obj = null;
boolean makeNewObject = false;
// This is a little tricky.
synchronized (session.getLockObject()) {
// store service objects in session, indexed by class name
obj = session.get(serviceName);
// If nothing there, put in a placeholder object so
// other threads wait for us to create the real
// service object.
if (obj == null) {
obj = new LockObject();
makeNewObject = true;
session.set(serviceName, obj);
}
}
// OK, we DEFINITELY have something in obj at this point. Either
// it's the service object or it's a LockObject (ours or someone
// else's).
if (LockObject.class == obj.getClass()) {
LockObject lock = (LockObject)obj;
// If we were the lucky thread who got to install the
// placeholder, create a new service object and install it
// instead, then notify anyone waiting on the LockObject.
if (makeNewObject) {
try {
obj = getNewServiceObject(msgContext, clsName);
session.set(serviceName, obj);
} catch(final Exception e) {
session.remove(serviceName);
throw e;
} finally {
lock.complete();
}
} else {
// It's someone else's LockObject, so wait around until
// it's completed.
lock.waitUntilComplete();
// Now we are guaranteed there is a service object in the
// session, so this next part doesn't need syncing
obj = session.get(serviceName);
}
}
return obj;
}
/**
* Return a new service object which, if it implements the ServiceLifecycle
* interface, has been init()ed.
*
* @param msgContext the MessageContext
* @param clsName the name of the class to instantiate
* @return an initialized service object
*/
private Object getNewServiceObject(MessageContext msgContext,
String clsName) throws Exception
{
Object serviceObject = makeNewServiceObject(msgContext, clsName);
if (serviceObject != null &&
serviceObject instanceof ServiceLifecycle) {
((ServiceLifecycle)serviceObject).init(
msgContext.getProperty(Constants.MC_SERVLET_ENDPOINT_CONTEXT));
}
return serviceObject;
}
/**
* Process the current message. Side-effect resEnv to create return value.
*
* @param msgContext self-explanatory
* @param reqEnv the request envelope
* @param resEnv the response envelope
* @param obj the service object itself
*/
public abstract void processMessage (MessageContext msgContext,
SOAPEnvelope reqEnv,
SOAPEnvelope resEnv,
Object obj)
throws Exception;
/**
* Invoke the message by obtaining various common fields, looking up
* the service object (via getServiceObject), and actually processing
* the message (via processMessage).
*/
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: JavaProvider::invoke (" + this + ")");
/* Find the service we're invoking so we can grab it's options */
/***************************************************************/
String serviceName = msgContext.getTargetService();
Handler service = msgContext.getService();
/* Now get the service (RPC) specific info */
/********************************************/
String clsName = getServiceClassName(service);
if ((clsName == null) || clsName.equals("")) {
throw new AxisFault("Server.NoClassForService",
Messages.getMessage("noOption00", getServiceClassNameOptionName(), serviceName),
null, null);
}
IntHolder scope = new IntHolder();
Object serviceObject = null;
try {
serviceObject = getServiceObject(msgContext, service, clsName, scope);
SOAPEnvelope resEnv = null;
// If there IS a response message AND this is a one-way operation,
// we delete the response message here. Note that this might
// cause confusing results in some cases - i.e. nothing fails,
// but your response headers don't go anywhere either. It might
// be nice if in the future there was a way to detect an error
// when trying to install a response message in a MessageContext
// associated with a one-way operation....
OperationDesc operation = msgContext.getOperation();
if (operation != null &&
OperationType.ONE_WAY.equals(operation.getMep())) {
msgContext.setResponseMessage(null);
} else {
Message resMsg = msgContext.getResponseMessage();
// If we didn't have a response message, make sure we set one up
// with the appropriate versions of SOAP and Schema
if (resMsg == null) {
resEnv = new SOAPEnvelope(msgContext.getSOAPConstants(),
msgContext.getSchemaVersion());
resMsg = new Message(resEnv);
String encoding = XMLUtils.getEncoding(msgContext);
resMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encoding);
msgContext.setResponseMessage( resMsg );
} else {
resEnv = resMsg.getSOAPEnvelope();
}
}
Message reqMsg = msgContext.getRequestMessage();
SOAPEnvelope reqEnv = reqMsg.getSOAPEnvelope();
processMessage(msgContext, reqEnv, resEnv, serviceObject);
} catch( SAXException exp ) {
entLog.debug( Messages.getMessage("toAxisFault00"), exp);
Exception real = exp.getException();
if (real == null) {
real = exp;
}
throw AxisFault.makeFault(real);
} catch( Exception exp ) {
entLog.debug( Messages.getMessage("toAxisFault00"), exp);
AxisFault fault = AxisFault.makeFault(exp);
//make a note if this was a runtime fault, for better logging
if (exp instanceof RuntimeException) {
fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION,
"true");
}
throw fault;
} finally {
// If this is a request scoped service object which implements
// ServiceLifecycle, let it know that it's being destroyed now.
if (serviceObject != null &&
scope.value == Scope.REQUEST.getValue() &&
serviceObject instanceof ServiceLifecycle)
{
((ServiceLifecycle)serviceObject).destroy();
}
}
if (log.isDebugEnabled())
log.debug("Exit: JavaProvider::invoke (" + this + ")");
}
private String getAllowedMethods(Handler service)
{
String val = (String)service.getOption(OPTION_ALLOWEDMETHODS);
if (val == null || val.length() == 0) {
// Try the old option for backwards-compatibility
val = (String)service.getOption("methodName");
}
return val;
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
/////// Default methods for java classes. Override, eg, for
/////// ejbeans
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
/**
* Default java service object comes from simply instantiating the
* class wrapped in jc
*
*/
protected Object makeNewServiceObject(MessageContext msgContext,
String clsName)
throws Exception
{
ClassLoader cl = msgContext.getClassLoader();
ClassCache cache = msgContext.getAxisEngine().getClassCache();
JavaClass jc = cache.lookup(clsName, cl);
return jc.getJavaClass().newInstance();
}
/**
* Return the class name of the service
*/
protected String getServiceClassName(Handler service)
{
return (String) service.getOption( getServiceClassNameOptionName() );
}
/**
* Return the option in the configuration that contains the service class
* name
*/
protected String getServiceClassNameOptionName()
{
return OPTION_CLASSNAME;
}
/**
* Returns the Class info about the service class.
*/
protected Class getServiceClass(String clsName,
SOAPService service,
MessageContext msgContext)
throws AxisFault {
ClassLoader cl = null;
Class serviceClass = null;
AxisEngine engine = service.getEngine();
// If we have a message context, use that to get classloader
// otherwise get the current threads classloader
if (msgContext != null) {
cl = msgContext.getClassLoader();
} else {
cl = Thread.currentThread().getContextClassLoader();
}
// If we have an engine, use its class cache
if (engine != null) {
ClassCache cache = engine.getClassCache();
try {
JavaClass jc = cache.lookup(clsName, cl);
serviceClass = jc.getJavaClass();
} catch (ClassNotFoundException e) {
log.error(Messages.getMessage("exception00"), e);
throw new AxisFault(Messages.getMessage("noClassForService00", clsName), e);
}
} else {
// if no engine, we don't have a cache, use Class.forName instead.
try {
serviceClass = ClassUtils.forName(clsName, true, cl);
} catch (ClassNotFoundException e) {
log.error(Messages.getMessage("exception00"), e);
throw new AxisFault(Messages.getMessage("noClassForService00", clsName), e);
}
}
return serviceClass;
}
/**
* Fill in a service description with the correct impl class
* and typemapping set. This uses methods that can be overridden by
* other providers (like the EJBProvider) to get the class from the
* right place.
*/
public void initServiceDesc(SOAPService service, MessageContext msgContext)
throws AxisFault
{
// Set up the Implementation class for the service
String clsName = getServiceClassName(service);
if (clsName == null) {
throw new AxisFault(Messages.getMessage("noServiceClass"));
}
Class cls = getServiceClass(clsName, service, msgContext);
JavaServiceDesc serviceDescription = (JavaServiceDesc)service.getServiceDescription();
// And the allowed methods, if necessary
if (serviceDescription.getAllowedMethods() == null && service != null) {
String allowedMethods = getAllowedMethods(service);
if (allowedMethods != null && !"*".equals(allowedMethods)) {
ArrayList methodList = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(allowedMethods, " ,");
while (tokenizer.hasMoreTokens()) {
methodList.add(tokenizer.nextToken());
}
serviceDescription.setAllowedMethods(methodList);
}
}
serviceDescription.loadServiceDescByIntrospection(cls);
}
}
| 7,444 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/MsgProvider.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.providers.java;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.i18n.Messages;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.MessageElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.lang.reflect.Method;
import java.util.Vector;
/**
* Deal with message-style Java services. For now, these are services
* with exactly ONE OperationDesc, pointing to a method which looks like
* one of the following:
*
* public Element [] method(Vector v);
* (NOTE : This is silly, we should change it to either be Vector/Vector
* or Element[]/Element[])
*
* public Document method(Document doc);
*
* public void method(MessageContext mc);
*
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@apache.org)
*/
public class MsgProvider extends JavaProvider {
/**
* Process the message. Figure out the method "style" (one of the three
* allowed signatures, which has already been determined and cached in
* the OperationDesc) and do the actual invocation. Note that we don't
* catch exceptions here, preferring to bubble them right up through to
* someone who'll catch it above us.
*
* @param msgContext the active MessageContext
* @param reqEnv the request SOAPEnvelope
* @param resEnv the response SOAPEnvelope (we should fill this in)
* @param obj the service target object
* @throws Exception
*/
public void processMessage (MessageContext msgContext,
SOAPEnvelope reqEnv,
SOAPEnvelope resEnv,
Object obj)
throws Exception
{
OperationDesc operation = msgContext.getOperation();
SOAPService service = msgContext.getService();
ServiceDesc serviceDesc = service.getServiceDescription();
QName opQName = null;
if (operation == null) {
Vector bodyElements = reqEnv.getBodyElements();
if(bodyElements.size() > 0) {
MessageElement element = (MessageElement) bodyElements.get(0);
if (element != null) {
opQName = new QName(element.getNamespaceURI(),
element.getLocalName());
operation = serviceDesc.getOperationByElementQName(opQName);
}
}
}
if (operation == null) {
throw new AxisFault(Messages.getMessage("noOperationForQName",
opQName == null ? "null" : opQName.toString()));
}
Method method = operation.getMethod();
int methodType = operation.getMessageOperationStyle();
if (methodType != OperationDesc.MSG_METHOD_SOAPENVELOPE) {
// dig out just the body, and pass it on
Vector bodies = reqEnv.getBodyElements();
Object argObjects[] = new Object [1];
switch (methodType) {
// SOAPBodyElement [] / SOAPBodyElement []
case OperationDesc.MSG_METHOD_BODYARRAY:
SOAPBodyElement [] bodyElements =
new SOAPBodyElement[bodies.size()];
bodies.toArray(bodyElements);
argObjects[0] = bodyElements;
SOAPBodyElement [] bodyResult =
(SOAPBodyElement [])method.invoke(obj, argObjects);
if (bodyResult != null) {
for (int i = 0; i < bodyResult.length; i++) {
SOAPBodyElement bodyElement = bodyResult[i];
resEnv.addBodyElement(bodyElement);
}
}
return;
// Element [] / Element []
case OperationDesc.MSG_METHOD_ELEMENTARRAY:
Element [] elements = new Element [bodies.size()];
for (int i = 0; i < elements.length; i++) {
SOAPBodyElement body = (SOAPBodyElement)bodies.get(i);
elements[i] = body.getAsDOM();
}
argObjects[0] = elements;
Element[] elemResult =
(Element[]) method.invoke( obj, argObjects );
if (elemResult != null) {
for ( int i = 0 ; i < elemResult.length ; i++ ) {
if(elemResult[i] != null)
resEnv.addBodyElement(
new SOAPBodyElement(elemResult[i]));
}
}
return;
// Element [] / Element []
case OperationDesc.MSG_METHOD_DOCUMENT:
Document doc = ((SOAPBodyElement)bodies.get(0)).getAsDocument();
argObjects[0] = doc;
Document resultDoc =
(Document) method.invoke( obj, argObjects );
if (resultDoc != null) {
resEnv.addBodyElement(new SOAPBodyElement(
resultDoc.getDocumentElement()));
}
return;
}
} else {
Object argObjects[] = new Object [2];
// SOAPEnvelope / SOAPEnvelope
argObjects[0] = reqEnv;
argObjects[1] = resEnv;
method.invoke(obj, argObjects);
return;
}
// SHOULD NEVER GET HERE...
throw new AxisFault(Messages.getMessage("badMsgMethodStyle"));
}
};
| 7,445 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/EJBProvider.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.providers.java;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.utils.ClassUtils;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
/**
* A basic EJB Provider
*
* @author Carl Woolf (cwoolf@macromedia.com)
* @author Tom Jordahl (tomj@macromedia.com)
* @author C?dric Chabanois (cchabanois@ifrance.com)
*/
public class EJBProvider extends RPCProvider
{
protected static Log log =
LogFactory.getLog(EJBProvider.class.getName());
// 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);
public static final String OPTION_BEANNAME = "beanJndiName";
public static final String OPTION_HOMEINTERFACENAME = "homeInterfaceName";
public static final String OPTION_REMOTEINTERFACENAME = "remoteInterfaceName";
public static final String OPTION_LOCALHOMEINTERFACENAME = "localHomeInterfaceName";
public static final String OPTION_LOCALINTERFACENAME = "localInterfaceName";
public static final String jndiContextClass = "jndiContextClass";
public static final String jndiURL = "jndiURL";
public static final String jndiUsername = "jndiUser";
public static final String jndiPassword = "jndiPassword";
protected static final Class[] empty_class_array = new Class[0];
protected static final Object[] empty_object_array = new Object[0];
private static InitialContext cached_context = null;
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
/////// Default methods from JavaProvider ancestor, overridden
/////// for ejbeans
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
/**
* Return a object which implements the service.
*
* @param msgContext the message context
* @param clsName The JNDI name of the EJB home class
* @return an object that implements the service
*/
protected Object makeNewServiceObject(MessageContext msgContext,
String clsName)
throws Exception
{
String remoteHomeName = getStrOption(OPTION_HOMEINTERFACENAME,
msgContext.getService());
String localHomeName = getStrOption(OPTION_LOCALHOMEINTERFACENAME,
msgContext.getService());
String homeName = (remoteHomeName != null ? remoteHomeName:localHomeName);
if (homeName == null) {
// cannot find both remote home and local home
throw new AxisFault(
Messages.getMessage("noOption00",
OPTION_HOMEINTERFACENAME,
msgContext.getTargetService()));
}
// Load the Home class name given in the config file
Class homeClass = ClassUtils.forName(homeName, true, msgContext.getClassLoader());
// we create either the ejb using either the RemoteHome or LocalHome object
if (remoteHomeName != null)
return createRemoteEJB(msgContext, clsName, homeClass);
else
return createLocalEJB(msgContext, clsName, homeClass);
}
/**
* Create an EJB using a remote home object
*
* @param msgContext the message context
* @param beanJndiName The JNDI name of the EJB remote home class
* @param homeClass the class of the home interface
* @return an EJB
*/
private Object createRemoteEJB(MessageContext msgContext,
String beanJndiName,
Class homeClass)
throws Exception
{
// Get the EJB Home object from JNDI
Object ejbHome = getEJBHome(msgContext.getService(),
msgContext, beanJndiName);
Object ehome = javax.rmi.PortableRemoteObject.narrow(ejbHome, homeClass);
// Invoke the create method of the ejbHome class without actually
// touching any EJB classes (i.e. no cast to EJBHome)
Method createMethod = homeClass.getMethod("create", empty_class_array);
Object result = createMethod.invoke(ehome, empty_object_array);
return result;
}
/**
* Create an EJB using a local home object
*
* @param msgContext the message context
* @param beanJndiName The JNDI name of the EJB local home class
* @param homeClass the class of the home interface
* @return an EJB
*/
private Object createLocalEJB(MessageContext msgContext,
String beanJndiName,
Class homeClass)
throws Exception
{
// Get the EJB Home object from JNDI
Object ejbHome = getEJBHome(msgContext.getService(),
msgContext, beanJndiName);
// the home object is a local home object
Object ehome;
if (homeClass.isInstance(ejbHome))
ehome = ejbHome;
else
throw new ClassCastException(
Messages.getMessage("badEjbHomeType"));
// Invoke the create method of the ejbHome class without actually
// touching any EJB classes (i.e. no cast to EJBLocalHome)
Method createMethod = homeClass.getMethod("create", empty_class_array);
Object result = createMethod.invoke(ehome, empty_object_array);
return result;
}
/**
* Tells if the ejb that will be used to handle this service is a remote
* one
*/
private boolean isRemoteEjb(SOAPService service)
{
return getStrOption(OPTION_HOMEINTERFACENAME,service) != null;
}
/**
* Tells if the ejb that will be used to handle this service is a local
* one
*/
private boolean isLocalEjb(SOAPService service)
{
return (!isRemoteEjb(service)) &&
(getStrOption(OPTION_LOCALHOMEINTERFACENAME,service) != null);
}
/**
* Return the option in the configuration that contains the service class
* name. In the EJB case, it is the JNDI name of the bean.
*/
protected String getServiceClassNameOptionName()
{
return OPTION_BEANNAME;
}
/**
* Get a String option by looking first in the service options,
* and then at the Handler's options. This allows defaults to be
* specified at the provider level, and then overriden for particular
* services.
*
* @param optionName the option to retrieve
* @return String the value of the option or null if not found in
* either scope
*/
protected String getStrOption(String optionName, Handler service)
{
String value = null;
if (service != null)
value = (String)service.getOption(optionName);
if (value == null)
value = (String)getOption(optionName);
return value;
}
/**
* Get the remote interface of an ejb from its home class.
* This function can only be used for remote ejbs
*
* @param beanJndiName the jndi name of the ejb
* @param service the soap service
* @param msgContext the message context (can be null)
*/
private Class getRemoteInterfaceClassFromHome(String beanJndiName,
SOAPService service,
MessageContext msgContext)
throws Exception
{
// Get the EJB Home object from JNDI
Object ejbHome = getEJBHome(service, msgContext, beanJndiName);
String homeName = getStrOption(OPTION_HOMEINTERFACENAME,
service);
if (homeName == null)
throw new AxisFault(
Messages.getMessage("noOption00",
OPTION_HOMEINTERFACENAME,
service.getName()));
// Load the Home class name given in the config file
ClassLoader cl = (msgContext != null) ?
msgContext.getClassLoader() :
Thread.currentThread().getContextClassLoader();
Class homeClass = ClassUtils.forName(homeName, true, cl);
// Make sure the object we got back from JNDI is the same type
// as the what is specified in the config file
Object ehome = javax.rmi.PortableRemoteObject.narrow(ejbHome, homeClass);
// This code requires the use of ejb.jar, so we do the stuff below
// EJBHome ejbHome = (EJBHome) ehome;
// EJBMetaData meta = ejbHome.getEJBMetaData();
// Class interfaceClass = meta.getRemoteInterfaceClass();
// Invoke the getEJBMetaData method of the ejbHome class without
// actually touching any EJB classes (i.e. no cast to EJBHome)
Method getEJBMetaData =
homeClass.getMethod("getEJBMetaData", empty_class_array);
Object metaData = getEJBMetaData.invoke(ehome, empty_object_array);
Method getRemoteInterfaceClass =
metaData.getClass().getMethod("getRemoteInterfaceClass",
empty_class_array);
return (Class) getRemoteInterfaceClass.invoke(metaData,
empty_object_array);
}
/**
* Get the class description for the EJB Remote or Local Interface,
* which is what we are interested in exposing to the world (i.e. in WSDL).
*
* @param msgContext the message context (can be null)
* @param beanJndiName the JNDI name of the EJB
* @return the class info of the EJB remote or local interface
*/
protected Class getServiceClass(String beanJndiName,
SOAPService service,
MessageContext msgContext)
throws AxisFault
{
Class interfaceClass = null;
try {
// First try to get the interface class from the configuation
// Note that we don't verify that remote remoteInterfaceName is used for
// remote ejb and localInterfaceName for local ejb. Should we ?
String remoteInterfaceName =
getStrOption(OPTION_REMOTEINTERFACENAME, service);
String localInterfaceName =
getStrOption(OPTION_LOCALINTERFACENAME, service);
String interfaceName = (remoteInterfaceName != null ? remoteInterfaceName : localInterfaceName);
if(interfaceName != null){
ClassLoader cl = (msgContext != null) ?
msgContext.getClassLoader() :
Thread.currentThread().getContextClassLoader();
interfaceClass = ClassUtils.forName(interfaceName,
true,
cl);
}
else
{
// cannot get the interface name from the configuration, we get
// it from the EJB Home (if remote)
if (isRemoteEjb(service)) {
interfaceClass = getRemoteInterfaceClassFromHome(beanJndiName,
service,
msgContext);
}
else
if (isLocalEjb(service)) {
// we cannot get the local interface from the local ejb home
// localInterfaceName is mandatory for local ejbs
throw new AxisFault(
Messages.getMessage("noOption00",
OPTION_LOCALINTERFACENAME,
service.getName()));
}
else
{
// neither a local ejb or a remote one ...
throw new AxisFault(Messages.getMessage("noOption00",
OPTION_HOMEINTERFACENAME,
service.getName()));
}
}
} catch (Exception e) {
throw AxisFault.makeFault(e);
}
// got it, return it
return interfaceClass;
}
/**
* Common routine to do the JNDI lookup on the Home interface object
* username and password for jndi lookup are got from the configuration or from
* the messageContext if not found in the configuration
*/
private Object getEJBHome(SOAPService serviceHandler,
MessageContext msgContext,
String beanJndiName)
throws AxisFault
{
Object ejbHome = null;
// Set up an InitialContext and use it get the beanJndiName from JNDI
try {
Properties properties = null;
// collect all the properties we need to access JNDI:
// username, password, factoryclass, contextUrl
// username
String username = getStrOption(jndiUsername, serviceHandler);
if ((username == null) && (msgContext != null))
username = msgContext.getUsername();
if (username != null) {
if (properties == null)
properties = new Properties();
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
}
// password
String password = getStrOption(jndiPassword, serviceHandler);
if ((password == null) && (msgContext != null))
password = msgContext.getPassword();
if (password != null) {
if (properties == null)
properties = new Properties();
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
}
// factory class
String factoryClass = getStrOption(jndiContextClass, serviceHandler);
if (factoryClass != null) {
if (properties == null)
properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryClass);
}
// contextUrl
String contextUrl = getStrOption(jndiURL, serviceHandler);
if (contextUrl != null) {
if (properties == null)
properties = new Properties();
properties.setProperty(Context.PROVIDER_URL, contextUrl);
}
// get context using these properties
InitialContext context = getContext(properties);
// if we didn't get a context, fail
if (context == null)
throw new AxisFault( Messages.getMessage("cannotCreateInitialContext00"));
ejbHome = getEJBHome(context, beanJndiName);
if (ejbHome == null)
throw new AxisFault( Messages.getMessage("cannotFindJNDIHome00",beanJndiName));
}
// Should probably catch javax.naming.NameNotFoundException here
catch (Exception exception) {
entLog.info(Messages.getMessage("toAxisFault00"), exception);
throw AxisFault.makeFault(exception);
}
return ejbHome;
}
protected InitialContext getCachedContext()
throws javax.naming.NamingException
{
if (cached_context == null)
cached_context = new InitialContext();
return cached_context;
}
protected InitialContext getContext(Properties properties)
throws AxisFault, javax.naming.NamingException
{
// if we got any stuff from the configuration file
// create a new context using these properties
// otherwise, we get a default context and cache it for next time
return ((properties == null)
? getCachedContext()
: new InitialContext(properties));
}
protected Object getEJBHome(InitialContext context, String beanJndiName)
throws AxisFault, javax.naming.NamingException
{
// Do the JNDI lookup
return context.lookup(beanJndiName);
}
/**
* Override the default implementation such that we can include
* special handling for {@link java.rmi.ServerException}.
* <p>
* Converts {@link java.rmi.ServerException} exceptions to
* {@link InvocationTargetException} exceptions with the same cause.
* This allows the axis framework to create a SOAP fault.
*
* @see org.apache.axis.providers.java.RPCProvider#invokeMethod(org.apache.axis.MessageContext, java.lang.reflect.Method, java.lang.Object, java.lang.Object[])
*/
protected Object invokeMethod(MessageContext msgContext, Method method,
Object obj, Object[] argValues)
throws Exception {
try {
return super.invokeMethod(msgContext, method, obj, argValues);
} catch (InvocationTargetException ite) {
Throwable cause = getCause(ite);
if (cause instanceof java.rmi.ServerException) {
throw new InvocationTargetException(getCause(cause));
}
throw ite;
}
}
/**
* Get the cause of an exception, using reflection so that
* it still works under JDK 1.3
*
* @param original the original exception
* @return the cause of the exception, or the given exception if the cause cannot be discovered.
*/
private Throwable getCause(Throwable original) {
try {
Method method = original.getClass().getMethod("getCause", null);
Throwable cause = (Throwable) method.invoke(original, null);
if (cause != null) {
return cause;
}
} catch (NoSuchMethodException nsme) {
// ignore, this occurs under JDK 1.3
} catch (Throwable t) {
}
return original;
}
}
| 7,446 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/providers/java/RPCProvider.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.providers.java;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.constants.Style;
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.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import javax.xml.rpc.holders.Holder;
import javax.wsdl.OperationType;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
/**
* Implement message processing by walking over RPCElements of the
* envelope body, invoking the appropriate methods on the service object.
*
* @author Doug Davis (dug@us.ibm.com)
*/
public class RPCProvider extends JavaProvider {
protected static Log log =
LogFactory.getLog(RPCProvider.class.getName());
/**
* Process the current message.
* Result in resEnv.
*
* @param msgContext self-explanatory
* @param reqEnv the request envelope
* @param resEnv the response envelope
* @param obj the service object itself
*/
public void processMessage(MessageContext msgContext,
SOAPEnvelope reqEnv,
SOAPEnvelope resEnv,
Object obj)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Enter: RPCProvider.processMessage()");
}
SOAPService service = msgContext.getService();
ServiceDesc serviceDesc = service.getServiceDescription();
RPCElement body = getBody(reqEnv, msgContext);
Vector args = null;
try {
args = body.getParams();
} catch (SAXException e) {
if(e.getException() != null)
throw e.getException();
throw e;
}
int numArgs = args.size();
OperationDesc operation = getOperationDesc(msgContext, body);
// Create the array we'll use to hold the actual parameter
// values. We know how big to make it from the metadata.
Object[] argValues = new Object[operation.getNumParams()];
// A place to keep track of the out params (INOUTs and OUTs)
ArrayList outs = new ArrayList();
// Put the values contained in the RPCParams into an array
// suitable for passing to java.lang.reflect.Method.invoke()
// Make sure we respect parameter ordering if we know about it
// from metadata, and handle whatever conversions are necessary
// (values -> Holders, etc)
for (int i = 0; i < numArgs; i++) {
RPCParam rpcParam = (RPCParam) args.get(i);
Object value = rpcParam.getObjectValue();
// first check the type on the paramter
ParameterDesc paramDesc = rpcParam.getParamDesc();
// if we found some type info try to make sure the value type is
// correct. For instance, if we deserialized a xsd:dateTime in
// to a Calendar and the service takes a Date, we need to convert
if (paramDesc != null && paramDesc.getJavaType() != null) {
// Get the type in the signature (java type or its holder)
Class sigType = paramDesc.getJavaType();
// Convert the value into the expected type in the signature
value = JavaUtils.convert(value, sigType);
rpcParam.setObjectValue(value);
if (paramDesc.getMode() == ParameterDesc.INOUT) {
outs.add(rpcParam);
}
}
// Put the value (possibly converted) in the argument array
// make sure to use the parameter order if we have it
if (paramDesc == null || paramDesc.getOrder() == -1) {
argValues[i] = value;
} else {
argValues[paramDesc.getOrder()] = value;
}
if (log.isDebugEnabled()) {
log.debug(" " + Messages.getMessage("value00",
"" + argValues[i]));
}
}
// See if any subclasses want a crack at faulting on a bad operation
// FIXME : Does this make sense here???
String allowedMethods = (String) service.getOption("allowedMethods");
checkMethodName(msgContext, allowedMethods, operation.getName());
// Now create any out holders we need to pass in
int count = numArgs;
for (int i = 0; i < argValues.length; i++) {
// We are interested only in OUT/INOUT
ParameterDesc param = operation.getParameter(i);
if(param.getMode() == ParameterDesc.IN)
continue;
Class holderClass = param.getJavaType();
if (holderClass != null &&
Holder.class.isAssignableFrom(holderClass)) {
int index = count;
// Use the parameter order if specified or just stick them to the end.
if (param.getOrder() != -1) {
index = param.getOrder();
} else {
count++;
}
// If it's already filled, don't muck with it
if (argValues[index] != null) {
continue;
}
argValues[index] = holderClass.newInstance();
// Store an RPCParam in the outs collection so we
// have an easy and consistent way to write these
// back to the client below
RPCParam p = new RPCParam(param.getQName(),
argValues[index]);
p.setParamDesc(param);
outs.add(p);
} else {
throw new AxisFault(Messages.getMessage("badOutParameter00",
"" + param.getQName(),
operation.getName()));
}
}
// OK! Now we can invoke the method
Object objRes = null;
try {
objRes = invokeMethod(msgContext,
operation.getMethod(),
obj, argValues);
} catch (IllegalArgumentException e) {
String methodSig = operation.getMethod().toString();
String argClasses = "";
for (int i = 0; i < argValues.length; i++) {
if (argValues[i] == null) {
argClasses += "null";
} else {
argClasses += argValues[i].getClass().getName();
}
if (i + 1 < argValues.length) {
argClasses += ",";
}
}
log.info(Messages.getMessage("dispatchIAE00",
new String[]{methodSig, argClasses}),
e);
throw new AxisFault(Messages.getMessage("dispatchIAE00",
new String[]{methodSig, argClasses}),
e);
}
/** If this is a one-way operation, there is nothing more to do.
*/
if (OperationType.ONE_WAY.equals(operation.getMep()))
return;
RPCElement resBody = createResponseBody(body, msgContext, operation, serviceDesc, objRes, resEnv, outs);
resEnv.addBodyElement(resBody);
}
protected RPCElement getBody(SOAPEnvelope reqEnv, MessageContext msgContext) throws Exception {
SOAPService service = msgContext.getService();
ServiceDesc serviceDesc = service.getServiceDescription();
OperationDesc operation = msgContext.getOperation();
Vector bodies = reqEnv.getBodyElements();
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("bodyElems00", "" + bodies.size()));
if(bodies.size()>0){
log.debug(Messages.getMessage("bodyIs00", "" + bodies.get(0)));
}
}
RPCElement body = null; // Find the first "root" body element, which is the RPC call.
for (int bNum = 0; body == null && bNum < bodies.size(); bNum++) {
// If this is a regular old SOAPBodyElement, and it's a root,
// we're probably a non-wrapped doc/lit service. In this case,
// we deserialize the element, and create an RPCElement "wrapper"
// around it which points to the correct method.
// FIXME : There should be a cleaner way to do this...
if (!(bodies.get(bNum) instanceof RPCElement)) {
SOAPBodyElement bodyEl = (SOAPBodyElement) bodies.get(bNum);
// igors: better check if bodyEl.getID() != null
// to make sure this loop does not step on SOAP-ENC objects
// that follow the parameters! FIXME?
if (bodyEl.isRoot() && operation != null && bodyEl.getID() == null) {
ParameterDesc param = operation.getParameter(bNum);
// at least do not step on non-existent parameters!
if (param != null) {
Object val = bodyEl.getValueAsType(param.getTypeQName());
body = new RPCElement("",
operation.getName(),
new Object[]{val});
}
}
} else {
body = (RPCElement) bodies.get(bNum);
}
} // special case code for a document style operation with no
// arguments (which is a strange thing to have, but whatever)
if (body == null) {
// throw an error if this isn't a document style service
if (!(serviceDesc.getStyle().equals(Style.DOCUMENT))) {
throw new Exception(Messages.getMessage("noBody00"));
}
// look for a method in the service that has no arguments,
// use the first one we find.
ArrayList ops = serviceDesc.getOperations();
for (Iterator iterator = ops.iterator(); iterator.hasNext();) {
OperationDesc desc = (OperationDesc) iterator.next();
if (desc.getNumInParams() == 0) {
// found one with no parameters, use it
msgContext.setOperation(desc);
// create an empty element
body = new RPCElement(desc.getName());
// stop looking
break;
}
}
// If we still didn't find anything, report no body error.
if (body == null) {
throw new Exception(Messages.getMessage("noBody00"));
}
}
return body;
}
protected OperationDesc getOperationDesc(MessageContext msgContext, RPCElement body) throws SAXException, AxisFault {
SOAPService service = msgContext.getService();
ServiceDesc serviceDesc = service.getServiceDescription();
String methodName = body.getMethodName();
// FIXME (there should be a cleaner way to do this)
OperationDesc operation = msgContext.getOperation();
if (operation == null) {
QName qname = new QName(body.getNamespaceURI(),
body.getName());
operation = serviceDesc.getOperationByElementQName(qname);
if (operation == null) {
SOAPConstants soapConstants = msgContext == null ?
SOAPConstants.SOAP11_CONSTANTS :
msgContext.getSOAPConstants();
if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
AxisFault fault =
new AxisFault(Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noSuchOperation",
methodName),
null,
null);
fault.addFaultSubCode(Constants.FAULT_SUBCODE_PROC_NOT_PRESENT);
throw new SAXException(fault);
} else {
throw new AxisFault(Constants.FAULT_CLIENT, Messages.getMessage("noSuchOperation", methodName),
null, null);
}
} else {
msgContext.setOperation(operation);
}
}
return operation;
}
protected RPCElement createResponseBody(RPCElement body, MessageContext msgContext, OperationDesc operation, ServiceDesc serviceDesc, Object objRes, SOAPEnvelope resEnv, ArrayList outs) throws Exception
{
String methodName = body.getMethodName();
/* Now put the result in the result SOAPEnvelope */
RPCElement resBody = new RPCElement(methodName + "Response");
resBody.setPrefix(body.getPrefix());
resBody.setNamespaceURI(body.getNamespaceURI());
resBody.setEncodingStyle(msgContext.getEncodingStyle());
try {
// Return first
if (operation.getMethod().getReturnType() != Void.TYPE) {
QName returnQName = operation.getReturnQName();
if (returnQName == null) {
String nsp = body.getNamespaceURI();
if(nsp == null || nsp.length()==0) {
nsp = serviceDesc.getDefaultNamespace();
}
returnQName = new QName(msgContext.isEncoded() ? "" :
nsp,
methodName + "Return");
}
RPCParam param = new RPCParam(returnQName, objRes);
param.setParamDesc(operation.getReturnParamDesc());
if (!operation.isReturnHeader()) {
// For SOAP 1.2 rpc style, add a result
if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS &&
(serviceDesc.getStyle().equals(Style.RPC))) {
RPCParam resultParam = new RPCParam(Constants.QNAME_RPC_RESULT, returnQName);
resultParam.setXSITypeGeneration(Boolean.FALSE);
resBody.addParam(resultParam);
}
resBody.addParam(param);
} else {
resEnv.addHeader(new RPCHeaderParam(param));
}
}
// Then any other out params
if (!outs.isEmpty()) {
for (Iterator i = outs.iterator(); i.hasNext();) {
// We know this has a holder, so just unwrap the value
RPCParam param = (RPCParam) i.next();
Holder holder = (Holder) param.getObjectValue();
Object value = JavaUtils.getHolderValue(holder);
ParameterDesc paramDesc = param.getParamDesc();
param.setObjectValue(value);
if (paramDesc != null && paramDesc.isOutHeader()) {
resEnv.addHeader(new RPCHeaderParam(param));
} else {
resBody.addParam(param);
}
}
}
} catch (Exception e) {
throw e;
}
return resBody;
}
/**
* This method encapsulates the method invocation.
*
* @param msgContext MessageContext
* @param method the target method.
* @param obj the target object
* @param argValues the method arguments
*/
protected Object invokeMethod(MessageContext msgContext,
Method method, Object obj,
Object[] argValues)
throws Exception {
return (method.invoke(obj, argValues));
}
/**
* Throw an AxisFault if the requested method is not allowed.
*
* @param msgContext MessageContext
* @param allowedMethods list of allowed methods
* @param methodName name of target method
*/
protected void checkMethodName(MessageContext msgContext,
String allowedMethods,
String methodName)
throws Exception {
// Our version doesn't need to do anything, though inherited
// ones might.
}
}
| 7,447 |
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/encoding/AttributeSerializationContextImpl.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.encoding;
import org.xml.sax.Attributes;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.Writer;
/** Used to suppress element tag serialization when serializing simple
* types into attributes.
*
* @author Thomas Sandholm (sandholm@mcs.anl.gov)
*/
public class AttributeSerializationContextImpl extends SerializationContext
{
SerializationContext parent;
public AttributeSerializationContextImpl(Writer writer, SerializationContext parent)
{
super(writer);
this.parent = parent;
}
public void startElement(QName qName, Attributes attributes)
throws IOException
{
// suppressed
}
public void endElement()
throws IOException
{
// suppressed
}
public String qName2String(QName qname)
{
return parent.qName2String(qname);
}
}
| 7,448 |
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/encoding/TextSerializationContext.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.encoding;
import java.io.IOException;
import java.io.Writer;
import javax.xml.namespace.QName;
import org.apache.axis.MessageContext;
import org.apache.axis.utils.Messages;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
/**
* For internal use only. Used to get the first text node of an element.
*
* @author Jarek Gawor (gawor@apache.org)
*/
public class TextSerializationContext extends SerializationContext {
private boolean ignore = false;
private int depth = 0;
public TextSerializationContext(Writer writer)
{
super(writer);
startOfDocument = false; // prevent XML decl for text
}
public TextSerializationContext(Writer writer, MessageContext msgContext)
{
super(writer, msgContext);
startOfDocument = false; // prevent XML decl for text
}
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType,
Boolean sendNull,
Boolean sendType)
throws IOException
{
throw new IOException(Messages.getMessage("notImplemented00",
"serialize"));
}
public void writeDOMElement(Element el)
throws IOException
{
throw new IOException(Messages.getMessage("notImplemented00",
"writeDOMElement"));
}
public void startElement(QName qName, Attributes attributes)
throws IOException
{
depth++;
if (depth == 2) {
this.ignore = true;
}
}
public void endElement()
throws IOException
{
depth--;
ignore = true;
}
public void writeChars(char [] p1, int p2, int p3)
throws IOException
{
if (!this.ignore) {
super.writeChars(p1, p2, p3);
}
}
public void writeString(String string)
throws IOException
{
if (!this.ignore) {
super.writeString(string);
}
}
}
| 7,449 |
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/encoding/Deserializer.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.encoding;
import org.apache.axis.message.SOAPHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import java.util.Vector;
/**
* This interface describes the AXIS Deserializer.
* A compliant implementiation must extend either
* the AXIS SoapHandler (org.apache.axis.message.SOAPHandler)
* or the AXIS DeserializerImpl (org.apache.axis.encoding.DeserializerImpl)
*
* The DeserializerImpl provides a lot of the default behavior including the
* support for id/href. So you may want to try extending it as opposed to
* extending SoapHandler.
*
* An Axis compliant Deserializer must provide one or more
* of the following methods:
*
* public <constructor>(Class javaType, QName xmlType)
* public <constructo>()
*
* This will allow for construction of generic factories that introspect the class
* to determine how to construct a deserializer.
* The xmlType, javaType arguments are filled in with the values known by the factory.
*/
public interface Deserializer extends javax.xml.rpc.encoding.Deserializer, Callback {
/**
* Get the deserialized value.
* @return Object representing deserialized value or null
*/
public Object getValue();
/**
* Set the deserialized value.
* @param value Object representing deserialized value
*/
public void setValue(Object value);
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method gets the specific component via the hint.
* The default implementation returns null.
* @return Object representing deserialized value or null
*/
public Object getValue(Object hint);
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method sets the specific component via the hint.
* The default implementation does nothing.
* @param value Object representing deserialized value or null
*/
public void setChildValue(Object value, Object hint) throws SAXException;
/**
* In some circumstances an element may not have
* a type attribute, but a default type qname is known from
* information in the container. For example,
* an element of an array may not have a type= attribute,
* so the default qname is the component type of the array.
* This method is used to communicate the default type information
* to the deserializer.
*/
public void setDefaultType(QName qName);
public QName getDefaultType();
/**
* For deserializers of non-primitives, the value may not be
* known until later (due to multi-referencing). In such
* cases the deserializer registers Target object(s). When
* the value is known, the set(value) will be invoked for
* each Target registered with the Deserializer. The Target
* object abstracts the function of setting a target with a
* value. See the Target interface for more info.
* @param target Target
*/
public void registerValueTarget(Target target);
/**
* Get the Value Targets of the Deserializer.
* @return Vector of Target objects or null
*/
public Vector getValueTargets();
/**
* Remove the Value Targets of the Deserializer.
*/
public void removeValueTargets() ;
/**
* Move someone else's targets to our own (see DeserializationContext)
*
* The DeserializationContext only allows one Deserializer to
* wait for a unknown multi-ref'ed value. So to ensure
* that all of the targets are updated, this method is invoked
* to copy the Target objects to the waiting Deserializer.
* @param other is the Deserializer to copy targets from.
*/
public void moveValueTargets(Deserializer other);
/**
* Some deserializers (ArrayDeserializer) require
* all of the component values to be known before the
* value is complete.
* (For the ArrayDeserializer this is important because
* the elements are stored in an ArrayList, and all values
* must be known before the ArrayList is converted into the
* expected array.
*
* This routine is used to indicate when the components are ready.
* The default (true) is useful for most Deserializers.
*/
public boolean componentsReady();
/**
* The valueComplete() method is invoked when the
* end tag of the element is read. This results
* in the setting of all registered Targets (see
* registerValueTarget).
* Note that the valueComplete() only processes
* the Targets if componentReady() returns true.
* So if you override componentReady(), then your
* specific Deserializer will need to call valueComplete()
* when your components are ready (See ArrayDeserializer)
*/
public void valueComplete() throws SAXException;
/**
* The following are the SAX specific methods.
* DeserializationImpl provides default behaviour, which
* in most cases is appropriate.
*/
/**
* This method is invoked when an element start tag is encountered.
* DeserializerImpl provides default behavior, which involves the following:
* - directly handling the deserialization of a nill value
* - handling the registration of the id value.
* - handling the registration of a fixup if this element is an href.
* - calling onStartElement to do the actual deserialization if not nill or href cases.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param qName is the prefixed qName of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*
* Normally a specific Deserializer (FooDeserializer) should extend DeserializerImpl.
* Here is the flow that will occur in such cases:
* 1) DeserializerImpl.startElement(...) will be called and do the id/href/nill stuff.
* 2) If real deserialization needs to take place DeserializerImpl.onStartElement will be
* invoked, which will attempt to install the specific Deserializer (FooDeserializer)
* 3) The FooDeserializer.startElement(...) will be called to do the Foo specific stuff.
* This results in a call to FooDeserializer.onStartElement(...) if startElement was
* not overridden.
* 4) The onChildElement(...) method is called for each child element. Nothing occurs
* if not overridden. The FooDeserializer.onStartChild(...) method should return
* the deserializer for the child element.
* 5) When the end tag is reached, the endElement(..) method is invoked. The default
* behavior is to handle hrefs/ids, call onEndElement and then call the Deserializer
* valueComplete method.
*
* So the methods that you potentially want to override are:
* onStartElement, onStartChild, componentsReady, set(object, hint)
*
* You probably should not override startElement or endElement.
* If you need specific behaviour at the end of the element consider overriding
* onEndElement.
*
* See the pre-existing Deserializers for more information.
*/
public void startElement(String namespace, String localName,
String qName, Attributes attributes,
DeserializationContext context)
throws SAXException;
/**
* This method is invoked after startElement when the element requires
* deserialization (i.e. the element is not an href and the value is not nil.)
* DeserializerImpl provides default behavior, which simply
* involves obtaining a correct Deserializer and plugging its handler.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the prefix of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*/
public void onStartElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException;
/**
* onStartChild is called on each child element.
* The default behavior supplied by DeserializationImpl is to do nothing.
* A specific deserializer may perform other tasks. For example a
* BeanDeserializer will construct a deserializer for the indicated
* property and return it.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param prefix is the prefix used on the name of the child element
* @param attributes are the attributes of the child element
* @param context is the deserialization context.
* @return is a Deserializer to use to deserialize a child (must be
* a derived class of SOAPHandler) or null if no deserialization should
* be performed.
*/
public SOAPHandler onStartChild(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException;
/**
* endElement is called when the end element tag is reached.
* It handles href/id information for multi-ref processing
* and invokes the valueComplete() method of the deserializer
* which sets the targets with the deserialized value.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public void endElement(String namespace, String localName,
DeserializationContext context)
throws SAXException;
/**
* onEndElement is called by endElement. It is not called
* if the element has an href.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public void onEndElement(String namespace, String localName,
DeserializationContext context)
throws SAXException;
}
| 7,450 |
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/encoding/CallbackTarget.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.encoding;
import org.xml.sax.SAXException;
// Target is a Callback. The set method invokes one of the setValue methods
// of the callback using the hing. The CallbackTarget
// is used in situations when the Deserializer is expecting multiple values and cannot
// be considered complete until all values are received.
// (example is an ArrayDeserializer).
public class CallbackTarget implements Target {
public Callback target;
public Object hint;
public CallbackTarget(Callback target, Object hint)
{
this.target = target;
this.hint = hint;
}
public void set(Object value) throws SAXException {
target.setValue(value, hint);
}
}
| 7,451 |
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/encoding/TypeMappingRegistry.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.encoding;
import java.io.Serializable;
/**
* This interface describes the AXIS TypeMappingRegistry.
*/
public interface TypeMappingRegistry
extends javax.xml.rpc.encoding.TypeMappingRegistry, Serializable {
/**
* delegate
*
* Changes the contained type mappings to delegate to
* their corresponding types in the secondary TMR.
*/
public void delegate(TypeMappingRegistry secondaryTMR);
/**
* Obtain a type mapping for the given encoding style. If no specific
* mapping exists for this encoding style, we will create and register
* one before returning it.
*
* @param encodingStyle
* @return a registered TypeMapping for the given encoding style
*/
public TypeMapping getOrMakeTypeMapping(String encodingStyle);
}
| 7,452 |
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/encoding/MixedContentType.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.encoding;
import org.apache.axis.message.MessageElement;
/**
* Interface to indicate that a bean has mixed content
*
*/
public interface MixedContentType {
public MessageElement[] get_any();
public void set_any(MessageElement[] any);
}
| 7,453 |
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/encoding/Base64.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.encoding ;
import org.apache.axis.utils.Messages;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
/**
*
* @author TAMURA Kent <kent@trl.ibm.co.jp>
*/
public class Base64 {
private static final char[] S_BASE64CHAR = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
private static final char S_BASE64PAD = '=';
private static final byte[] S_DECODETABLE = new byte[128];
static {
for (int i = 0; i < S_DECODETABLE.length; i ++)
S_DECODETABLE[i] = Byte.MAX_VALUE; // 127
for (int i = 0; i < S_BASE64CHAR.length; i ++) // 0 to 63
S_DECODETABLE[S_BASE64CHAR[i]] = (byte)i;
}
private static int decode0(char[] ibuf, byte[] obuf, int wp) {
int outlen = 3;
if (ibuf[3] == S_BASE64PAD) outlen = 2;
if (ibuf[2] == S_BASE64PAD) outlen = 1;
int b0 = S_DECODETABLE[ibuf[0]];
int b1 = S_DECODETABLE[ibuf[1]];
int b2 = S_DECODETABLE[ibuf[2]];
int b3 = S_DECODETABLE[ibuf[3]];
switch (outlen) {
case 1:
obuf[wp] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
return 1;
case 2:
obuf[wp++] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
obuf[wp] = (byte)(b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
return 2;
case 3:
obuf[wp++] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
obuf[wp++] = (byte)(b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
obuf[wp] = (byte)(b2 << 6 & 0xc0 | b3 & 0x3f);
return 3;
default:
throw new RuntimeException(Messages.getMessage("internalError00"));
}
}
/**
*
*/
public static byte[] decode(char[] data, int off, int len) {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[len/4*3+3];
int obufcount = 0;
for (int i = off; i < off+len; i ++) {
char ch = data[i];
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
obufcount += decode0(ibuf, obuf, obufcount);
}
}
}
if (obufcount == obuf.length)
return obuf;
byte[] ret = new byte[obufcount];
System.arraycopy(obuf, 0, ret, 0, obufcount);
return ret;
}
/**
*
*/
public static byte[] decode(String data) {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[data.length()/4*3+3];
int obufcount = 0;
for (int i = 0; i < data.length(); i ++) {
char ch = data.charAt(i);
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
obufcount += decode0(ibuf, obuf, obufcount);
}
}
}
if (obufcount == obuf.length)
return obuf;
byte[] ret = new byte[obufcount];
System.arraycopy(obuf, 0, ret, 0, obufcount);
return ret;
}
/**
*
*/
public static void decode(char[] data, int off, int len, OutputStream ostream) throws IOException {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[3];
for (int i = off; i < off+len; i ++) {
char ch = data[i];
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
int obufcount = decode0(ibuf, obuf, 0);
ostream.write(obuf, 0, obufcount);
}
}
}
}
/**
*
*/
public static void decode(String data, OutputStream ostream) throws IOException {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[3];
for (int i = 0; i < data.length(); i ++) {
char ch = data.charAt(i);
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
int obufcount = decode0(ibuf, obuf, 0);
ostream.write(obuf, 0, obufcount);
}
}
}
}
/**
* Returns base64 representation of specified byte array.
*/
public static String encode(byte[] data) {
return encode(data, 0, data.length);
}
/**
* Returns base64 representation of specified byte array.
*/
public static String encode(byte[] data, int off, int len) {
if (len <= 0) return "";
char[] out = new char[len/3*4+4];
int rindex = off;
int windex = 0;
int rest = len-off;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[windex++] = S_BASE64CHAR[i>>18];
out[windex++] = S_BASE64CHAR[(i>>12)&0x3f];
out[windex++] = S_BASE64CHAR[(i>>6)&0x3f];
out[windex++] = S_BASE64CHAR[i&0x3f];
rindex += 3;
rest -= 3;
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[windex++] = S_BASE64CHAR[i>>2];
out[windex++] = S_BASE64CHAR[(i<<4)&0x3f];
out[windex++] = S_BASE64PAD;
out[windex++] = S_BASE64PAD;
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[windex++] = S_BASE64CHAR[i>>10];
out[windex++] = S_BASE64CHAR[(i>>4)&0x3f];
out[windex++] = S_BASE64CHAR[(i<<2)&0x3f];
out[windex++] = S_BASE64PAD;
}
return new String(out, 0, windex);
}
/**
* Outputs base64 representation of the specified byte array to a byte stream.
*/
public static void encode(byte[] data, int off, int len, OutputStream ostream) throws IOException {
if (len <= 0) return;
byte[] out = new byte[4];
int rindex = off;
int rest = len-off;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[0] = (byte)S_BASE64CHAR[i>>18];
out[1] = (byte)S_BASE64CHAR[(i>>12)&0x3f];
out[2] = (byte)S_BASE64CHAR[(i>>6)&0x3f];
out[3] = (byte)S_BASE64CHAR[i&0x3f];
ostream.write(out, 0, 4);
rindex += 3;
rest -= 3;
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[0] = (byte)S_BASE64CHAR[i>>2];
out[1] = (byte)S_BASE64CHAR[(i<<4)&0x3f];
out[2] = (byte)S_BASE64PAD;
out[3] = (byte)S_BASE64PAD;
ostream.write(out, 0, 4);
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[0] = (byte)S_BASE64CHAR[i>>10];
out[1] = (byte)S_BASE64CHAR[(i>>4)&0x3f];
out[2] = (byte)S_BASE64CHAR[(i<<2)&0x3f];
out[3] = (byte)S_BASE64PAD;
ostream.write(out, 0, 4);
}
}
/**
* Outputs base64 representation of the specified byte array to a character stream.
*/
public static void encode(byte[] data, int off, int len, Writer writer) throws IOException {
if (len <= 0) return;
char[] out = new char[4];
int rindex = off;
int rest = len-off;
int output = 0;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[0] = S_BASE64CHAR[i>>18];
out[1] = S_BASE64CHAR[(i>>12)&0x3f];
out[2] = S_BASE64CHAR[(i>>6)&0x3f];
out[3] = S_BASE64CHAR[i&0x3f];
writer.write(out, 0, 4);
rindex += 3;
rest -= 3;
output += 4;
if (output % 76 == 0)
writer.write("\n");
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[0] = S_BASE64CHAR[i>>2];
out[1] = S_BASE64CHAR[(i<<4)&0x3f];
out[2] = S_BASE64PAD;
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[0] = S_BASE64CHAR[i>>10];
out[1] = S_BASE64CHAR[(i>>4)&0x3f];
out[2] = S_BASE64CHAR[(i<<2)&0x3f];
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
}
}
}
| 7,454 |
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/encoding/DefaultJAXRPC11TypeMappingImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.ser.CalendarDeserializerFactory;
import org.apache.axis.encoding.ser.CalendarSerializerFactory;
import org.apache.axis.encoding.ser.DateDeserializerFactory;
import org.apache.axis.encoding.ser.DateSerializerFactory;
import org.apache.axis.encoding.ser.TimeDeserializerFactory;
import org.apache.axis.encoding.ser.TimeSerializerFactory;
/**
* This is the implementation of the axis Default JAX-RPC SOAP Encoding TypeMapping
* See DefaultTypeMapping for more information.
*/
public class DefaultJAXRPC11TypeMappingImpl extends DefaultTypeMappingImpl {
private static DefaultJAXRPC11TypeMappingImpl tm = null;
/**
* Obtain the singleton default typemapping.
*/
public static synchronized TypeMappingImpl getSingleton() {
if (tm == null) {
tm = new DefaultJAXRPC11TypeMappingImpl();
}
return tm;
}
protected DefaultJAXRPC11TypeMappingImpl() {
registerXSDTypes();
}
/**
* Register the XSD data types in JAXRPC11 spec.
*/
private void registerXSDTypes() {
// Table 4-1 of the JAXRPC 1.1 spec
myRegisterSimple(Constants.XSD_UNSIGNEDINT, Long.class);
myRegisterSimple(Constants.XSD_UNSIGNEDINT, long.class);
myRegisterSimple(Constants.XSD_UNSIGNEDSHORT, Integer.class);
myRegisterSimple(Constants.XSD_UNSIGNEDSHORT, int.class);
myRegisterSimple(Constants.XSD_UNSIGNEDBYTE, Short.class);
myRegisterSimple(Constants.XSD_UNSIGNEDBYTE, short.class);
myRegister(Constants.XSD_DATETIME, java.util.Calendar.class,
new CalendarSerializerFactory(java.util.Calendar.class,
Constants.XSD_DATETIME),
new CalendarDeserializerFactory(java.util.Calendar.class,
Constants.XSD_DATETIME));
myRegister(Constants.XSD_DATE, java.util.Calendar.class,
new DateSerializerFactory(java.util.Calendar.class,
Constants.XSD_DATE),
new DateDeserializerFactory(java.util.Calendar.class,
Constants.XSD_DATE));
myRegister(Constants.XSD_TIME, java.util.Calendar.class,
new TimeSerializerFactory(java.util.Calendar.class,
Constants.XSD_TIME),
new TimeDeserializerFactory(java.util.Calendar.class,
Constants.XSD_TIME));
try {
myRegisterSimple(Constants.XSD_ANYURI,
Class.forName("java.net.URI"));
} catch (ClassNotFoundException e) {
myRegisterSimple(Constants.XSD_ANYURI, java.lang.String.class);
}
// Table 4-2 of JAXRPC 1.1 spec
myRegisterSimple(Constants.XSD_DURATION, java.lang.String.class);
myRegisterSimple(Constants.XSD_YEARMONTH, java.lang.String.class);
myRegisterSimple(Constants.XSD_YEAR, java.lang.String.class);
myRegisterSimple(Constants.XSD_MONTHDAY, java.lang.String.class);
myRegisterSimple(Constants.XSD_DAY, java.lang.String.class);
myRegisterSimple(Constants.XSD_MONTH, java.lang.String.class);
myRegisterSimple(Constants.XSD_NORMALIZEDSTRING,
java.lang.String.class);
myRegisterSimple(Constants.XSD_TOKEN, java.lang.String.class);
myRegisterSimple(Constants.XSD_LANGUAGE, java.lang.String.class);
myRegisterSimple(Constants.XSD_NAME, java.lang.String.class);
myRegisterSimple(Constants.XSD_NCNAME, java.lang.String.class);
myRegisterSimple(Constants.XSD_ID, java.lang.String.class);
myRegisterSimple(Constants.XSD_NMTOKEN, java.lang.String.class);
myRegisterSimple(Constants.XSD_NMTOKENS, java.lang.String.class);
myRegisterSimple(Constants.XSD_STRING, java.lang.String.class);
myRegisterSimple(Constants.XSD_NONPOSITIVEINTEGER,
java.math.BigInteger.class);
myRegisterSimple(Constants.XSD_NEGATIVEINTEGER,
java.math.BigInteger.class);
myRegisterSimple(Constants.XSD_NONNEGATIVEINTEGER,
java.math.BigInteger.class);
myRegisterSimple(Constants.XSD_UNSIGNEDLONG,
java.math.BigInteger.class);
myRegisterSimple(Constants.XSD_POSITIVEINTEGER,
java.math.BigInteger.class);
}
} | 7,455 |
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/encoding/DeserializationContext.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.encoding;
import org.apache.axis.MessageContext;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.AxisFault;
import org.apache.axis.constants.Use;
import org.apache.axis.attachments.Attachments;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.DefaultEntityResolver;
import org.apache.axis.utils.DefaultErrorHandler;
import org.apache.axis.utils.NSStack;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.cache.MethodCache;
import org.apache.axis.schema.SchemaVersion;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.message.IDResolver;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SAX2EventRecorder;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHandler;
import org.apache.axis.message.EnvelopeBuilder;
import org.apache.axis.message.EnvelopeHandler;
import org.apache.axis.message.NullAttributes;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Locator;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.namespace.QName;
import javax.xml.parsers.SAXParser;
import javax.xml.rpc.JAXRPCException;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* This interface describes the AXIS DeserializationContext, note that
* an AXIS compliant DeserializationContext must extend the org.xml.sax.helpers.DefaultHandler.
*/
public class DeserializationContext implements ContentHandler, DTDHandler,
javax.xml.rpc.encoding.DeserializationContext, LexicalHandler {
protected static Log log =
LogFactory.getLog(DeserializationContext.class.getName());
// invariant member variable to track low-level logging requirements
// we cache this once per instance lifecycle to avoid repeated lookups
// in heavily used code.
private final boolean debugEnabled = log.isDebugEnabled();
static final SchemaVersion schemaVersions[] = new SchemaVersion [] {
SchemaVersion.SCHEMA_1999,
SchemaVersion.SCHEMA_2000,
SchemaVersion.SCHEMA_2001,
};
private NSStack namespaces = new NSStack();
// Class used for deserialization using class metadata from
// downstream deserializers
private Class destClass;
// for performance reasons, keep the top of the stack separate from
// the remainder of the handlers, and therefore readily available.
private SOAPHandler topHandler = null;
private ArrayList pushedDownHandlers = new ArrayList();
//private SAX2EventRecorder recorder = new SAX2EventRecorder();
private SAX2EventRecorder recorder = null;
private SOAPEnvelope envelope;
/* A map of IDs -> IDResolvers */
private HashMap idMap;
private LocalIDResolver localIDs;
private HashMap fixups;
static final SOAPHandler nullHandler = new SOAPHandler();
protected MessageContext msgContext;
private boolean doneParsing = false;
protected InputSource inputSource = null;
private MessageElement curElement;
protected int startOfMappingsPos = -1;
private static final Class[] DESERIALIZER_CLASSES =
new Class[] {String.class, Class.class, QName.class};
private static final String DESERIALIZER_METHOD = "getDeserializer";
// This is a hack to associate the first schema namespace we see with
// the correct SchemaVersion. It assumes people won't often be mixing
// schema versions in a given document, which I think is OK. --Glen
protected boolean haveSeenSchemaNS = false;
public void deserializing(boolean isDeserializing) {
doneParsing = isDeserializing;
}
/**
* Construct Deserializer using MessageContext and EnvelopeBuilder handler
* @param ctx is the MessageContext
* @param initialHandler is the EnvelopeBuilder handler
*/
public DeserializationContext(MessageContext ctx,
SOAPHandler initialHandler)
{
msgContext = ctx;
// If high fidelity is required, record the whole damn thing.
if (ctx == null || ctx.isHighFidelity())
recorder = new SAX2EventRecorder();
if (initialHandler instanceof EnvelopeBuilder) {
envelope = ((EnvelopeBuilder)initialHandler).getEnvelope();
envelope.setRecorder(recorder);
}
pushElementHandler(new EnvelopeHandler(initialHandler));
}
/**
* Construct Deserializer
* @param is is the InputSource
* @param ctx is the MessageContext
* @param messageType is the MessageType to construct an EnvelopeBuilder
*/
public DeserializationContext(InputSource is,
MessageContext ctx,
String messageType)
{
msgContext = ctx;
EnvelopeBuilder builder = new EnvelopeBuilder(messageType, ctx != null ? ctx.getSOAPConstants() : null);
// If high fidelity is required, record the whole damn thing.
if (ctx == null || ctx.isHighFidelity())
recorder = new SAX2EventRecorder();
envelope = builder.getEnvelope();
envelope.setRecorder(recorder);
pushElementHandler(new EnvelopeHandler(builder));
inputSource = is;
}
private SOAPConstants soapConstants = null;
/**
* returns the soap constants.
*/
public SOAPConstants getSOAPConstants(){
if (soapConstants != null)
return soapConstants;
if (msgContext != null) {
soapConstants = msgContext.getSOAPConstants();
return soapConstants;
} else {
return Constants.DEFAULT_SOAP_VERSION;
}
}
/**
* Construct Deserializer
* @param is is the InputSource
* @param ctx is the MessageContext
* @param messageType is the MessageType to construct an EnvelopeBuilder
* @param env is the SOAPEnvelope to construct an EnvelopeBuilder
*/
public DeserializationContext(InputSource is,
MessageContext ctx,
String messageType,
SOAPEnvelope env)
{
EnvelopeBuilder builder = new EnvelopeBuilder(env, messageType);
msgContext = ctx;
// If high fidelity is required, record the whole damn thing.
if (ctx == null || ctx.isHighFidelity())
recorder = new SAX2EventRecorder();
envelope = builder.getEnvelope();
envelope.setRecorder(recorder);
pushElementHandler(new EnvelopeHandler(builder));
inputSource = is;
}
/**
* Create a parser and parse the inputSource
*/
public void parse() throws SAXException
{
if (inputSource != null) {
SAXParser parser = XMLUtils.getSAXParser();
try {
// We only set the DeserializationContext as ContentHandler and DTDHandler, but
// we use singletons for the EntityResolver and ErrorHandler. This reduces the risk
// that the SAX parser internally keeps a reference to the DeserializationContext
// after we release the parser. E.g. Oracle's SAX parser (oracle.xml.parser.v2) keeps a
// reference to the EntityResolver, although we reset the EntityResolver in
// XMLUtils#releaseSAXParser. That reference is only cleared when the parser is reused.
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
reader.setEntityResolver(DefaultEntityResolver.INSTANCE);
reader.setErrorHandler(DefaultErrorHandler.INSTANCE);
reader.setDTDHandler(this);
reader.setProperty("http://xml.org/sax/properties/lexical-handler", this);
reader.parse(inputSource);
try {
// cleanup - so that the parser can be reused.
reader.setProperty("http://xml.org/sax/properties/lexical-handler", nullLexicalHandler);
} catch (Exception e){
// Ignore.
}
// only release the parser for reuse if there wasn't an
// error. While parsers should be reusable, don't trust
// parsers that died to clean up appropriately.
XMLUtils.releaseSAXParser(parser);
} catch (IOException e) {
throw new SAXException(e);
}
inputSource = null;
}
}
/**
* Get current MessageElement
**/
public MessageElement getCurElement() {
return curElement;
}
/**
* Set current MessageElement
**/
public void setCurElement(MessageElement el)
{
curElement = el;
if (curElement != null && curElement.getRecorder() != recorder) {
recorder = curElement.getRecorder();
}
}
/**
* Get MessageContext
*/
public MessageContext getMessageContext()
{
return msgContext;
}
/**
* Returns this context's encoding style. If we've got a message
* context then we'll get the style from that; otherwise we'll
* return a default.
*
* @return a <code>String</code> value
*/
public String getEncodingStyle()
{
return msgContext == null ?
Use.ENCODED.getEncoding() : msgContext.getEncodingStyle();
}
/**
* Get Envelope
*/
public SOAPEnvelope getEnvelope()
{
return envelope;
}
/**
* Get Event Recorder
*/
public SAX2EventRecorder getRecorder()
{
return recorder;
}
/**
* Set Event Recorder
*/
public void setRecorder(SAX2EventRecorder recorder)
{
this.recorder = recorder;
}
/**
* Get the Namespace Mappings. Returns null if none are present.
**/
public ArrayList getCurrentNSMappings()
{
return namespaces.cloneFrame();
}
/**
* Get the Namespace for a particular prefix
*/
public String getNamespaceURI(String prefix)
{
String result = namespaces.getNamespaceURI(prefix);
if (result != null)
return result;
if (curElement != null)
return curElement.getNamespaceURI(prefix);
return null;
}
/**
* Construct a QName from a string of the form <prefix>:<localName>
* @param qNameStr is the prefixed name from the xml text
* @return QName
*/
public QName getQNameFromString(String qNameStr)
{
if (qNameStr == null)
return null;
// OK, this is a QName, so look up the prefix in our current mappings.
int i = qNameStr.indexOf(':');
String nsURI;
if (i == -1) {
nsURI = getNamespaceURI("");
} else {
nsURI = getNamespaceURI(qNameStr.substring(0, i));
}
return new QName(nsURI, qNameStr.substring(i + 1));
}
/**
* Create a QName for the type of the element defined by localName and
* namespace from the XSI type.
* @param namespace of the element
* @param localName is the local name of the element
* @param attrs are the attributes on the element
*/
public QName getTypeFromXSITypeAttr(String namespace, String localName,
Attributes attrs) {
// Check for type
String type = Constants.getValue(attrs, Constants.URIS_SCHEMA_XSI,
"type");
if (type == null) {
log.debug("No xsi:type attribute found");
return null;
} else {
// Return the type attribute value converted to a QName
QName result = getQNameFromString(type);
if (log.isDebugEnabled()) {
log.debug("xsi:type attribute found; raw=" + type + "; resolved=" + result);
}
return result;
}
}
/**
* Create a QName for the type of the element defined by localName and
* namespace with the specified attributes.
* @param namespace of the element
* @param localName is the local name of the element
* @param attrs are the attributes on the element
*/
public QName getTypeFromAttributes(String namespace, String localName,
Attributes attrs)
{
QName typeQName = getTypeFromXSITypeAttr(namespace, localName, attrs);
if ( (typeQName == null) && Constants.isSOAP_ENC(namespace) ) {
// If the element is a SOAP-ENC element, the name of the element is the type.
// If the default type mapping accepts SOAP 1.2, then use then set
// the typeQName to the SOAP-ENC type.
// Else if the default type mapping accepts SOAP 1.1, then
// convert the SOAP-ENC type to the appropriate XSD Schema Type.
if (namespace.equals(Constants.URI_SOAP12_ENC)) {
typeQName = new QName(namespace, localName);
} else if (localName.equals(Constants.SOAP_ARRAY.getLocalPart())) {
typeQName = Constants.SOAP_ARRAY;
} else if (localName.equals(Constants.SOAP_STRING.getLocalPart())) {
typeQName = Constants.SOAP_STRING;
} else if (localName.equals(Constants.SOAP_BOOLEAN.getLocalPart())) {
typeQName = Constants.SOAP_BOOLEAN;
} else if (localName.equals(Constants.SOAP_DOUBLE.getLocalPart())) {
typeQName = Constants.SOAP_DOUBLE;
} else if (localName.equals(Constants.SOAP_FLOAT.getLocalPart())) {
typeQName = Constants.SOAP_FLOAT;
} else if (localName.equals(Constants.SOAP_INT.getLocalPart())) {
typeQName = Constants.SOAP_INT;
} else if (localName.equals(Constants.SOAP_LONG.getLocalPart())) {
typeQName = Constants.SOAP_LONG;
} else if (localName.equals(Constants.SOAP_SHORT.getLocalPart())) {
typeQName = Constants.SOAP_SHORT;
} else if (localName.equals(Constants.SOAP_BYTE.getLocalPart())) {
typeQName = Constants.SOAP_BYTE;
}
}
// If we still have no luck, check to see if there's an arrayType
// (itemType for SOAP 1.2) attribute, in which case this is almost
// certainly an array.
if (typeQName == null && attrs != null) {
String encURI = getSOAPConstants().getEncodingURI();
String itemType = getSOAPConstants().getAttrItemType();
for (int i = 0; i < attrs.getLength(); i++) {
if (encURI.equals(attrs.getURI(i)) &&
itemType.equals(attrs.getLocalName(i))) {
return new QName(encURI, "Array");
}
}
}
return typeQName;
}
/**
* Convenenience method that returns true if the value is nil
* (due to the xsi:nil) attribute.
* @param attrs are the element attributes.
* @return true if xsi:nil is true
*/
public boolean isNil(Attributes attrs) {
return JavaUtils.isTrueExplicitly(
Constants.getValue(attrs, Constants.QNAMES_NIL),
false);
}
/**
* Get a Deserializer which can turn a given xml type into a given
* Java type
*/
public final Deserializer getDeserializer(Class cls, QName xmlType) {
if (xmlType == null)
return null;
DeserializerFactory dserF = null;
Deserializer dser = null;
try {
dserF = (DeserializerFactory) getTypeMapping().
getDeserializer(cls, xmlType);
} catch (JAXRPCException e) {
log.error(Messages.getMessage("noFactory00", xmlType.toString()));
}
if (dserF != null) {
try {
dser = (Deserializer) dserF.getDeserializerAs(Constants.AXIS_SAX);
} catch (JAXRPCException e) {
log.error(Messages.getMessage("noDeser00", xmlType.toString()));
}
}
return dser;
}
/**
* Convenience method to get the Deserializer for a specific
* java class from its meta data.
* @param cls is the Class used to find the deserializer
* @return Deserializer
*/
public Deserializer getDeserializerForClass(Class cls) {
if (cls == null) {
cls = destClass;
}
if (cls == null) {
return null;
}
// if (cls.isArray()) {
// cls = cls.getComponentType();
// }
if (javax.xml.rpc.holders.Holder.class.isAssignableFrom(cls)) {
try {
cls = cls.getField("value").getType();
} catch (Exception e) {
}
}
Deserializer dser = null;
QName type = getTypeMapping().getTypeQName(cls);
dser = getDeserializer(cls, type);
if (dser != null)
return dser;
try {
Method method =
MethodCache.getInstance().getMethod(cls,
DESERIALIZER_METHOD,
DESERIALIZER_CLASSES);
if (method != null) {
TypeDesc typedesc = TypeDesc.getTypeDescForClass(cls);
if (typedesc != null) {
dser = (Deserializer) method.invoke(null,
new Object[] {getEncodingStyle(), cls, typedesc.getXmlType()});
}
}
} catch (Exception e) {
log.error(Messages.getMessage("noDeser00", cls.getName()));
}
return dser;
}
/**
* Allows the destination class to be set so that downstream
* deserializers like ArrayDeserializer can pick it up when
* deserializing its components using getDeserializerForClass
* @param destClass is the Class of the component to be deserialized
*/
public void setDestinationClass(Class destClass) {
this.destClass = destClass;
}
/**
* Allows the destination class to be retrieved so that downstream
* deserializers like ArrayDeserializer can pick it up when
* deserializing its components using getDeserializerForClass
* @return the Class of the component to be deserialized
*/
public Class getDestinationClass() {
return destClass;
}
/**
* Convenience method to get the Deserializer for a specific
* xmlType.
* @param xmlType is QName for a type to deserialize
* @return Deserializer
*/
public final Deserializer getDeserializerForType(QName xmlType) {
return getDeserializer(null, xmlType);
}
/**
* Get the TypeMapping for this DeserializationContext
*/
public TypeMapping getTypeMapping()
{
if (msgContext == null || msgContext.getTypeMappingRegistry() == null) {
return (TypeMapping) new org.apache.axis.encoding.TypeMappingRegistryImpl().getTypeMapping(
null);
}
TypeMappingRegistry tmr = msgContext.getTypeMappingRegistry();
return (TypeMapping) tmr.getTypeMapping(getEncodingStyle());
}
/**
* Get the TypeMappingRegistry we're using.
* @return TypeMapping or null
*/
public TypeMappingRegistry getTypeMappingRegistry() {
return msgContext.getTypeMappingRegistry();
}
/**
* Get the MessageElement for the indicated id (where id is the #value of an href)
* If the MessageElement has not been processed, the MessageElement will
* be returned. If the MessageElement has been processed, the actual object
* value is stored with the id and this routine will return null.
* @param id is the value of an href attribute
* @return MessageElement or null
*/
public MessageElement getElementByID(String id)
{
if((idMap != null)) {
IDResolver resolver = (IDResolver)idMap.get(id);
if(resolver != null) {
Object ret = resolver.getReferencedObject(id);
if (ret instanceof MessageElement)
return (MessageElement)ret;
}
}
return null;
}
/**
* Gets the MessageElement or actual Object value associated with the href value.
* The return of a MessageElement indicates that the referenced element has
* not been processed. If it is not a MessageElement, the Object is the
* actual deserialized value.
* In addition, this method is invoked to get Object values via Attachments.
* @param href is the value of an href attribute (or an Attachment id)
* @return MessageElement other Object or null
*/
public Object getObjectByRef(String href) {
Object ret= null;
if(href != null){
if((idMap != null)){
IDResolver resolver = (IDResolver)idMap.get(href);
if(resolver != null)
ret = resolver.getReferencedObject(href);
}
if( null == ret && !href.startsWith("#")){
//Could this be an attachment?
Message msg= null;
if(null != (msg=msgContext.getCurrentMessage())){
Attachments attch= null;
if( null != (attch= msg.getAttachmentsImpl())){
try{
ret= attch.getAttachmentByReference(href);
}catch(AxisFault e){
throw new RuntimeException(e.toString() + JavaUtils.stackToString(e));
}
}
}
}
}
return ret;
}
/**
* Add the object associated with this id (where id is the value of an id= attribute,
* i.e. it does not start with #).
* This routine is called to associate the deserialized object
* with the id specified on the XML element.
* @param id (id name without the #)
* @param obj is the deserialized object for this id.
*/
public void addObjectById(String id, Object obj)
{
// The resolver uses the href syntax as the key.
String idStr = '#' + id;
if ((idMap == null) || (id == null))
return ;
IDResolver resolver = (IDResolver)idMap.get(idStr);
if (resolver == null)
return ;
resolver.addReferencedObject(idStr, obj);
return;
}
/**
* During deserialization, an element with an href=#id<int>
* may be encountered before the element defining id=id<int> is
* read. In these cases, the getObjectByRef method above will
* return null. The deserializer is placed in a table keyed
* by href (a fixup table). After the element id is processed,
* the deserializer is informed of the value so that it can
* update its target(s) with the value.
* @param href (#id syntax)
* @param dser is the deserializer of the element
*/
public void registerFixup(String href, Deserializer dser)
{
if (fixups == null)
fixups = new HashMap();
Deserializer prev = (Deserializer) fixups.put(href, dser);
// There could already be a deserializer in the fixup list
// for this href. If so, the easiest way to get all of the
// targets updated is to move the previous deserializers
// targets to dser.
if (prev != null && prev != dser) {
dser.moveValueTargets(prev);
if (dser.getDefaultType() == null) {
dser.setDefaultType(prev.getDefaultType());
}
}
}
/**
* Register the MessageElement with this id (where id is id= form without the #)
* This routine is called when the MessageElement with an id is read.
* If there is a Deserializer in our fixup list (described above),
* the 'fixup' deserializer is given to the MessageElement. When the
* MessageElement is completed, the 'fixup' deserializer is informed and
* it can set its targets.
* @param id (id name without the #)
* @param elem is the MessageElement
*/
public void registerElementByID(String id, MessageElement elem)
{
if (localIDs == null)
localIDs = new LocalIDResolver();
String absID = '#' + id;
localIDs.addReferencedObject(absID, elem);
registerResolverForID(absID, localIDs);
if (fixups != null) {
Deserializer dser = (Deserializer)fixups.get(absID);
if (dser != null) {
elem.setFixupDeserializer(dser);
}
}
}
/**
* Each id can have its own kind of resolver. This registers a
* resolver for the id.
*/
public void registerResolverForID(String id, IDResolver resolver)
{
if ((id == null) || (resolver == null)) {
// ??? Throw nullPointerException?
return;
}
if (idMap == null)
idMap = new HashMap();
idMap.put(id, resolver);
}
/**
* Return true if any ids are being tracked by this DeserializationContext
*
* @return true if any ides are being tracked by this DeserializationContext
*/
public boolean hasElementsByID()
{
return idMap == null ? false : idMap.size() > 0;
}
/**
* Get the current position in the record.
*/
public int getCurrentRecordPos()
{
if (recorder == null) return -1;
return recorder.getLength() - 1;
}
/**
* Get the start of the mapping position
*/
public int getStartOfMappingsPos()
{
if (startOfMappingsPos == -1) {
return getCurrentRecordPos() + 1;
}
return startOfMappingsPos;
}
/**
* Push the MessageElement into the recorder
*/
public void pushNewElement(MessageElement elem)
{
if (debugEnabled) {
log.debug("Pushing element " + elem.getName());
}
if (!doneParsing && (recorder != null)) {
recorder.newElement(elem);
}
try {
if(curElement != null)
elem.setParentElement(curElement);
} catch (Exception e) {
/*
* The only checked exception that may be thrown from setParent
* occurs if the parent already has an explicit object value,
* which should never occur during deserialization.
*/
log.fatal(Messages.getMessage("exception00"), e);
}
curElement = elem;
if (elem.getRecorder() != recorder)
recorder = elem.getRecorder();
}
/****************************************************************
* Management of sub-handlers (deserializers)
*/
public void pushElementHandler(SOAPHandler handler)
{
if (debugEnabled) {
log.debug(Messages.getMessage("pushHandler00", "" + handler));
}
if (topHandler != null) pushedDownHandlers.add(topHandler);
topHandler = handler;
}
/** Replace the handler at the top of the stack.
*
* This is only used when we have a placeholder Deserializer
* for a referenced object which doesn't know its type until we
* hit the referent.
*/
public void replaceElementHandler(SOAPHandler handler)
{
topHandler = handler;
}
public SOAPHandler popElementHandler()
{
SOAPHandler result = topHandler;
int size = pushedDownHandlers.size();
if (size > 0) {
topHandler = (SOAPHandler) pushedDownHandlers.remove(size-1);
} else {
topHandler = null;
}
if (debugEnabled) {
if (result == null) {
log.debug(Messages.getMessage("popHandler00", "(null)"));
} else {
log.debug(Messages.getMessage("popHandler00", "" + result));
}
}
return result;
}
boolean processingRef = false;
public void setProcessingRef(boolean ref) {
processingRef = ref;
}
public boolean isProcessingRef() {
return processingRef;
}
/****************************************************************
* SAX event handlers
*/
public void startDocument() throws SAXException {
// Should never receive this in the midst of a parse.
if (!doneParsing && (recorder != null))
recorder.startDocument();
}
/**
* endDocument is invoked at the end of the document.
*/
public void endDocument() throws SAXException {
if (debugEnabled) {
log.debug("Enter: DeserializationContext::endDocument()");
}
if (!doneParsing && (recorder != null))
recorder.endDocument();
doneParsing = true;
if (debugEnabled) {
log.debug("Exit: DeserializationContext::endDocument()");
}
}
/**
* Return if done parsing document.
*/
public boolean isDoneParsing() {return doneParsing;}
/** Record the current set of prefix mappings in the nsMappings table.
*
* !!! We probably want to have this mapping be associated with the
* MessageElements, since they may potentially need access to them
* long after the end of the prefix mapping here. (example:
* when we need to record a long string of events scanning forward
* in the document to find an element with a particular ID.)
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
if (debugEnabled) {
log.debug("Enter: DeserializationContext::startPrefixMapping(" + prefix + ", " + uri + ")");
}
if (!doneParsing && (recorder != null)) {
recorder.startPrefixMapping(prefix, uri);
}
if (startOfMappingsPos == -1) {
namespaces.push();
startOfMappingsPos = getCurrentRecordPos();
}
if (prefix != null) {
namespaces.add(uri, prefix);
} else {
namespaces.add(uri, "");
}
if (!haveSeenSchemaNS && msgContext != null) {
// If we haven't yet seen a schema namespace, check if this
// is one. If so, set the SchemaVersion appropriately.
// Hopefully the schema def is on the outermost element so we
// get this over with quickly.
for (int i = 0; !haveSeenSchemaNS && i < schemaVersions.length;
i++) {
SchemaVersion schemaVersion = schemaVersions[i];
if (uri.equals(schemaVersion.getXsdURI()) ||
uri.equals(schemaVersion.getXsiURI())) {
msgContext.setSchemaVersion(schemaVersion);
haveSeenSchemaNS = true;
}
}
}
if (topHandler != null) {
topHandler.startPrefixMapping(prefix, uri);
}
if (debugEnabled) {
log.debug("Exit: DeserializationContext::startPrefixMapping()");
}
}
public void endPrefixMapping(String prefix)
throws SAXException
{
if (debugEnabled) {
log.debug("Enter: DeserializationContext::endPrefixMapping(" + prefix + ")");
}
if (!doneParsing && (recorder != null)) {
recorder.endPrefixMapping(prefix);
}
if (topHandler != null) {
topHandler.endPrefixMapping(prefix);
}
if (debugEnabled) {
log.debug("Exit: DeserializationContext::endPrefixMapping()");
}
}
public void setDocumentLocator(Locator locator)
{
// We don't store the Locator because we don't need it. In addition it is typically
// a reference to some internal object of the parser and not keeping that reference
// ensures that this object (which may be heavyweight) can be garbage collected
// early (see AXIS-2863 for an issue that may be related to this: in that case,
// Locator is implemented by oracle.xml.parser.v2.XMLReader).
}
public void characters(char[] p1, int p2, int p3) throws SAXException {
if (!doneParsing && (recorder != null)) {
recorder.characters(p1, p2, p3);
}
if (topHandler != null) {
topHandler.characters(p1, p2, p3);
}
}
public void ignorableWhitespace(char[] p1, int p2, int p3) throws SAXException {
if (!doneParsing && (recorder != null)) {
recorder.ignorableWhitespace(p1, p2, p3);
}
if (topHandler != null) {
topHandler.ignorableWhitespace(p1, p2, p3);
}
}
public void processingInstruction(String p1, String p2) throws SAXException {
// must throw an error since SOAP 1.1 doesn't allow
// processing instructions anywhere in the message
throw new SAXException(Messages.getMessage("noInstructions00"));
}
public void skippedEntity(String p1) throws SAXException {
if (!doneParsing && (recorder != null)) {
recorder.skippedEntity(p1);
}
topHandler.skippedEntity(p1);
}
/**
* startElement is called when an element is read. This is the big work-horse.
*
* This guy also handles monitoring the recording depth if we're recording
* (so we know when to stop).
*/
public void startElement(String namespace, String localName,
String qName, Attributes attributes)
throws SAXException
{
if (debugEnabled) {
log.debug("Enter: DeserializationContext::startElement(" + namespace + ", " + localName + ")");
}
if (attributes == null || attributes.getLength() == 0) {
attributes = NullAttributes.singleton;
} else {
attributes = new AttributesImpl(attributes);
SOAPConstants soapConstants = getSOAPConstants();
if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
if (attributes.getValue(soapConstants.getAttrHref()) != null &&
attributes.getValue(Constants.ATTR_ID) != null) {
AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER,
null, Messages.getMessage("noIDandHREFonSameElement"), null, null, null);
throw new SAXException(fault);
}
}
}
SOAPHandler nextHandler = null;
String prefix = "";
int idx = qName.indexOf(':');
if (idx > 0) {
prefix = qName.substring(0, idx);
}
if (topHandler != null) {
nextHandler = topHandler.onStartChild(namespace,
localName,
prefix,
attributes,
this);
}
if (nextHandler == null) {
nextHandler = new SOAPHandler();
}
pushElementHandler(nextHandler);
nextHandler.startElement(namespace, localName, prefix,
attributes, this);
if (!doneParsing && (recorder != null)) {
recorder.startElement(namespace, localName, qName,
attributes);
if (!doneParsing) {
curElement.setContentsIndex(recorder.getLength());
}
}
if (startOfMappingsPos != -1) {
startOfMappingsPos = -1;
} else {
// Push an empty frame if there are no mappings
namespaces.push();
}
if (debugEnabled) {
log.debug("Exit: DeserializationContext::startElement()");
}
}
/**
* endElement is called at the end tag of an element
*/
public void endElement(String namespace, String localName, String qName)
throws SAXException
{
if (debugEnabled) {
log.debug("Enter: DeserializationContext::endElement(" + namespace + ", " + localName + ")");
}
if (!doneParsing && (recorder != null)) {
recorder.endElement(namespace, localName, qName);
}
try {
SOAPHandler handler = popElementHandler();
handler.endElement(namespace, localName, this);
if (topHandler != null) {
topHandler.onEndChild(namespace, localName, this);
} else {
// We should be done!
}
} finally {
if (curElement != null) {
curElement = (MessageElement)curElement.getParentElement();
}
namespaces.pop();
if (debugEnabled) {
String name = curElement != null ?
curElement.getClass().getName() + ":" +
curElement.getName() : null;
log.debug("Popped element stack to " + name);
log.debug("Exit: DeserializationContext::endElement()");
}
}
}
/**
* This class is used to map ID's to an actual value Object or Message
*/
private static class LocalIDResolver implements IDResolver
{
HashMap idMap = null;
/**
* Add object associated with id
*/
public void addReferencedObject(String id, Object referent)
{
if (idMap == null) {
idMap = new HashMap();
}
idMap.put(id, referent);
}
/**
* Get object referenced by href
*/
public Object getReferencedObject(String href)
{
if ((idMap == null) || (href == null)) {
return null;
}
return idMap.get(href);
}
}
public void startDTD(java.lang.String name,
java.lang.String publicId,
java.lang.String systemId)
throws SAXException
{
/* It is possible for a malicious user to send us bad stuff in
the <!DOCTYPE ../> tag that will cause a denial of service
Example:
<?xml version="1.0" ?>
<!DOCTYPE foobar [
<!ENTITY x0 "hello">
<!ENTITY x1 "&x0;&x0;">
<!ENTITY x2 "&x1;&x1;">
...
<!ENTITY x99 "&x98;&x98;">
<!ENTITY x100 "&x99;&x99;">
]>
*/
throw new SAXException(Messages.getMessage("noInstructions00"));
/* if (recorder != null)
recorder.startDTD(name, publicId, systemId);
*/
}
public void notationDecl(String name, String publicId, String systemId) throws SAXException {
// Do nothing; we never get here
}
public void unparsedEntityDecl(String name, String publicId, String systemId,
String notationName) throws SAXException {
// Do nothing; we never get here
}
public void endDTD()
throws SAXException
{
if (recorder != null)
recorder.endDTD();
}
public void startEntity(java.lang.String name)
throws SAXException
{
if (recorder != null)
recorder.startEntity(name);
}
public void endEntity(java.lang.String name)
throws SAXException
{
if (recorder != null)
recorder.endEntity(name);
}
public void startCDATA()
throws SAXException
{
if (recorder != null)
recorder.startCDATA();
}
public void endCDATA()
throws SAXException
{
if (recorder != null)
recorder.endCDATA();
}
public void comment(char[] ch,
int start,
int length)
throws SAXException
{
if (recorder != null)
recorder.comment(ch, start, length);
}
/** We only need one instance of this dummy handler to set into the parsers. */
private static final NullLexicalHandler nullLexicalHandler = new NullLexicalHandler();
/**
* It is illegal to set the lexical-handler property to null. To facilitate
* discarding the heavily loaded instance of DeserializationContextImpl from
* the SAXParser instance that is kept in the Stack maintained by XMLUtils
* we use this class.
*/
private static class NullLexicalHandler implements LexicalHandler {
public void startDTD(String arg0, String arg1, String arg2) throws SAXException {}
public void endDTD() throws SAXException {}
public void startEntity(String arg0) throws SAXException {}
public void endEntity(String arg0) throws SAXException {}
public void startCDATA() throws SAXException {}
public void endCDATA() throws SAXException {}
public void comment(char[] arg0, int arg1, int arg2) throws SAXException {}
}
}
| 7,456 |
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/encoding/TypeMappingDelegate.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.encoding;
import org.apache.axis.utils.Messages;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
/**
* The TypeMapping delegate is used to simply delegate to
* the indicated type mapping. It is used by the TypeMappingRegistry
* to assist with chaining.
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class TypeMappingDelegate implements TypeMapping {
static final TypeMappingImpl placeholder = new TypeMappingImpl();
TypeMappingImpl delegate;
TypeMappingDelegate next;
/**
* Construct TypeMapping
*/
TypeMappingDelegate(TypeMappingImpl delegate) {
if (delegate == null) {
throw new RuntimeException(Messages.getMessage("NullDelegate"));
}
this.delegate = delegate;
}
/********* JAX-RPC Compliant Method Definitions *****************/
// Delegate or throw an exception
public String[] getSupportedEncodings() {
return delegate.getSupportedEncodings();
}
public void setSupportedEncodings(String[] namespaceURIs) {
delegate.setSupportedEncodings(namespaceURIs);
}
/**
* always throws an exception
* @param javaType
* @param xmlType
* @param sf
* @param dsf
* @throws JAXRPCException
*/
public void register(Class javaType, QName xmlType,
javax.xml.rpc.encoding.SerializerFactory sf,
javax.xml.rpc.encoding.DeserializerFactory dsf)
throws JAXRPCException {
delegate.register(javaType, xmlType, sf, dsf);
}
public javax.xml.rpc.encoding.SerializerFactory
getSerializer(Class javaType, QName xmlType)
throws JAXRPCException
{
javax.xml.rpc.encoding.SerializerFactory sf = delegate.getSerializer(javaType, xmlType);
if (sf == null && next != null) {
sf = next.getSerializer(javaType, xmlType);
}
if (sf == null) {
sf = delegate.finalGetSerializer(javaType);
}
return sf;
}
public javax.xml.rpc.encoding.SerializerFactory
getSerializer(Class javaType)
throws JAXRPCException
{
return getSerializer(javaType, null);
}
public javax.xml.rpc.encoding.DeserializerFactory
getDeserializer(Class javaType, QName xmlType)
throws JAXRPCException {
return getDeserializer(javaType, xmlType, this);
}
public javax.xml.rpc.encoding.DeserializerFactory
getDeserializer(Class javaType, QName xmlType, TypeMappingDelegate start)
throws JAXRPCException {
javax.xml.rpc.encoding.DeserializerFactory df =
delegate.getDeserializer(javaType, xmlType, start);
if (df == null && next != null) {
df = next.getDeserializer(javaType, xmlType, start);
}
if (df == null) {
df = delegate.finalGetDeserializer(javaType, xmlType, start);
}
return df;
}
public javax.xml.rpc.encoding.DeserializerFactory
getDeserializer(QName xmlType)
throws JAXRPCException {
return getDeserializer(null, xmlType);
}
public void removeSerializer(Class javaType, QName xmlType)
throws JAXRPCException {
delegate.removeSerializer(javaType, xmlType);
}
public void removeDeserializer(Class javaType, QName xmlType)
throws JAXRPCException {
delegate.removeDeserializer(javaType, xmlType);
}
public boolean isRegistered(Class javaType, QName xmlType) {
boolean result = delegate.isRegistered(javaType, xmlType);
if (result == false && next != null) {
return next.isRegistered(javaType, xmlType);
}
return result;
}
/********* End JAX-RPC Compliant Method Definitions *****************/
/**
* Gets the QName for the type mapped to Class.
* @param javaType class or type
* @return xmlType qname or null
*/
public QName getTypeQName(Class javaType) {
return delegate.getTypeQName(javaType, next);
}
/**
* Gets the Class mapped to QName.
* @param xmlType qname or null
* @return javaType class for type or null for no mappingor delegate
*/
public Class getClassForQName(QName xmlType) {
return getClassForQName(xmlType, null);
}
/**
* Gets the Class mapped to QName, preferring the passed Class if possible
* @param xmlType qname or null
* @param javaType a Java class
* @return javaType class for type or null for no mappingor delegate
*/
public Class getClassForQName(QName xmlType, Class javaType) {
return delegate.getClassForQName(xmlType, javaType, next);
}
/**
* Get the QName for this Java class, but only return a specific
* mapping if there is one. In other words, don't do special array
* processing, etc.
*
* @param javaType
* @return
*/
public QName getTypeQNameExact(Class javaType) {
QName result = delegate.getTypeQNameExact(javaType, next);
return result;
}
/**
* setDelegate sets the new Delegate TypeMapping
*/
public void setNext(TypeMappingDelegate next) {
if (next == this) {
return; // Refuse to set up tight loops (throw exception?)
}
this.next = next;
}
/**
* getDelegate gets the new Delegate TypeMapping
*/
public TypeMappingDelegate getNext() {
return next;
}
/**
* Returns an array of all the classes contained within this mapping
*/
public Class[] getAllClasses() {
return delegate.getAllClasses(next);
}
/**
* Get the exact XML type QName which will be used when serializing a
* given Class to a given type QName. In other words, if we have:
*
* Class TypeQName
* ----------------------
* Base myNS:Base
* Child myNS:Child
*
* and call getXMLType(Child.class, BASE_QNAME), we should get
* CHILD_QNAME.
*
* @param javaType
* @param xmlType
* @return the type's QName
* @throws JAXRPCException
*/
public QName getXMLType(Class javaType, QName xmlType, boolean encoded)
throws JAXRPCException {
QName result = delegate.getXMLType(javaType, xmlType, encoded);
if (result == null && next != null) {
return next.getXMLType(javaType, xmlType, encoded);
}
return result;
}
public void setDoAutoTypes(boolean doAutoTypes) {
delegate.setDoAutoTypes(doAutoTypes);
}
}
| 7,457 |
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/encoding/SimpleValueSerializer.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.
*/
/**
* Serializers which implement this interface are indicating their
* ability to serialize "simple" values as strings. These are things
* suitable for putting in attributes, for instance.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
package org.apache.axis.encoding;
public interface SimpleValueSerializer extends Serializer {
/**
* Return an XML compatible representation of the value.
*
* @param value
* @return
*/
public String getValueAsString(Object value, SerializationContext context);
}
| 7,458 |
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/encoding/XMLType.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.encoding ;
/**
*
* @author Doug Davis (dug@us.ibm.com)
*/
import org.apache.axis.Constants;
import javax.xml.namespace.QName;
public class XMLType extends Constants {
/** A "marker" XML type QName we use to indicate a void type. */
public static final QName AXIS_VOID = new QName(Constants.NS_URI_AXIS, "Void");
// public static QName XSD_DATE;
//
// static {
// if (Constants.NS_URI_CURRENT_SCHEMA_XSD.equals(Constants.NS_URI_1999_SCHEMA_XSD))
// XSD_DATE = Constants.XSD_DATE2;
// else if (Constants.NS_URI_CURRENT_SCHEMA_XSD.equals(Constants.NS_URI_2000_SCHEMA_XSD))
// XSD_DATE = Constants.XSD_DATE3;
// else
// XSD_DATE = Constants.XSD_DATE;
// }
}
| 7,459 |
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/encoding/TypeMapping.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.encoding;
import java.io.Serializable;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import javax.xml.rpc.encoding.DeserializerFactory;
import javax.xml.rpc.encoding.SerializerFactory;
/**
* This interface describes the AXIS TypeMapping.
*/
public interface TypeMapping
extends javax.xml.rpc.encoding.TypeMapping, Serializable {
/**
* Gets the SerializerFactory registered for the specified pair
* of Java type and XML data type.
*
* @param javaType - Class of the Java type
*
* @return Registered SerializerFactory
*
* @throws JAXRPCException - If there is no registered SerializerFactory
* for this pair of Java type and XML data type
* java.lang.IllegalArgumentException
* If invalid or unsupported XML/Java type is specified
*/
public SerializerFactory getSerializer(Class javaType)
throws JAXRPCException;
/**
* Gets the DeserializerFactory registered for the specified XML data type.
*
* @param xmlType - Qualified name of the XML data type
*
* @return Registered DeserializerFactory
*
* @throws JAXRPCException - If there is no registered DeserializerFactory
* for this pair of Java type and XML data type
* java.lang.IllegalArgumentException -
* If invalid or unsupported XML/Java type is specified
*/
public DeserializerFactory getDeserializer(QName xmlType)
throws JAXRPCException;
/**
* Gets the QName for the type mapped to Class.
* @param javaType class or type
* @return xmlType qname or null
*/
public QName getTypeQName(Class javaType);
/**
* Get the QName for this Java class, but only return a specific
* mapping if there is one. In other words, don't do special array
* processing, etc.
*
* @param javaType
* @return
*/
public QName getTypeQNameExact(Class javaType);
/**
* Gets the Class mapped to QName.
* @param xmlType qname or null
* @return javaType class for type or null for no mapping
*/
public Class getClassForQName(QName xmlType);
public Class getClassForQName(QName xmlType, Class javaType);
/**
* Returns an array of all the classes contained within this mapping
*/
public Class [] getAllClasses();
/**
* Get the exact XML type QName which will be used when serializing a
* given Class to a given type QName. In other words, if we have:
*
* Class TypeQName
* ----------------------
* Base myNS:Base
* Child myNS:Child
*
* and call getXMLType(Child.class, BASE_QNAME), we should get
* CHILD_QNAME.
*
* @param javaType
* @param xmlType
* @return the type's QName
* @throws javax.xml.rpc.JAXRPCException
*/
QName getXMLType(Class javaType, QName xmlType, boolean encoded)
throws JAXRPCException;
}
| 7,460 |
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/encoding/DeserializerTarget.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.encoding;
import org.xml.sax.SAXException;
// Target is a Deserializer. The set method invokes one of the setValue methods
// of the deserializer depending on whether a hint was given. The DeserializerTarget
// is used in situations when the Deserializer is expecting multiple values and cannot
// be considered complete until all values are received.
// (example is an ArrayDeserializer).
public class DeserializerTarget implements Target {
public Deserializer target;
public Object hint;
public DeserializerTarget(Deserializer target, Object hint)
{
this.target = target;
this.hint = hint;
}
public void set(Object value) throws SAXException {
if (hint != null) {
target.setChildValue(value, hint);
} else {
target.setValue(value);
}
}
}
| 7,461 |
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/encoding/Callback.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.encoding;
import org.xml.sax.SAXException;
public interface Callback
{
public void setValue(Object value, Object hint) throws SAXException;
}
| 7,462 |
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/encoding/MethodTarget.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.encoding;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// Target is set via a method call. The set method places the value in the field.
public class MethodTarget implements Target
{
protected static Log log =
LogFactory.getLog(MethodTarget.class.getName());
private Object targetObject;
private Method targetMethod;
private static final Class [] objArg = new Class [] { Object.class };
/**
* Construct a target whose value is set via a method
* @param targetObject is the object containing the value to be set
* @param targetMethod is the Method used to set the value
*/
public MethodTarget(Object targetObject, Method targetMethod)
{
this.targetObject = targetObject;
this.targetMethod = targetMethod;
}
/**
* Construct a target whose value is set via a method
* @param targetObject is the object containing the value to be set
* @param methodName is the name of the Method
*/
public MethodTarget(Object targetObject, String methodName)
throws NoSuchMethodException
{
this.targetObject = targetObject;
Class cls = targetObject.getClass();
targetMethod = cls.getMethod(methodName, objArg);
}
/**
* Set the target's value by invoking the targetMethod.
* @param value is the new Object value
*/
public void set(Object value) throws SAXException {
try {
targetMethod.invoke(targetObject, new Object [] { value });
} catch (IllegalAccessException accEx) {
log.error(Messages.getMessage("illegalAccessException00"),
accEx);
throw new SAXException(accEx);
} catch (IllegalArgumentException argEx) {
log.error(Messages.getMessage("illegalArgumentException00"),
argEx);
throw new SAXException(argEx);
} catch (InvocationTargetException targetEx) {
log.error(Messages.getMessage("invocationTargetException00"),
targetEx);
throw new SAXException(targetEx);
}
}
}
| 7,463 |
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/encoding/DefaultSOAPEncodingTypeMappingImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.ser.Base64SerializerFactory;
import org.apache.axis.encoding.ser.Base64DeserializerFactory;
import org.apache.axis.encoding.ser.ArraySerializerFactory;
import org.apache.axis.encoding.ser.ArrayDeserializerFactory;
/**
*
* This is the implementation of the axis Default JAX-RPC SOAP Encoding TypeMapping
* See DefaultTypeMapping for more information.
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class DefaultSOAPEncodingTypeMappingImpl extends DefaultTypeMappingImpl {
private static DefaultSOAPEncodingTypeMappingImpl tm = null;
/**
* Construct TypeMapping
*/
public static synchronized TypeMappingImpl getSingleton() {
if (tm == null) {
tm = new DefaultSOAPEncodingTypeMappingImpl();
}
return tm;
}
public static TypeMappingDelegate createWithDelegate() {
TypeMappingDelegate ret = new TypeMappingDelegate(new DefaultSOAPEncodingTypeMappingImpl());
MessageContext mc = MessageContext.getCurrentContext();
TypeMappingDelegate tm = null;
if (mc != null) {
tm = (TypeMappingDelegate)mc.getTypeMappingRegistry().getDefaultTypeMapping();
} else {
tm = DefaultTypeMappingImpl.getSingletonDelegate();
}
ret.setNext(tm);
return ret;
}
protected DefaultSOAPEncodingTypeMappingImpl() {
super(true);
registerSOAPTypes();
}
/**
* Register the SOAP encoding data types. This is split out into a
* method so it can happen either before or after the XSD mappings.
*/
private void registerSOAPTypes() {
// SOAP Encoded strings are treated as primitives.
// Everything else is not.
myRegisterSimple(Constants.SOAP_STRING, java.lang.String.class);
myRegisterSimple(Constants.SOAP_BOOLEAN, java.lang.Boolean.class);
myRegisterSimple(Constants.SOAP_DOUBLE, java.lang.Double.class);
myRegisterSimple(Constants.SOAP_FLOAT, java.lang.Float.class);
myRegisterSimple(Constants.SOAP_INT, java.lang.Integer.class);
myRegisterSimple(Constants.SOAP_INTEGER, java.math.BigInteger.class);
myRegisterSimple(Constants.SOAP_DECIMAL, java.math.BigDecimal.class);
myRegisterSimple(Constants.SOAP_LONG, java.lang.Long.class);
myRegisterSimple(Constants.SOAP_SHORT, java.lang.Short.class);
myRegisterSimple(Constants.SOAP_BYTE, java.lang.Byte.class);
myRegister(Constants.SOAP_BASE64, byte[].class,
new Base64SerializerFactory(byte[].class,
Constants.SOAP_BASE64),
new Base64DeserializerFactory(byte[].class,
Constants.SOAP_BASE64)
);
myRegister(Constants.SOAP_BASE64BINARY, byte[].class,
new Base64SerializerFactory(byte[].class,
Constants.SOAP_BASE64BINARY),
new Base64DeserializerFactory(byte[].class,
Constants.SOAP_BASE64BINARY)
);
myRegister(Constants.SOAP_ARRAY12, java.util.Collection.class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
myRegister(Constants.SOAP_ARRAY12, java.util.ArrayList.class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
myRegister(Constants.SOAP_ARRAY12, Object[].class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
myRegister(Constants.SOAP_ARRAY, java.util.ArrayList.class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
// All array objects automatically get associated with the SOAP_ARRAY.
// There is no way to do this with a hash table,
// so it is done directly in getTypeQName.
// Internally the runtime uses ArrayList objects to hold arrays...
// which is the reason that ArrayList is associated with SOAP_ARRAY.
// In addition, handle all objects that implement the List interface
// as a SOAP_ARRAY
myRegister(Constants.SOAP_ARRAY, java.util.Collection.class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
myRegister(Constants.SOAP_ARRAY, Object[].class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
}
}
| 7,464 |
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/encoding/ConstructorTarget.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.encoding;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.SAXException;
import org.apache.axis.i18n.Messages;
/**
* Used when the class need a specific Constructor (not default one)
* @author Florent Benoit
*/
public class ConstructorTarget implements Target {
/**
* Constructor to use
*/
private Constructor constructor = null;
/**
* Deserializer on which set value
*/
private Deserializer deSerializer = null;
/**
* List of values
*/
private List values = null;
public ConstructorTarget(Constructor constructor, Deserializer deSerializer) {
this.deSerializer = deSerializer;
this.constructor = constructor;
values = new ArrayList();
}
/**
* Instantiate a new class with right constructor
* @param value value to use on Constructor
* @throws SAXException on error
*/
public void set(Object value) throws SAXException {
try {
// store received value
values.add(value);
// got right parameter length
if (constructor.getParameterTypes().length == values.size()) {
// type of parameters
Class[] classes = constructor.getParameterTypes();
// args array
Object[] args = new Object[constructor.getParameterTypes().length];
// Get arg for the type of the class
for (int c = 0; c < classes.length; c++) {
boolean found = false;
int i = 0;
while (!found && i < values.size()) {
// got right class arg
if (values.get(i).getClass().getName().toLowerCase().indexOf(classes[c].getName().toLowerCase()) != -1) {
found = true;
args[c] = values.get(i);
}
i++;
}
// no suitable object for class required
if (!found) {
throw new SAXException(Messages.getMessage("cannotFindObjectForClass00", classes[c].toString()));
}
}
// then build object
Object o = constructor.newInstance(args);
deSerializer.setValue(o);
}
} catch (Exception e) {
throw new SAXException(e);
}
}
}
| 7,465 |
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/encoding/TypeMappingImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.AxisProperties;
import org.apache.axis.MessageContext;
import org.apache.axis.AxisEngine;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.ser.ArrayDeserializerFactory;
import org.apache.axis.encoding.ser.ArraySerializerFactory;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.utils.ArrayUtil;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.ClassUtils;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.wsdl.fromJava.Namespaces;
import org.apache.axis.wsdl.fromJava.Types;
import org.apache.axis.wsdl.symbolTable.Utils;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.Serializable;
/**
* <p>
* This is the implementation of the axis TypeMapping interface (which extends
* the JAX-RPC TypeMapping interface).
* </p>
* <p>
* A TypeMapping is obtained from the singleton TypeMappingRegistry using
* the namespace of the webservice. The TypeMapping contains the tuples
* {Java type, SerializerFactory, DeserializerFactory, Type QName)
* </p>
* <p>
* So if you have a Web Service with the namespace "XYZ", you call
* the TypeMappingRegistry.getTypeMapping("XYZ").
* </p>
* <p>
* The wsdl in your web service will use a number of types. The tuple
* information for each of these will be accessed via the TypeMapping.
* </p>
* <p>
* Because every web service uses the soap, schema, wsdl primitives, we could
* pre-populate the TypeMapping with these standard tuples. Instead,
* if the namespace/class matches is not found in the TypeMapping
* the request is delegated to the
* Default TypeMapping or another TypeMapping
* </p>
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class TypeMappingImpl implements Serializable
{
protected static Log log =
LogFactory.getLog(TypeMappingImpl.class.getName());
/**
* Work around a .NET bug with soap encoded types.
* This is a static property of the type mapping that will
* cause the class to ignore SOAPENC types when looking up
* QNames of java types. See getTypeQNameExact().
*/
public static boolean dotnet_soapenc_bugfix = false;
public static class Pair implements Serializable {
public Class javaType;
public QName xmlType;
public Pair(Class javaType, QName xmlType) {
this.javaType = javaType;
this.xmlType = xmlType;
}
public boolean equals(Object o) {
if (o == null) return false;
Pair p = (Pair) o;
// Test straight equality
if (p.xmlType == this.xmlType &&
p.javaType == this.javaType) {
return true;
}
return (p.xmlType.equals(this.xmlType) &&
p.javaType.equals(this.javaType));
}
public int hashCode() {
int hashcode = 0;
if (javaType != null) {
hashcode ^= javaType.hashCode();
}
if (xmlType != null) {
hashcode ^= xmlType.hashCode();
}
return hashcode;
}
public String toString() {
return "(" + javaType + "," + xmlType + ")";
}
}
private HashMap qName2Pair; // QName to Pair Mapping
private HashMap class2Pair; // Class Name to Pair Mapping
private HashMap pair2SF; // Pair to Serialization Factory
private HashMap pair2DF; // Pair to Deserialization Factory
private ArrayList namespaces; // Supported namespaces
protected Boolean doAutoTypes = null;
/**
* Construct TypeMapping
*/
public TypeMappingImpl() {
qName2Pair = new HashMap();
class2Pair = new HashMap();
pair2SF = new HashMap();
pair2DF = new HashMap();
namespaces = new ArrayList();
}
private static boolean isArray(Class clazz)
{
return clazz.isArray() || java.util.Collection.class.isAssignableFrom(clazz);
}
/********* JAX-RPC Compliant Method Definitions *****************/
/**
* Gets the list of encoding styles supported by this TypeMapping object.
*
* @return String[] of namespace URIs for the supported encoding
* styles and XML schema namespaces.
*/
public String[] getSupportedEncodings() {
String[] stringArray = new String[namespaces.size()];
return (String[]) namespaces.toArray(stringArray);
}
/**
* Sets the list of encoding styles supported by this TypeMapping object.
* (Not sure why this is useful...this information is automatically updated
* during registration.
*
* @param namespaceURIs String[] of namespace URI's
*/
public void setSupportedEncodings(String[] namespaceURIs) {
namespaces.clear();
for (int i =0; i< namespaceURIs.length; i++) {
if (!namespaces.contains(namespaceURIs[i])) {
namespaces.add(namespaceURIs[i]);
}
}
}
/**
* isRegistered returns true if the [javaType, xmlType]
* pair is registered.
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
* @return true if there is a mapping for the given pair, or
* false if the pair is not specifically registered.
*
* For example if called with (java.lang.String[], soapenc:Array)
* this routine will return false because this pair is
* probably not specifically registered.
* However if getSerializer is called with the same pair,
* the default TypeMapping will use extra logic to find
* a serializer (i.e. array serializer)
*/
public boolean isRegistered(Class javaType, QName xmlType) {
if (javaType == null || xmlType == null) {
// REMOVED_FOR_TCK
// return false;
throw new JAXRPCException(
Messages.getMessage(javaType == null ?
"badJavaType" : "badXmlType"));
}
if (pair2SF.keySet().contains(new Pair(javaType, xmlType))) {
return true;
}
return false;
}
/**
* Registers SerializerFactory and DeserializerFactory for a
* specific type mapping between an XML type and Java type.
*
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
* @param sf - SerializerFactory
* @param dsf - DeserializerFactory
*
* @throws JAXRPCException - If any error during the registration
*/
public void register(Class javaType, QName xmlType,
javax.xml.rpc.encoding.SerializerFactory sf,
javax.xml.rpc.encoding.DeserializerFactory dsf)
throws JAXRPCException {
// At least a serializer or deserializer factory must be specified.
if (sf == null && dsf == null) {
throw new JAXRPCException(Messages.getMessage("badSerFac"));
}
internalRegister(javaType, xmlType, sf, dsf);
}
/**
* Internal version of register(), which allows null factories.
*
* @param javaType
* @param xmlType
* @param sf
* @param dsf
* @throws JAXRPCException
*/
protected void internalRegister(Class javaType, QName xmlType,
javax.xml.rpc.encoding.SerializerFactory sf,
javax.xml.rpc.encoding.DeserializerFactory dsf)
throws JAXRPCException {
// Both javaType and xmlType must be specified.
if (javaType == null || xmlType == null) {
throw new JAXRPCException(
Messages.getMessage(javaType == null ?
"badJavaType" : "badXmlType"));
}
if (log.isDebugEnabled()) {
log.debug("Registering type mapping: javaType=" + javaType + ", xmlType=" + xmlType
+ ", sf=" + sf + ", dsf=" + dsf);
}
//REMOVED_FOR_TCK
//if (sf != null &&
// !(sf instanceof javax.xml.rpc.encoding.SerializerFactory)) {
// throw new JAXRPCException(message text);
//}
//if (dsf != null &&
// !(dsf instanceof javax.xml.rpc.encoding.DeserializerFactory)) {
// throw new JAXRPCException(message text);
//}
Pair pair = new Pair(javaType, xmlType);
// This code used to not put the xmlType and the JavaType
// in the maps if it already existed:
// if ((dsf != null) || (qName2Pair.get(xmlType) == null))
// This goes against the philosphy that "last one registered wins".
// In particular, the mapping for java.lang.Object --> anyType
// was coming out in WSDL generation under the 1999 XML Schema
// namespace, which .NET doesn't understand (and is not great anyway).
qName2Pair.put(xmlType, pair);
class2Pair.put(javaType, pair);
if (sf != null)
pair2SF.put(pair, sf);
if (dsf != null)
pair2DF.put(pair, dsf);
}
/**
* Gets the SerializerFactory registered for the specified pair
* of Java type and XML data type.
*
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
*
* @return Registered SerializerFactory
*
* @throws JAXRPCException - If there is no registered SerializerFactory
* for this pair of Java type and XML data type
* java.lang.IllegalArgumentException -
* If invalid or unsupported XML/Java type is specified
*/
public javax.xml.rpc.encoding.SerializerFactory
getSerializer(Class javaType, QName xmlType)
throws JAXRPCException {
javax.xml.rpc.encoding.SerializerFactory sf = null;
// If the xmlType was not provided, get one
if (xmlType == null) {
xmlType = getTypeQName(javaType, null);
// If we couldn't find one, we're hosed, since getTypeQName()
// already asked all of our delegates.
if (xmlType == null) {
return null;
}
}
// Try to get the serializer associated with this pair
Pair pair = new Pair(javaType, xmlType);
// Now get the serializer with the pair
sf = (javax.xml.rpc.encoding.SerializerFactory) pair2SF.get(pair);
// Need to look into hierarchy of component type.
// ex) java.util.GregorianCalendar[]
// -> java.util.Calendar[]
if (sf == null && javaType.isArray()) {
int dimension = 1;
Class componentType = javaType.getComponentType();
while (componentType.isArray()) {
dimension += 1;
componentType = componentType.getComponentType();
}
int[] dimensions = new int[dimension];
componentType = componentType.getSuperclass();
Class superJavaType = null;
while (componentType != null) {
superJavaType = Array.newInstance(componentType, dimensions).getClass();
pair = new Pair(superJavaType, xmlType);
sf = (javax.xml.rpc.encoding.SerializerFactory) pair2SF.get(pair);
if (sf != null) {
break;
}
componentType = componentType.getSuperclass();
}
}
// check if ArrayOfT(xml)->T[](java) conversion is possible
if (sf == null && javaType.isArray() && xmlType != null) {
Pair pair2 = (Pair) qName2Pair.get(xmlType);
if (pair2 != null
&& pair2.javaType != null
&& !pair2.javaType.isPrimitive()
&& ArrayUtil.isConvertable(pair2.javaType, javaType)) {
sf = (javax.xml.rpc.encoding.SerializerFactory) pair2SF.get(pair2);
}
}
// find serializer with xmlType
if (sf == null && !javaType.isArray()
&& !Constants.isSchemaXSD(xmlType.getNamespaceURI())
&& !Constants.isSOAP_ENC(xmlType.getNamespaceURI())) {
Pair pair2 = (Pair) qName2Pair.get(xmlType);
if (pair2 != null && pair2.javaType != null
&& !pair2.javaType.isArray() // for array
&& (javaType.isAssignableFrom(pair2.javaType) ||
(pair2.javaType.isPrimitive() && javaType == JavaUtils.getWrapperClass(pair2.javaType)))) // for derived type (xsd:restriction)
{
sf = (javax.xml.rpc.encoding.SerializerFactory) pair2SF.get(pair2);
}
}
return sf;
}
public SerializerFactory finalGetSerializer(Class javaType) {
Pair pair;
if (isArray(javaType)) {
pair = (Pair) qName2Pair.get(Constants.SOAP_ARRAY);
} else {
pair = (Pair) class2Pair.get(javaType);
}
if (pair != null) {
return (SerializerFactory)pair2SF.get(pair);
}
return null;
}
/**
* Get the exact XML type QName which will be used when serializing a
* given Class to a given type QName. In other words, if we have:
*
* Class TypeQName
* ----------------------
* Base myNS:Base
* Child myNS:Child
*
* and call getXMLType(Child.class, BASE_QNAME), we should get
* CHILD_QNAME.
*
* @param javaType
* @param xmlType
* @return the type's QName
* @throws JAXRPCException
*/
public QName getXMLType(Class javaType, QName xmlType, boolean encoded)
throws JAXRPCException
{
javax.xml.rpc.encoding.SerializerFactory sf = null;
// If the xmlType was not provided, get one
if (xmlType == null) {
xmlType = getTypeQNameRecursive(javaType);
// If we couldn't find one, we're hosed, since getTypeQName()
// already asked all of our delegates.
if (xmlType == null) {
return null;
}
}
// Try to get the serializer associated with this pair
Pair pair = new Pair(javaType, xmlType);
// Now get the serializer with the pair
sf = (javax.xml.rpc.encoding.SerializerFactory) pair2SF.get(pair);
if (sf != null)
return xmlType;
// If not successful, use the xmlType to get
// another pair. For some xmlTypes (like SOAP_ARRAY)
// all of the possible javaTypes are not registered.
if (isArray(javaType)) {
if (encoded) {
return Constants.SOAP_ARRAY;
} else {
pair = (Pair) qName2Pair.get(xmlType);
}
}
if (pair == null) {
pair = (Pair) class2Pair.get(javaType);
}
if (pair != null) {
xmlType = pair.xmlType;
}
return xmlType;
}
/**
* Gets the DeserializerFactory registered for the specified pair
* of Java type and XML data type.
*
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
*
* @return Registered DeserializerFactory
*
* @throws JAXRPCException - If there is no registered DeserializerFactory
* for this pair of Java type and XML data type
* java.lang.IllegalArgumentException -
* If invalid or unsupported XML/Java type is specified
*/
public javax.xml.rpc.encoding.DeserializerFactory
getDeserializer(Class javaType, QName xmlType, TypeMappingDelegate start)
throws JAXRPCException {
if (javaType == null) {
javaType = start.getClassForQName(xmlType);
// If we don't have a mapping, we're hosed since getClassForQName()
// has already asked all our delegates.
if (javaType == null) {
return null;
}
}
Pair pair = new Pair(javaType, xmlType);
return (javax.xml.rpc.encoding.DeserializerFactory) pair2DF.get(pair);
}
public DeserializerFactory finalGetDeserializer(Class javaType,
QName xmlType,
TypeMappingDelegate start) {
DeserializerFactory df = null;
if (javaType != null && javaType.isArray()) {
Class componentType = javaType.getComponentType();
// HACK ALERT - Don't return the ArrayDeserializer IF
// the xmlType matches the component type of the array
// or if the componentType is the wrappertype of the
// xmlType, because that means we're using maxOccurs
// and/or nillable and we'll want the higher layers to
// get the component type deserializer... (sigh)
if (xmlType != null) {
Class actualClass = start.getClassForQName(xmlType);
if (actualClass == componentType
|| (actualClass != null && (componentType.isAssignableFrom(actualClass)
|| Utils.getWrapperType(actualClass.getName()).equals(componentType.getName())))) {
return null;
}
}
Pair pair = (Pair) qName2Pair.get(Constants.SOAP_ARRAY);
df = (DeserializerFactory) pair2DF.get(pair);
if (df instanceof ArrayDeserializerFactory && javaType.isArray()) {
QName componentXmlType = start.getTypeQName(componentType);
if (componentXmlType != null) {
df = new ArrayDeserializerFactory(componentXmlType);
}
}
}
return df;
}
/**
* Removes the SerializerFactory registered for the specified
* pair of Java type and XML data type.
*
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
*
* @throws JAXRPCException - If there is error in
* removing the registered SerializerFactory
*/
public void removeSerializer(Class javaType, QName xmlType)
throws JAXRPCException {
if (javaType == null || xmlType == null) {
throw new JAXRPCException(
Messages.getMessage(javaType == null ?
"badJavaType" : "badXmlType"));
}
Pair pair = new Pair(javaType, xmlType);
pair2SF.remove(pair);
}
/**
* Removes the DeserializerFactory registered for the specified
* pair of Java type and XML data type.
*
* @param javaType - Class of the Java type
* @param xmlType - Qualified name of the XML data type
*
* @throws JAXRPCException - If there is error in
* removing the registered DeserializerFactory
*/
public void removeDeserializer(Class javaType, QName xmlType)
throws JAXRPCException {
if (javaType == null || xmlType == null) {
throw new JAXRPCException(
Messages.getMessage(javaType == null ?
"badJavaType" : "badXmlType"));
}
Pair pair = new Pair(javaType, xmlType);
pair2DF.remove(pair);
}
/********* End JAX-RPC Compliant Method Definitions *****************/
/**
* Gets the QName for the type mapped to Class.
* @param javaType class or type
* @return xmlType qname or null
*/
public QName getTypeQNameRecursive(Class javaType) {
QName ret = null;
while (javaType != null) {
ret = getTypeQName(javaType, null);
if (ret != null)
return ret;
// Walk my interfaces...
Class [] interfaces = javaType.getInterfaces();
if (interfaces != null) {
for (int i = 0; i < interfaces.length; i++) {
Class iface = interfaces[i];
ret = getTypeQName(iface, null);
if (ret != null)
return ret;
}
}
javaType = javaType.getSuperclass();
}
return null;
}
/**
* Get the QName for this Java class, but only return a specific
* mapping if there is one. In other words, don't do special array
* processing, etc.
*
* @param javaType
* @return
*/
public QName getTypeQNameExact(Class javaType, TypeMappingDelegate next) {
if (log.isDebugEnabled()) {
log.debug("getTypeQNameExact for javaType=" + javaType);
}
if (javaType == null) {
log.debug("javaType == null; getTypeQNameExact returning null");
return null;
}
QName xmlType = null;
Pair pair = (Pair) class2Pair.get(javaType);
if (log.isDebugEnabled()) {
log.debug("class2Pair gives: " + pair);
}
if (isDotNetSoapEncFixNeeded() && pair != null ) {
// Hack alert!
// If we are in .NET bug compensation mode, skip over any
// SOAP Encoded types we my find and prefer XML Schema types
xmlType = pair.xmlType;
if (Constants.isSOAP_ENC(xmlType.getNamespaceURI()) &&
!xmlType.getLocalPart().equals("Array")) {
pair = null;
}
}
if (pair == null && next != null) {
// Keep checking up the stack...
xmlType = next.delegate.getTypeQNameExact(javaType,
next.next);
}
if (pair != null) {
xmlType = pair.xmlType;
}
if (log.isDebugEnabled()) {
log.debug("getTypeQNameExact returning " + xmlType);
}
return xmlType;
}
/**
* isDotNetSoapEncFixNeeded - Do we need to compensate for the dotnet bug.
* check the service specific flag before using the global flag
* @return
*/
private boolean isDotNetSoapEncFixNeeded() {
MessageContext msgContext = MessageContext.getCurrentContext();
if (msgContext != null) {
SOAPService service = msgContext.getService();
if (service != null) {
String dotNetSoapEncFix = (String) service.getOption(AxisEngine.PROP_DOTNET_SOAPENC_FIX);
if (dotNetSoapEncFix != null) {
return JavaUtils.isTrue(dotNetSoapEncFix);
}
}
}
return TypeMappingImpl.dotnet_soapenc_bugfix;
}
public QName getTypeQName(Class javaType, TypeMappingDelegate next) {
QName xmlType = getTypeQNameExact(javaType, next);
/* If auto-typing is on and the array has the default SOAP_ARRAY QName,
* then generate a namespace for this array intelligently. Also
* register it's javaType and xmlType. List classes and derivitives
* can't be used because they should be serialized as an anyType array.
*/
if ( shouldDoAutoTypes() &&
javaType != List.class &&
!List.class.isAssignableFrom(javaType) &&
xmlType != null &&
xmlType.equals(Constants.SOAP_ARRAY) )
{
xmlType = new QName(
Namespaces.makeNamespace( javaType.getName() ),
Types.getLocalNameFromFullName( javaType.getName() ) );
internalRegister( javaType,
xmlType,
new ArraySerializerFactory(),
new ArrayDeserializerFactory() );
}
// Can only detect arrays via code
if (xmlType == null && isArray(javaType)) {
// get the registered array if any
Pair pair = (Pair) class2Pair.get(Object[].class);
// TODO: it always returns the last registered one,
// so that's why the soap 1.2 typemappings have to
// move to an other registry to differentiate them
if (pair != null) {
xmlType = pair.xmlType;
} else {
xmlType = Constants.SOAP_ARRAY;
}
}
/* If the class isn't an array or List and auto-typing is turned on,
* register the class and it's type as beans.
*/
if (xmlType == null && shouldDoAutoTypes())
{
xmlType = new QName(
Namespaces.makeNamespace( javaType.getName() ),
Types.getLocalNameFromFullName( javaType.getName() ) );
/* If doAutoTypes is set, register a new type mapping for the
* java class with the above QName. This way, when getSerializer()
* and getDeserializer() are called, this QName is returned and
* these methods do not need to worry about creating a serializer.
*/
internalRegister( javaType,
xmlType,
new BeanSerializerFactory(javaType, xmlType),
new BeanDeserializerFactory(javaType, xmlType) );
}
//log.debug("getTypeQName xmlType =" + xmlType);
return xmlType;
}
public Class getClassForQName(QName xmlType, Class javaType,
TypeMappingDelegate next) {
if (xmlType == null) {
return null;
}
//log.debug("getClassForQName xmlType =" + xmlType);
if (javaType != null) {
// Looking for an exact match first
Pair pair = new Pair(javaType, xmlType);
if (pair2DF.get(pair) == null) {
if (next != null) {
javaType = next.getClassForQName(xmlType, javaType);
}
}
}
if (javaType == null) {
//look for it in our map
Pair pair = (Pair) qName2Pair.get(xmlType);
if (pair == null && next != null) {
//on no match, delegate
javaType = next.getClassForQName(xmlType);
} else if (pair != null) {
javaType = pair.javaType;
}
}
//log.debug("getClassForQName javaType =" + javaType);
if(javaType == null && shouldDoAutoTypes()) {
String pkg = Namespaces.getPackage(xmlType.getNamespaceURI());
if (pkg != null) {
String className = xmlType.getLocalPart();
if (pkg.length() > 0) {
className = pkg + "." + className;
}
try {
javaType = ClassUtils.forName(className);
internalRegister(javaType,
xmlType,
new BeanSerializerFactory(javaType, xmlType),
new BeanDeserializerFactory(javaType, xmlType));
} catch (ClassNotFoundException e) {
}
}
}
return javaType;
}
public void setDoAutoTypes(boolean doAutoTypes) {
this.doAutoTypes = doAutoTypes ? Boolean.TRUE : Boolean.FALSE;
}
public boolean shouldDoAutoTypes() {
if(doAutoTypes != null) {
return doAutoTypes.booleanValue();
}
MessageContext msgContext = MessageContext.getCurrentContext();
if(msgContext != null) {
if (msgContext.isPropertyTrue("axis.doAutoTypes") ||
(msgContext.getAxisEngine() != null && JavaUtils.isTrue(msgContext.getAxisEngine().getOption("axis.doAutoTypes")))) {
doAutoTypes = Boolean.TRUE;
}
}
if(doAutoTypes == null){
doAutoTypes = AxisProperties.getProperty("axis.doAutoTypes",
"false")
.equals("true") ?
Boolean.TRUE : Boolean.FALSE;
}
return doAutoTypes.booleanValue();
}
/**
* Returns an array of all the classes contained within this mapping
*/
public Class [] getAllClasses(TypeMappingDelegate next)
{
java.util.HashSet temp = new java.util.HashSet();
if (next != null)
{
temp.addAll(java.util.Arrays.asList(next.getAllClasses()));
}
temp.addAll(class2Pair.keySet());
return (Class[])temp.toArray(new Class[temp.size()]);
}
} | 7,466 |
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/encoding/DeserializerImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.Part;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.message.EnvelopeHandler;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SAX2EventRecorder;
import org.apache.axis.message.SAXOutputter;
import org.apache.axis.message.SOAPHandler;
import org.apache.axis.utils.Messages;
import org.apache.axis.soap.SOAPConstants;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Vector;
/** The Deserializer base class.
*
* @author Glen Daniels (gdaniels@allaire.com)
* Re-architected for JAX-RPC Compliance by
* @author Rich Scheuerle (sche@us.ibm.com)
*/
public class DeserializerImpl extends SOAPHandler
implements javax.xml.rpc.encoding.Deserializer, Deserializer, Callback
{
protected static Log log =
LogFactory.getLog(DeserializerImpl.class.getName());
protected Object value = null;
// invariant member variable to track low-level logging requirements
// we cache this once per instance lifecycle to avoid repeated lookups
// in heavily used code.
private final boolean debugEnabled = log.isDebugEnabled();
// isEnded is set when the endElement is called
protected boolean isEnded = false;
protected Vector targets = null;
protected QName defaultType = null;
protected boolean componentsReadyFlag = false;
/**
* A set of sub-deserializers whose values must complete before our
* value is complete.
*/
private HashSet activeDeserializers = new HashSet();
protected boolean isHref = false;
protected boolean isNil = false; // xsd:nil attribute is set to true
protected String id = null; // Set to the id of the element
public DeserializerImpl() {
}
/**
* JAX-RPC compliant method which returns mechanism type.
*/
public String getMechanismType() {
return Constants.AXIS_SAX;
}
/**
* Get the deserialized value.
* @return Object representing deserialized value or null
*/
public Object getValue()
{
return value;
}
/**
* Set the deserialized value.
* @param value Object representing deserialized value
*/
public void setValue(Object value)
{
this.value = value;
}
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method gets the specific component via the hint.
* The default implementation returns null.
* @return Object representing deserialized value or null
*/
public Object getValue(Object hint)
{
return null;
}
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method sets the specific component via the hint.
* The default implementation does nothing.
* @param hint Object representing deserialized value or null
*/
public void setChildValue(Object value, Object hint) throws SAXException
{
}
public void setValue(Object value, Object hint) throws SAXException {
if (hint instanceof Deserializer) {
// This one's done
activeDeserializers.remove(hint);
// If we're past the end of our XML, and this is the last one,
// our value has been assembled completely.
if (componentsReady()) {
// Got everything we need, call valueComplete()
valueComplete();
}
}
}
/**
* In some circumstances an element may not have
* a type attribute, but a default type qname is known from
* information in the container. For example,
* an element of an array may not have a type= attribute,
* so the default qname is the component type of the array.
* This method is used to communicate the default type information
* to the deserializer.
*/
public void setDefaultType(QName qName) {
defaultType = qName;
}
public QName getDefaultType() {
return defaultType;
}
/**
* For deserializers of non-primitives, the value may not be
* known until later (due to multi-referencing). In such
* cases the deserializer registers Target object(s). When
* the value is known, the set(value) will be invoked for
* each Target registered with the Deserializer. The Target
* object abstracts the function of setting a target with a
* value. See the Target interface for more info.
* @param target
*/
public void registerValueTarget(Target target)
{
if (targets == null) {
targets = new Vector();
}
targets.addElement(target);
}
/**
* Get the Value Targets of the Deserializer.
* @return Vector of Target objects or null
*/
public Vector getValueTargets() {
return targets;
}
/**
* Remove the Value Targets of the Deserializer.
*/
public void removeValueTargets() {
if (targets != null) {
targets = null;
}
}
/**
* Move someone else's targets to our own (see DeserializationContext)
*
* The DeserializationContext only allows one Deserializer to
* wait for a unknown multi-ref'ed value. So to ensure
* that all of the targets are updated, this method is invoked
* to copy the Target objects to the waiting Deserializer.
* @param other is the Deserializer to copy targets from.
*/
public void moveValueTargets(Deserializer other)
{
if ((other == null) || (other.getValueTargets() == null)) {
return;
}
if (targets == null) {
targets = new Vector();
}
targets.addAll(other.getValueTargets());
other.removeValueTargets();
}
/**
* Some deserializers (ArrayDeserializer) require
* all of the component values to be known before the
* value is complete.
* (For the ArrayDeserializer this is important because
* the elements are stored in an ArrayList, and all values
* must be known before the ArrayList is converted into the
* expected array.
*
* This routine is used to indicate when the components are ready.
* The default (true) is useful for most Deserializers.
*/
public boolean componentsReady() {
return (componentsReadyFlag ||
(!isHref && isEnded && activeDeserializers.isEmpty()));
}
/**
* The valueComplete() method is invoked when the
* end tag of the element is read. This results
* in the setting of all registered Targets (see
* registerValueTarget).
* Note that the valueComplete() only processes
* the Targets if componentReady() returns true.
* So if you override componentReady(), then your
* specific Deserializer will need to call valueComplete()
* when your components are ready (See ArrayDeserializer)
*/
public void valueComplete() throws SAXException
{
if (componentsReady()) {
if (targets != null) {
for (int i = 0; i < targets.size(); i++) {
Target target = (Target) targets.get(i);
target.set(value);
if (debugEnabled) {
log.debug(Messages.getMessage("setValueInTarget00",
"" + value, "" + target));
}
}
// Don't need targets any more, so clear them
removeValueTargets();
}
}
}
public void addChildDeserializer(Deserializer dSer) {
// Keep track of our active deserializers. This enables us to figure
// out whether or not we're really done in the case where we get to
// our end tag, but still have open hrefs for members.
if (activeDeserializers != null) {
activeDeserializers.add(dSer);
}
// In concert with the above, we make sure each field deserializer
// lets us know when it's done so we can take it off our list.
dSer.registerValueTarget(new CallbackTarget(this, dSer));
}
/**
* Subclasses may override these
*/
/**
* This method is invoked when an element start tag is encountered.
* DeserializerImpl provides default behavior, which involves the following:
* - directly handling the deserialization of a nill value
* - handling the registration of the id value.
* - handling the registration of a fixup if this element is an href.
* - calling onStartElement to do the actual deserialization if not nill or href cases.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the prefix of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*
* Normally a specific Deserializer (FooDeserializer) should extend DeserializerImpl.
* Here is the flow that will occur in such cases:
* 1) DeserializerImpl.startElement(...) will be called and do the id/href/nill stuff.
* 2) If real deserialization needs to take place DeserializerImpl.onStartElement will be
* invoked, which will attempt to install the specific Deserializer (FooDeserializer)
* 3) The FooDeserializer.startElement(...) will be called to do the Foo specific stuff.
* This results in a call to FooDeserializer.onStartElement(...) if startElement was
* not overridden.
* 4) The onChildElement(...) method is called for each child element. Nothing occurs
* if not overridden. The FooDeserializer.onStartChild(...) method should return
* the deserializer for the child element.
* 5) When the end tag is reached, the endElement(..) method is invoked. The default
* behavior is to handle hrefs/ids, call onEndElement and then call the Deserializer
* valueComplete method.
*
* So the methods that you potentially want to override are:
* onStartElement, onStartChild, componentsReady, setValue(object, hint)
* You probably should not override startElement or endElement.
* If you need specific behaviour at the end of the element consider overriding
* onEndElement.
*
* See the pre-existing Deserializers for more information.
*/
public void startElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
super.startElement(namespace, localName, prefix, attributes, context);
// If the nil attribute is present and true, set the value to null
// and return since there is nothing to deserialize.
if (context.isNil(attributes)) {
value = null;
isNil = true;
return;
}
SOAPConstants soapConstants = context.getSOAPConstants();
// If this element has an id, then associate the value with the id.
// (Prior to this association, the MessageElement of the element is
// associated with the id. Failure to replace the MessageElement at this
// point will cause an infinite loop during deserialization if the
// current element contains child elements that cause an href back to this id.)
// Also note that that endElement() method is responsible for the final
// association of this id with the completed value.
id = attributes.getValue("id");
if (id != null) {
context.addObjectById(id, value);
if (debugEnabled) {
log.debug(Messages.getMessage("deserInitPutValueDebug00", "" + value, id));
}
context.registerFixup("#" + id, this);
}
String href = attributes.getValue(soapConstants.getAttrHref());
if (href != null) {
isHref = true;
Object ref = context.getObjectByRef(href);
if (debugEnabled) {
log.debug(Messages.getMessage(
"gotForID00",
new String[] {"" + ref, href, (ref == null ? "*null*" : ref.getClass().toString())}));
}
if (ref == null) {
// Nothing yet... register for later interest.
context.registerFixup(href, this);
return;
}
if (ref instanceof MessageElement) {
context.replaceElementHandler(new EnvelopeHandler(this));
SAX2EventRecorder r = context.getRecorder();
context.setRecorder(null);
((MessageElement)ref).publishToHandler(context);
context.setRecorder(r);
} else {
if( !href.startsWith("#") && defaultType != null && ref instanceof Part ){
//For attachments this is the end of the road-- invoke deserializer
Deserializer dser = context.getDeserializerForType(defaultType );
if(null != dser){
dser.startElement(namespace, localName,
prefix, attributes,
context);
ref = dser.getValue();
}
}
// If the ref is not a MessageElement, then it must be an
// element that has already been deserialized. Use it directly.
value = ref;
componentsReadyFlag = true;
valueComplete();
}
} else {
isHref = false;
onStartElement(namespace, localName, prefix, attributes,
context);
}
}
/**
* This method is invoked after startElement when the element requires
* deserialization (i.e. the element is not an href and the value is not nil.)
* DeserializerImpl provides default behavior, which simply
* involves obtaining a correct Deserializer and plugging its handler.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the prefix of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*/
public void onStartElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
// If I'm the base class, try replacing myself with an
// appropriate deserializer gleaned from type info.
if (this.getClass().equals(DeserializerImpl.class)) {
QName type = context.getTypeFromAttributes(namespace,
localName,
attributes);
// If no type is specified, use the defaultType if available.
// xsd:string is used if no type is provided.
if (type == null) {
type = defaultType;
if (type == null) {
type = Constants.XSD_STRING;
}
}
if (debugEnabled) {
log.debug(Messages.getMessage("gotType00", "Deser", "" + type));
}
// We know we're deserializing, but we don't have
// a specific deserializer. So create one using the
// attribute type qname.
if (type != null) {
Deserializer dser = context.getDeserializerForType(type);
if (dser == null) {
dser = context.getDeserializerForClass(null);
}
if (dser != null) {
// Move the value targets to the new deserializer
dser.moveValueTargets(this);
context.replaceElementHandler((SOAPHandler) dser);
// And don't forget to give it the start event...
boolean isRef = context.isProcessingRef();
context.setProcessingRef(true);
dser.startElement(namespace, localName, prefix,
attributes, context);
context.setProcessingRef(isRef);
} else {
throw new SAXException(
Messages.getMessage("noDeser00", "" + type));
}
}
}
}
/**
* onStartChild is called on each child element.
* The default behavior supplied by DeserializationImpl is to do nothing.
* A specific deserializer may perform other tasks. For example a
* BeanDeserializer will construct a deserializer for the indicated
* property and return it.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param prefix is the prefix used on the name of the child element
* @param attributes are the attributes of the child element
* @param context is the deserialization context.
* @return is a Deserializer to use to deserialize a child (must be
* a derived class of SOAPHandler) or null if no deserialization should
* be performed.
*/
public SOAPHandler onStartChild(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
return null;
}
/**
* endElement is called when the end element tag is reached.
* It handles href/id information for multi-ref processing
* and invokes the valueComplete() method of the deserializer
* which sets the targets with the deserialized value.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public final void endElement(String namespace, String localName,
DeserializationContext context)
throws SAXException
{
super.endElement(namespace, localName, context);
isEnded = true;
if (!isHref) {
onEndElement(namespace, localName, context);
}
// Time to call valueComplete to copy the value to
// the targets. First a call is made to componentsReady
// to ensure that all components are ready.
if (componentsReady()) {
valueComplete();
}
// If this element has an id, then associate the value with the id.
// Subsequent hrefs to the id will obtain the value directly.
// This is necessary for proper multi-reference deserialization.
if (id != null) {
context.addObjectById(id, value);
if (debugEnabled) {
log.debug(Messages.getMessage("deserPutValueDebug00", "" + value, id));
}
}
}
/**
* onEndElement is called by endElement. It is not called
* if the element has an href.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public void onEndElement(String namespace, String localName,
DeserializationContext context)
throws SAXException
{
// If we only have SAX events, but someone really wanted a
// value, try sending them the contents of this element
// as a String...
// ??? Is this the right thing to do here?
if (this.getClass().equals(DeserializerImpl.class) &&
targets != null &&
!targets.isEmpty()) {
StringWriter writer = new StringWriter();
SerializationContext serContext =
new SerializationContext(writer,
context.getMessageContext());
serContext.setSendDecl(false);
SAXOutputter so = null;
so = new SAXOutputter(serContext);
context.getCurElement().publishContents(so);
if (!isNil) {
value = writer.getBuffer().toString();
}
}
}
}
| 7,467 |
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/encoding/DeserializerFactory.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.encoding;
/**
* This interface describes the AXIS DeserializerFactory.
*
* An Axis compliant Serializer Factory must provide one or more
* of the following methods:
*
* public static create(Class javaType, QName xmlType)
* public <constructor>(Class javaType, QName xmlType)
* public <constructor>()
*
* The deployment code will attempt to invoke these methods in the above order.
* The xmlType, javaType arguments are filled in with the values supplied during the
* deployment registration of the factory.
*/
public interface DeserializerFactory extends javax.xml.rpc.encoding.DeserializerFactory {
}
| 7,468 |
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/encoding/Serializer.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.encoding;
import org.apache.axis.wsdl.fromJava.Types;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import javax.xml.namespace.QName;
import java.io.IOException;
/**
* This interface describes the AXIS Serializer.
* An Axis compliant Serializer must provide one or more
* of the following methods:
*
* public <constructor>(Class javaType, QName xmlType)
* public <constructor>()
*
* This will allow for construction of generic factories that introspect the class
* to determine how to construct a deserializer.
* The xmlType, javaType arguments are filled in with the values known by the factory.
*/
public interface Serializer extends javax.xml.rpc.encoding.Serializer {
/**
* Serialize an element named name, with the indicated attributes
* and value.
* @param name is the element name
* @param attributes are the attributes...serialize is free to add more.
* @param value is the value
* @param context is the SerializationContext
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException;
/**
* Return XML schema for the specified type, suitable for insertion into
* the <types> element of a WSDL document, or underneath an
* <element> or <attribute> declaration.
*
* @param javaType the Java Class we're writing out schema for
* @param types the Java2WSDL Types object which holds the context
* for the WSDL being generated.
* @return a type element containing a schema simpleType/complexType
* @see org.apache.axis.wsdl.fromJava.Types
*/
public Element writeSchema(Class javaType, Types types) throws Exception;
}
| 7,469 |
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/encoding/Target.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.encoding;
import org.xml.sax.SAXException;
/**
* A deserializer constructs a value from the xml passed over the wire and
* sets a target. The value is set on the target in a number of ways:
* setting a field, calling a method, setting an indexed property.
* The Target interface hides the complexity. The set method is simply
* invoked with the value. A class that implements the Target interface
* needs to supply enough information in the constructor to properly do the
* set (for example see MethodTarget)
*/
public interface Target
{
public void set(Object value) throws SAXException;
}
| 7,470 |
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/encoding/FieldTarget.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.encoding;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import java.lang.reflect.Field;
// Target is a field. The set method places the value in the field.
public class FieldTarget implements Target
{
protected static Log log =
LogFactory.getLog(FieldTarget.class.getName());
private Object targetObject;
private Field targetField;
public FieldTarget(Object targetObject, Field targetField)
{
this.targetObject = targetObject;
this.targetField = targetField;
}
public FieldTarget(Object targetObject, String fieldName)
throws NoSuchFieldException
{
Class cls = targetObject.getClass();
targetField = cls.getField(fieldName);
this.targetObject = targetObject;
}
public void set(Object value) throws SAXException {
try {
targetField.set(targetObject, value);
} catch (IllegalAccessException accEx) {
log.error(Messages.getMessage("illegalAccessException00"),
accEx);
throw new SAXException(accEx);
} catch (IllegalArgumentException argEx) {
log.error(Messages.getMessage("illegalArgumentException00"),
argEx);
throw new SAXException(argEx);
}
}
}
| 7,471 |
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/encoding/TypeMappingRegistryImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.utils.Messages;
import java.util.HashMap;
/**
* The TypeMappingRegistry keeps track of the individual TypeMappings.
* <p>
* The TypeMappingRegistry for axis contains a default type mapping
* that is set for either SOAP 1.1 or SOAP 1.2
* The default type mapping is a singleton used for the entire
* runtime and should not have anything new registered in it.
* <p>
* Instead the new TypeMappings for the deploy and service are
* made in a separate TypeMapping which is identified by
* the soap encoding. These new TypeMappings delegate back to
* the default type mapping when information is not found.
* <p>
* So logically we have:
* <pre>
* TMR
* | |
* | +---------------> DefaultTM
* | ^
* | |
* +----> TM --delegate---+
* </pre>
*
* But in the implementation, the TMR references
* "delegate" TypeMappings (TM') which then reference the actual TM's
* <p>
* So the picture is really:
* <pre>
* TMR
* | |
* | +-----------TM'------> DefaultTM
* | ^
* | |
* +-TM'-> TM ----+
* </pre>
*
* This extra indirection is necessary because the user may want to
* change the default type mapping. In such cases, the TMR
* just needs to adjust the TM' for the DefaultTM, and all of the
* other TMs will properly delegate to the new one. Here's the picture:
* <pre>
* TMR
* | |
* | +-----------TM'--+ DefaultTM
* | ^ |
* | | +---> New User Defined Default TM
* +-TM'-> TM ----+
* </pre>
*
* The other reason that it is necessary is when a deploy
* has a TMR, and then TMR's are defined for the individual services
* in such cases the delegate() method is invoked on the service
* to delegate to the deploy TMR
* <pre>
* Deploy TMR
* | |
* | +-----------TM'------> DefaultTM
* | ^
* | |
* +-TM'-> TM ----+
*
* Service TMR
* | |
* | +-----------TM'------> DefaultTM
* | ^
* | |
* +-TM'-> TM ----+
*
* ServiceTMR.delegate(DeployTMR)
*
* Deploy TMR
* | |
* | +------------TM'------> DefaultTM
* | ^ ^
* | | |
* +-TM'-> TM ----+ |
* ^ |
* +-------+ |
* | |
* | Service TMR |
* | | | |
* | | +----------TM'-+
* | |
* | |
* | +-TM'-> TM +
* | |
* +----------------+
* </pre>
*
* So now the service uses the DefaultTM of the Deploy TMR, and
* the Service TM properly delegates to the deploy's TM. And
* if either the deploy defaultTM or TMs change, the links are not broken.
*
* @author James Snell (jasnell@us.ibm.com)
* @author Sam Ruby (rubys@us.ibm.com)
* Re-written for JAX-RPC Compliance by
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class TypeMappingRegistryImpl implements TypeMappingRegistry {
private HashMap mapTM; // Type Mappings keyed with Namespace URI
private TypeMappingDelegate defaultDelTM; // Delegate to default Type Mapping
private boolean isDelegated = false;
/**
* Construct TypeMappingRegistry
* @param tm
*/
public TypeMappingRegistryImpl(TypeMappingImpl tm) {
mapTM = new HashMap();
defaultDelTM = new TypeMappingDelegate(tm);
// TypeMappingDelegate del = new TypeMappingDelegate(new DefaultSOAPEncodingTypeMappingImpl());
// register(Constants.URI_SOAP11_ENC, del);
}
/**
* Construct TypeMappingRegistry
*/
public TypeMappingRegistryImpl() {
this(true);
}
public TypeMappingRegistryImpl(boolean registerDefaults) {
mapTM = new HashMap();
if (registerDefaults) {
defaultDelTM = DefaultTypeMappingImpl.getSingletonDelegate();
TypeMappingDelegate del = new TypeMappingDelegate(new DefaultSOAPEncodingTypeMappingImpl());
register(Constants.URI_SOAP11_ENC, del);
} else {
defaultDelTM = new TypeMappingDelegate(TypeMappingDelegate.placeholder);
}
}
/**
* delegate
*
* Changes the contained type mappings to delegate to
* their corresponding types in the secondary TMR.
*/
public void delegate(TypeMappingRegistry secondaryTMR) {
if (isDelegated || secondaryTMR == null || secondaryTMR == this) {
return;
}
isDelegated = true;
String[] keys = secondaryTMR.getRegisteredEncodingStyleURIs();
TypeMappingDelegate otherDefault =
((TypeMappingRegistryImpl)secondaryTMR).defaultDelTM;
if (keys != null) {
for (int i=0; i < keys.length; i++) {
try {
String nsURI = keys[i];
TypeMappingDelegate tm = (TypeMappingDelegate) mapTM.get(nsURI);
if (tm == null) {
tm = (TypeMappingDelegate)createTypeMapping();
tm.setSupportedEncodings(new String[] { nsURI });
register(nsURI, tm);
}
if (tm != null) {
// Get the secondaryTMR's TM'
TypeMappingDelegate del = (TypeMappingDelegate)
((TypeMappingRegistryImpl)secondaryTMR).mapTM.get(nsURI);
while (del.next != null) {
TypeMappingDelegate nu = new TypeMappingDelegate(del.delegate);
tm.setNext(nu);
if (del.next == otherDefault) {
nu.setNext(defaultDelTM);
break;
}
del = del.next;
tm = nu;
}
}
} catch (Exception e) {
}
}
}
// Change our defaultDelTM to delegate to the one in
// the secondaryTMR
if (defaultDelTM.delegate != TypeMappingDelegate.placeholder) {
defaultDelTM.setNext(otherDefault);
} else {
defaultDelTM.delegate = otherDefault.delegate;
}
}
/********* JAX-RPC Compliant Method Definitions *****************/
/**
* The method register adds a TypeMapping instance for a specific
* namespace
*
* @param namespaceURI
* @param mapping - TypeMapping for specific namespaces
*
* @return Previous TypeMapping associated with the specified namespaceURI,
* or null if there was no TypeMapping associated with the specified namespaceURI
*
*/
public javax.xml.rpc.encoding.TypeMapping register(String namespaceURI,
javax.xml.rpc.encoding.TypeMapping mapping) {
// namespaceURI = "";
if (mapping == null ||
!(mapping instanceof TypeMappingDelegate)) {
throw new IllegalArgumentException(
Messages.getMessage("badTypeMapping"));
}
if (namespaceURI == null) {
throw new java.lang.IllegalArgumentException(
Messages.getMessage("nullNamespaceURI"));
}
TypeMappingDelegate del = (TypeMappingDelegate)mapping;
TypeMappingDelegate old = (TypeMappingDelegate)mapTM.get(namespaceURI);
if (old == null) {
del.setNext(defaultDelTM);
} else {
del.setNext(old);
}
mapTM.put(namespaceURI, del);
return old; // Needs works
}
/**
* The method register adds a default TypeMapping instance. If a specific
* TypeMapping is not found, the default TypeMapping is used.
*
* @param mapping - TypeMapping for specific type namespaces
*
* java.lang.IllegalArgumentException -
* if an invalid type mapping is specified or the delegate is already set
*/
public void registerDefault(javax.xml.rpc.encoding.TypeMapping mapping) {
if (mapping == null ||
!(mapping instanceof TypeMappingDelegate)) {
throw new IllegalArgumentException(
Messages.getMessage("badTypeMapping"));
}
/* Don't allow this call after the delegate() method since
* the TMR's TypeMappings will be using the default type mapping
* of the secondary TMR.
*/
if (defaultDelTM.getNext() != null) {
throw new IllegalArgumentException(
Messages.getMessage("defaultTypeMappingSet"));
}
defaultDelTM = (TypeMappingDelegate)mapping;
}
/**
* Set up the default type mapping (and the SOAP encoding type mappings)
* as per the passed "version" option.
*
* @param version
*/
public void doRegisterFromVersion(String version) {
if (version == null || version.equals("1.0") || version.equals("1.2")) {
TypeMappingImpl.dotnet_soapenc_bugfix = false;
// Do nothing, just register SOAPENC mapping
} else if (version.equals("1.1")) {
TypeMappingImpl.dotnet_soapenc_bugfix = true;
// Do nothing, no SOAPENC mapping
return;
} else if (version.equals("1.3")) {
// Reset the default TM to the JAXRPC version, then register SOAPENC
defaultDelTM = new TypeMappingDelegate(
DefaultJAXRPC11TypeMappingImpl.getSingleton());
} else {
throw new RuntimeException(
Messages.getMessage("j2wBadTypeMapping00"));
}
registerSOAPENCDefault(
new TypeMappingDelegate(DefaultSOAPEncodingTypeMappingImpl.
getSingleton()));
}
/**
* Force registration of the given mapping as the SOAPENC default mapping
* @param mapping
*/
private void registerSOAPENCDefault(TypeMappingDelegate mapping) {
// This get a bit ugly as we do not want to just overwrite
// an existing type mapping for SOAP encodings. This happens
// when {client,server}-config.wsdd defines a type mapping for
// instance.
if (!mapTM.containsKey(Constants.URI_SOAP11_ENC)) {
mapTM.put(Constants.URI_SOAP11_ENC, mapping);
} else {
// We have to make sure the default type mapping is
// at the end of the chain.
// This is important if the default is switched to
// the JAX_RPC 1.1 default type mapping!
TypeMappingDelegate del =
(TypeMappingDelegate) mapTM.get(Constants.URI_SOAP11_ENC);
while (del.getNext() != null && ! (del.delegate instanceof DefaultTypeMappingImpl)) {
del = del.getNext();
}
del.setNext(defaultDelTM);
}
if (!mapTM.containsKey(Constants.URI_SOAP12_ENC)) {
mapTM.put(Constants.URI_SOAP12_ENC, mapping);
} else {
// We have to make sure the default type mapping is
// at the end of the chain.
// This is important if the default is switched to
// the JAX_RPC 1.1 default type mapping!
TypeMappingDelegate del =
(TypeMappingDelegate) mapTM.get(Constants.URI_SOAP12_ENC);
while (del.getNext() != null && ! (del.delegate instanceof DefaultTypeMappingImpl)) {
del = del.getNext();
}
del.setNext(defaultDelTM);
}
// Just do this unconditionally in case we used mapping.
// This is important if the default is switched to
// the JAX_RPC 1.1 default type mapping!
mapping.setNext(defaultDelTM);
}
/**
* Gets the TypeMapping for the namespace. If not found, the default
* TypeMapping is returned.
*
* @param namespaceURI - The namespace URI of a Web Service
* @return The registered TypeMapping
* (which may be the default TypeMapping) or null.
*/
public javax.xml.rpc.encoding.TypeMapping
getTypeMapping(String namespaceURI) {
// namespaceURI = "";
TypeMapping del = (TypeMappingDelegate) mapTM.get(namespaceURI);
if (del == null) {
del = (TypeMapping)getDefaultTypeMapping();
}
return del;
}
/**
* Obtain a type mapping for the given encodingStyle. If no specific
* mapping exists for this encodingStyle, we will create and register
* one before returning it.
*
* @param encodingStyle
* @return a registered TypeMapping for the given encodingStyle
*/
public TypeMapping getOrMakeTypeMapping(String encodingStyle) {
TypeMappingDelegate del = (TypeMappingDelegate) mapTM.get(encodingStyle);
if (del == null || del.delegate instanceof DefaultTypeMappingImpl) {
del = (TypeMappingDelegate)createTypeMapping();
del.setSupportedEncodings(new String[] {encodingStyle});
register(encodingStyle, del);
}
return del;
}
/**
* Unregisters the TypeMapping for the namespace.
*
* @param namespaceURI - The namespace URI
* @return The registered TypeMapping .
*/
public javax.xml.rpc.encoding.TypeMapping
unregisterTypeMapping(String namespaceURI) {
return (TypeMappingDelegate)mapTM.remove(namespaceURI);
}
/**
* Removes the TypeMapping for the namespace.
*
* @param mapping The type mapping to remove
* @return true if found and removed
*/
public boolean removeTypeMapping(
javax.xml.rpc.encoding.TypeMapping mapping) {
String[] ns = getRegisteredEncodingStyleURIs();
boolean rc = false;
for (int i=0; i < ns.length; i++) {
if (getTypeMapping(ns[i]) == mapping) {
rc = true;
unregisterTypeMapping(ns[i]);
}
}
return rc;
}
/**
* Creates a new empty TypeMapping object for the specified
* encoding style or XML schema namespace.
*
* @return An empty generic TypeMapping object
*/
public javax.xml.rpc.encoding.TypeMapping createTypeMapping() {
TypeMappingImpl impl = new TypeMappingImpl();
TypeMappingDelegate del = new TypeMappingDelegate(impl);
del.setNext(defaultDelTM);
return del;
}
/**
* Gets a list of namespace URIs registered with this TypeMappingRegistry.
*
* @return String[] containing names of all registered namespace URIs
*/
public String[] getRegisteredEncodingStyleURIs() {
java.util.Set s = mapTM.keySet();
if (s != null) {
String[] rc = new String[s.size()];
int i = 0;
java.util.Iterator it = s.iterator();
while(it.hasNext()) {
rc[i++] = (String) it.next();
}
return rc;
}
return null;
}
/**
* Removes all TypeMappings and namespaceURIs from this TypeMappingRegistry.
*/
public void clear() {
mapTM.clear();
}
/**
* Return the default TypeMapping
* @return TypeMapping or null
**/
public javax.xml.rpc.encoding.TypeMapping getDefaultTypeMapping() {
return defaultDelTM;
}
}
| 7,472 |
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/encoding/SimpleType.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.encoding;
/**
* Marker interface to indicate that a bean is "really" a simple type
* (typically with attributes).
*
* @author Tom Jordahl (tomj@apache.org)
*/
public interface SimpleType {
}
| 7,473 |
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/encoding/AnyContentType.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.encoding;
import org.apache.axis.message.MessageElement;
/**
* Interface to indicate that a bean has xsd:any content
*
* @author Thomas Sandholm (sandholm@apache.org)
*/
public interface AnyContentType {
public MessageElement[] get_any();
public void set_any(MessageElement[] any);
}
| 7,474 |
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/encoding/SerializerFactory.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.encoding;
/**
* This interface describes the AXIS SerializerFactory.
*
* An Axis compliant Serializer Factory must provide one or more
* of the following methods:
*
* public static create(Class javaType, QName xmlType)
* public <constructor>(Class javaType, QName xmlType)
* public <constructor>()
*
* The deployment code will attempt to invoke these methods in the above order.
* The xmlType, javaType arguments are filled in with the values supplied during the
* deployment registration of the factory.
*/
public interface SerializerFactory extends javax.xml.rpc.encoding.SerializerFactory {
}
| 7,475 |
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/encoding/DefaultTypeMappingImpl.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.encoding;
import org.apache.axis.Constants;
import org.apache.axis.attachments.OctetStream;
import org.apache.axis.encoding.ser.ArrayDeserializerFactory;
import org.apache.axis.encoding.ser.ArraySerializerFactory;
import org.apache.axis.encoding.ser.Base64DeserializerFactory;
import org.apache.axis.encoding.ser.Base64SerializerFactory;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.encoding.ser.DateDeserializerFactory;
import org.apache.axis.encoding.ser.DateSerializerFactory;
import org.apache.axis.encoding.ser.DocumentDeserializerFactory;
import org.apache.axis.encoding.ser.DocumentSerializerFactory;
import org.apache.axis.encoding.ser.ElementDeserializerFactory;
import org.apache.axis.encoding.ser.ElementSerializerFactory;
import org.apache.axis.encoding.ser.HexDeserializerFactory;
import org.apache.axis.encoding.ser.HexSerializerFactory;
import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
import org.apache.axis.encoding.ser.MapDeserializerFactory;
import org.apache.axis.encoding.ser.MapSerializerFactory;
import org.apache.axis.encoding.ser.QNameDeserializerFactory;
import org.apache.axis.encoding.ser.QNameSerializerFactory;
import org.apache.axis.encoding.ser.SimpleDeserializerFactory;
import org.apache.axis.encoding.ser.SimpleSerializerFactory;
import org.apache.axis.encoding.ser.VectorDeserializerFactory;
import org.apache.axis.encoding.ser.VectorSerializerFactory;
import org.apache.axis.schema.SchemaVersion;
import org.apache.axis.types.HexBinary;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import javax.xml.rpc.encoding.DeserializerFactory;
/**
* This is the implementation of the axis Default TypeMapping (which extends
* the JAX-RPC TypeMapping interface) for SOAP 1.1.
*
* A TypeMapping contains tuples as follows:
* {Java type, SerializerFactory, DeserializerFactory, Type QName)
*
* In other words, it serves to map Java types to and from XML types using
* particular Serializers/Deserializers. Each TypeMapping is associated with
* one or more encodingStyle URIs.
*
* The wsdl in your web service will use a number of types. The tuple
* information for each of these will be accessed via the TypeMapping.
*
* This TypeMapping is the "default" one, which includes all the standard
* SOAP and schema XSD types. Individual TypeMappings (associated with
* AxisEngines and SOAPServices) will delegate to this one, so if you haven't
* overriden a default mapping we'll end up getting it from here.
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class DefaultTypeMappingImpl extends TypeMappingImpl {
private static DefaultTypeMappingImpl tm = null;
private boolean inInitMappings = false;
/**
* Obtain the singleton default typemapping.
*/
public static synchronized TypeMappingDelegate getSingletonDelegate() {
if (tm == null) {
tm = new DefaultTypeMappingImpl();
}
return new TypeMappingDelegate(tm);
}
protected DefaultTypeMappingImpl() {
initMappings();
}
protected DefaultTypeMappingImpl(boolean noMappings) {
if (!noMappings) {
initMappings();
}
}
protected void initMappings() {
inInitMappings = true;
// Notes:
// 1) The registration statements are order dependent. The last one
// wins. So if two javaTypes of String are registered, the
// ser factory for the last one registered will be chosen. Likewise
// if two javaTypes for XSD_DATE are registered, the deserializer
// factory for the last one registered will be chosen.
// Corollary: Please be very careful with the order. The
// runtime, Java2WSDL and WSDL2Java emitters all
// use this code to get type mapping information.
// 2) Even if the SOAP 1.1 format is used over the wire, an
// attempt is made to receive SOAP 1.2 format from the wire.
// This is the reason why the soap encoded primitives are
// registered without serializers.
// Since the last-registered type wins, I want to add the mime
// String FIRST.
if (JavaUtils.isAttachmentSupported()) {
myRegister(Constants.MIME_PLAINTEXT, java.lang.String.class,
new JAFDataHandlerSerializerFactory(
java.lang.String.class,
Constants.MIME_PLAINTEXT),
new JAFDataHandlerDeserializerFactory(
java.lang.String.class,
Constants.MIME_PLAINTEXT));
}
// HexBinary binary data needs to use the hex binary serializer/deserializer
myRegister(Constants.XSD_HEXBIN, HexBinary.class,
new HexSerializerFactory(
HexBinary.class, Constants.XSD_HEXBIN),
new HexDeserializerFactory(
HexBinary.class, Constants.XSD_HEXBIN));
myRegister(Constants.XSD_HEXBIN, byte[].class,
new HexSerializerFactory(
byte[].class, Constants.XSD_HEXBIN),
new HexDeserializerFactory(
byte[].class, Constants.XSD_HEXBIN));
// SOAP 1.1
// byte[] -ser-> XSD_BASE64
// XSD_BASE64 -deser-> byte[]
// SOAP_BASE64 -deser->byte[]
//
// Special case:
// If serialization is requested for xsd:byte with byte[],
// the array serializer is used. If deserialization
// is specifically requested for xsd:byte with byte[], the
// simple deserializer is used. This is necessary
// to support the serialization/deserialization
// of <element name="a" type="xsd:byte" maxOccurs="unbounded" />
// as discrete bytes without interference with XSD_BASE64.
myRegister(Constants.XSD_BYTE, byte[].class,
new ArraySerializerFactory(),
null
);
myRegister(Constants.XSD_BASE64, byte[].class,
new Base64SerializerFactory(byte[].class,
Constants.XSD_BASE64 ),
new Base64DeserializerFactory(byte[].class,
Constants.XSD_BASE64));
// anySimpleType is mapped to java.lang.String according to JAX-RPC 1.1 spec.
myRegisterSimple(Constants.XSD_ANYSIMPLETYPE, java.lang.String.class);
// If SOAP 1.1 over the wire, map wrapper classes to XSD primitives.
myRegisterSimple(Constants.XSD_STRING, java.lang.String.class);
myRegisterSimple(Constants.XSD_BOOLEAN, java.lang.Boolean.class);
myRegisterSimple(Constants.XSD_DOUBLE, java.lang.Double.class);
myRegisterSimple(Constants.XSD_FLOAT, java.lang.Float.class);
myRegisterSimple(Constants.XSD_INT, java.lang.Integer.class);
myRegisterSimple(Constants.XSD_INTEGER, java.math.BigInteger.class
);
myRegisterSimple(Constants.XSD_DECIMAL, java.math.BigDecimal.class
);
myRegisterSimple(Constants.XSD_LONG, java.lang.Long.class);
myRegisterSimple(Constants.XSD_SHORT, java.lang.Short.class);
myRegisterSimple(Constants.XSD_BYTE, java.lang.Byte.class);
// The XSD Primitives are mapped to java primitives.
myRegisterSimple(Constants.XSD_BOOLEAN, boolean.class);
myRegisterSimple(Constants.XSD_DOUBLE, double.class);
myRegisterSimple(Constants.XSD_FLOAT, float.class);
myRegisterSimple(Constants.XSD_INT, int.class);
myRegisterSimple(Constants.XSD_LONG, long.class);
myRegisterSimple(Constants.XSD_SHORT, short.class);
myRegisterSimple(Constants.XSD_BYTE, byte.class);
// Map QNAME to the jax rpc QName class
myRegister(Constants.XSD_QNAME,
javax.xml.namespace.QName.class,
new QNameSerializerFactory(javax.xml.namespace.QName.class,
Constants.XSD_QNAME),
new QNameDeserializerFactory(javax.xml.namespace.QName.class,
Constants.XSD_QNAME)
);
// The closest match for anytype is Object
myRegister(Constants.XSD_ANYTYPE, java.lang.Object.class,
null, null);
// See the SchemaVersion classes for where the registration of
// dateTime (for 2001) and timeInstant (for 1999 & 2000) happen.
myRegister(Constants.XSD_DATE, java.sql.Date.class,
new DateSerializerFactory(java.sql.Date.class,
Constants.XSD_DATE),
new DateDeserializerFactory(java.sql.Date.class,
Constants.XSD_DATE)
);
// See the SchemaVersion classes for where the registration of
// dateTime (for 2001) and timeInstant (for 1999 & 2000) happen.
myRegister(Constants.XSD_DATE, java.util.Date.class,
new DateSerializerFactory(java.util.Date.class,
Constants.XSD_DATE),
new DateDeserializerFactory(java.util.Date.class,
Constants.XSD_DATE)
);
// Mapping for xsd:time. Map to Axis type Time
myRegister(Constants.XSD_TIME, org.apache.axis.types.Time.class,
new SimpleSerializerFactory(org.apache.axis.types.Time.class,
Constants.XSD_TIME),
new SimpleDeserializerFactory(org.apache.axis.types.Time.class,
Constants.XSD_TIME)
);
// These are the g* types (gYearMonth, etc) which map to Axis types
myRegister(Constants.XSD_YEARMONTH, org.apache.axis.types.YearMonth.class,
new SimpleSerializerFactory(org.apache.axis.types.YearMonth.class,
Constants.XSD_YEARMONTH),
new SimpleDeserializerFactory(org.apache.axis.types.YearMonth.class,
Constants.XSD_YEARMONTH)
);
myRegister(Constants.XSD_YEAR, org.apache.axis.types.Year.class,
new SimpleSerializerFactory(org.apache.axis.types.Year.class,
Constants.XSD_YEAR),
new SimpleDeserializerFactory(org.apache.axis.types.Year.class,
Constants.XSD_YEAR)
);
myRegister(Constants.XSD_MONTH, org.apache.axis.types.Month.class,
new SimpleSerializerFactory(org.apache.axis.types.Month.class,
Constants.XSD_MONTH),
new SimpleDeserializerFactory(org.apache.axis.types.Month.class,
Constants.XSD_MONTH)
);
myRegister(Constants.XSD_DAY, org.apache.axis.types.Day.class,
new SimpleSerializerFactory(org.apache.axis.types.Day.class,
Constants.XSD_DAY),
new SimpleDeserializerFactory(org.apache.axis.types.Day.class,
Constants.XSD_DAY)
);
myRegister(Constants.XSD_MONTHDAY, org.apache.axis.types.MonthDay.class,
new SimpleSerializerFactory(org.apache.axis.types.MonthDay.class,
Constants.XSD_MONTHDAY),
new SimpleDeserializerFactory(org.apache.axis.types.MonthDay.class,
Constants.XSD_MONTHDAY)
);
// Serialize all extensions of Map to SOAP_MAP
// Order counts here, HashMap should be last.
myRegister(Constants.SOAP_MAP, java.util.Hashtable.class,
new MapSerializerFactory(java.util.Hashtable.class,
Constants.SOAP_MAP),
null // Make sure not to override the deser mapping
);
myRegister(Constants.SOAP_MAP, java.util.Map.class,
new MapSerializerFactory(java.util.Map.class,
Constants.SOAP_MAP),
null // Make sure not to override the deser mapping
);
// The SOAP_MAP will be deserialized into a HashMap by default.
myRegister(Constants.SOAP_MAP, java.util.HashMap.class,
new MapSerializerFactory(java.util.Map.class,
Constants.SOAP_MAP),
new MapDeserializerFactory(java.util.HashMap.class,
Constants.SOAP_MAP)
);
// Use the Element Serializeration for elements
myRegister(Constants.SOAP_ELEMENT, org.w3c.dom.Element.class,
new ElementSerializerFactory(),
new ElementDeserializerFactory());
// Use the Document Serializeration for Document's
myRegister(Constants.SOAP_DOCUMENT, org.w3c.dom.Document.class,
new DocumentSerializerFactory(),
new DocumentDeserializerFactory());
myRegister(Constants.SOAP_VECTOR, java.util.Vector.class,
new VectorSerializerFactory(java.util.Vector.class,
Constants.SOAP_VECTOR),
new VectorDeserializerFactory(java.util.Vector.class,
Constants.SOAP_VECTOR)
);
// Register all the supported MIME types
// (note that MIME_PLAINTEXT was registered near the top)
if (JavaUtils.isAttachmentSupported()) {
myRegister(Constants.MIME_IMAGE, java.awt.Image.class,
new JAFDataHandlerSerializerFactory(
java.awt.Image.class,
Constants.MIME_IMAGE),
new JAFDataHandlerDeserializerFactory(
java.awt.Image.class,
Constants.MIME_IMAGE));
myRegister(Constants.MIME_MULTIPART, javax.mail.internet.MimeMultipart.class,
new JAFDataHandlerSerializerFactory(
javax.mail.internet.MimeMultipart.class,
Constants.MIME_MULTIPART),
new JAFDataHandlerDeserializerFactory(
javax.mail.internet.MimeMultipart.class,
Constants.MIME_MULTIPART));
myRegister(Constants.MIME_SOURCE, javax.xml.transform.Source.class,
new JAFDataHandlerSerializerFactory(
javax.xml.transform.Source.class,
Constants.MIME_SOURCE),
new JAFDataHandlerDeserializerFactory(
javax.xml.transform.Source.class,
Constants.MIME_SOURCE));
myRegister(Constants.MIME_OCTETSTREAM, OctetStream.class,
new JAFDataHandlerSerializerFactory(
OctetStream.class,
Constants.MIME_OCTETSTREAM),
new JAFDataHandlerDeserializerFactory(
OctetStream.class,
Constants.MIME_OCTETSTREAM));
myRegister(Constants.MIME_DATA_HANDLER, javax.activation.DataHandler.class,
new JAFDataHandlerSerializerFactory(),
new JAFDataHandlerDeserializerFactory());
}
// xsd:token
myRegister(Constants.XSD_TOKEN, org.apache.axis.types.Token.class,
new SimpleSerializerFactory(org.apache.axis.types.Token.class,
Constants.XSD_TOKEN),
new SimpleDeserializerFactory(org.apache.axis.types.Token.class,
Constants.XSD_TOKEN)
);
// a xsd:normalizedString
myRegister(Constants.XSD_NORMALIZEDSTRING, org.apache.axis.types.NormalizedString.class,
new SimpleSerializerFactory(org.apache.axis.types.NormalizedString.class,
Constants.XSD_NORMALIZEDSTRING),
new SimpleDeserializerFactory(org.apache.axis.types.NormalizedString.class,
Constants.XSD_NORMALIZEDSTRING)
);
// a xsd:unsignedLong
myRegister(Constants.XSD_UNSIGNEDLONG, org.apache.axis.types.UnsignedLong.class,
new SimpleSerializerFactory(org.apache.axis.types.UnsignedLong.class,
Constants.XSD_UNSIGNEDLONG),
new SimpleDeserializerFactory(org.apache.axis.types.UnsignedLong.class,
Constants.XSD_UNSIGNEDLONG)
);
// a xsd:unsignedInt
myRegister(Constants.XSD_UNSIGNEDINT, org.apache.axis.types.UnsignedInt.class,
new SimpleSerializerFactory(org.apache.axis.types.UnsignedInt.class,
Constants.XSD_UNSIGNEDINT),
new SimpleDeserializerFactory(org.apache.axis.types.UnsignedInt.class,
Constants.XSD_UNSIGNEDINT)
);
// a xsd:unsignedShort
myRegister(Constants.XSD_UNSIGNEDSHORT, org.apache.axis.types.UnsignedShort.class,
new SimpleSerializerFactory(org.apache.axis.types.UnsignedShort.class,
Constants.XSD_UNSIGNEDSHORT),
new SimpleDeserializerFactory(org.apache.axis.types.UnsignedShort.class,
Constants.XSD_UNSIGNEDSHORT)
);
// a xsd:unsignedByte
myRegister(Constants.XSD_UNSIGNEDBYTE, org.apache.axis.types.UnsignedByte.class,
new SimpleSerializerFactory(org.apache.axis.types.UnsignedByte.class,
Constants.XSD_UNSIGNEDBYTE),
new SimpleDeserializerFactory(org.apache.axis.types.UnsignedByte.class,
Constants.XSD_UNSIGNEDBYTE)
);
// a xsd:nonNegativeInteger
myRegister(Constants.XSD_NONNEGATIVEINTEGER, org.apache.axis.types.NonNegativeInteger.class,
new SimpleSerializerFactory(org.apache.axis.types.NonNegativeInteger.class,
Constants.XSD_NONNEGATIVEINTEGER),
new SimpleDeserializerFactory(org.apache.axis.types.NonNegativeInteger.class,
Constants.XSD_NONNEGATIVEINTEGER)
);
// a xsd:negativeInteger
myRegister(Constants.XSD_NEGATIVEINTEGER, org.apache.axis.types.NegativeInteger.class,
new SimpleSerializerFactory(org.apache.axis.types.NegativeInteger.class,
Constants.XSD_NEGATIVEINTEGER),
new SimpleDeserializerFactory(org.apache.axis.types.NegativeInteger.class,
Constants.XSD_NEGATIVEINTEGER)
);
// a xsd:positiveInteger
myRegister(Constants.XSD_POSITIVEINTEGER, org.apache.axis.types.PositiveInteger.class,
new SimpleSerializerFactory(org.apache.axis.types.PositiveInteger.class,
Constants.XSD_POSITIVEINTEGER),
new SimpleDeserializerFactory(org.apache.axis.types.PositiveInteger.class,
Constants.XSD_POSITIVEINTEGER)
);
// a xsd:nonPositiveInteger
myRegister(Constants.XSD_NONPOSITIVEINTEGER, org.apache.axis.types.NonPositiveInteger.class,
new SimpleSerializerFactory(org.apache.axis.types.NonPositiveInteger.class,
Constants.XSD_NONPOSITIVEINTEGER),
new SimpleDeserializerFactory(org.apache.axis.types.NonPositiveInteger.class,
Constants.XSD_NONPOSITIVEINTEGER)
);
// a xsd:Name
myRegister(Constants.XSD_NAME, org.apache.axis.types.Name.class,
new SimpleSerializerFactory(org.apache.axis.types.Name.class,
Constants.XSD_NAME),
new SimpleDeserializerFactory(org.apache.axis.types.Name.class,
Constants.XSD_NAME)
);
// a xsd:NCName
myRegister(Constants.XSD_NCNAME, org.apache.axis.types.NCName.class,
new SimpleSerializerFactory(org.apache.axis.types.NCName.class,
Constants.XSD_NCNAME),
new SimpleDeserializerFactory(org.apache.axis.types.NCName.class,
Constants.XSD_NCNAME)
);
// a xsd:ID
myRegister(Constants.XSD_ID, org.apache.axis.types.Id.class,
new SimpleSerializerFactory(org.apache.axis.types.Id.class,
Constants.XSD_ID),
new SimpleDeserializerFactory(org.apache.axis.types.Id.class,
Constants.XSD_ID)
);
// a xml:lang
myRegister(Constants.XML_LANG, org.apache.axis.types.Language.class,
new SimpleSerializerFactory(org.apache.axis.types.Language.class,
Constants.XML_LANG),
new SimpleDeserializerFactory(org.apache.axis.types.Language.class,
Constants.XML_LANG)
);
// a xsd:language
myRegister(Constants.XSD_LANGUAGE, org.apache.axis.types.Language.class,
new SimpleSerializerFactory(org.apache.axis.types.Language.class,
Constants.XSD_LANGUAGE),
new SimpleDeserializerFactory(org.apache.axis.types.Language.class,
Constants.XSD_LANGUAGE)
);
// a xsd:NmToken
myRegister(Constants.XSD_NMTOKEN, org.apache.axis.types.NMToken.class,
new SimpleSerializerFactory(org.apache.axis.types.NMToken.class,
Constants.XSD_NMTOKEN),
new SimpleDeserializerFactory(org.apache.axis.types.NMToken.class,
Constants.XSD_NMTOKEN)
);
// a xsd:NmTokens
myRegister(Constants.XSD_NMTOKENS, org.apache.axis.types.NMTokens.class,
new SimpleSerializerFactory(org.apache.axis.types.NMTokens.class,
Constants.XSD_NMTOKENS),
new SimpleDeserializerFactory(org.apache.axis.types.NMTokens.class,
Constants.XSD_NMTOKENS)
);
// a xsd:NOTATION
myRegister(Constants.XSD_NOTATION, org.apache.axis.types.Notation.class,
new BeanSerializerFactory(org.apache.axis.types.Notation.class,
Constants.XSD_NOTATION),
new BeanDeserializerFactory(org.apache.axis.types.Notation.class,
Constants.XSD_NOTATION)
);
// a xsd:XSD_ENTITY
myRegister(Constants.XSD_ENTITY, org.apache.axis.types.Entity.class,
new SimpleSerializerFactory(org.apache.axis.types.Entity.class,
Constants.XSD_ENTITY),
new SimpleDeserializerFactory(org.apache.axis.types.Entity.class,
Constants.XSD_ENTITY)
);
// a xsd:XSD_ENTITIES
myRegister(Constants.XSD_ENTITIES, org.apache.axis.types.Entities.class,
new SimpleSerializerFactory(org.apache.axis.types.Entities.class,
Constants.XSD_ENTITIES),
new SimpleDeserializerFactory(org.apache.axis.types.Entities.class,
Constants.XSD_ENTITIES)
);
// a xsd:XSD_IDREF
myRegister(Constants.XSD_IDREF, org.apache.axis.types.IDRef.class,
new SimpleSerializerFactory(org.apache.axis.types.IDRef.class,
Constants.XSD_IDREF),
new SimpleDeserializerFactory(org.apache.axis.types.IDRef.class,
Constants.XSD_IDREF)
);
// a xsd:XSD_XSD_IDREFS
myRegister(Constants.XSD_IDREFS, org.apache.axis.types.IDRefs.class,
new SimpleSerializerFactory(org.apache.axis.types.IDRefs.class,
Constants.XSD_IDREFS),
new SimpleDeserializerFactory(org.apache.axis.types.IDRefs.class,
Constants.XSD_IDREFS)
);
// a xsd:Duration
myRegister(Constants.XSD_DURATION, org.apache.axis.types.Duration.class,
new SimpleSerializerFactory(org.apache.axis.types.Duration.class,
Constants.XSD_DURATION),
new SimpleDeserializerFactory(org.apache.axis.types.Duration.class,
Constants.XSD_DURATION)
);
// a xsd:anyURI
myRegister(Constants.XSD_ANYURI, org.apache.axis.types.URI.class,
new SimpleSerializerFactory(org.apache.axis.types.URI.class,
Constants.XSD_ANYURI),
new SimpleDeserializerFactory(org.apache.axis.types.URI.class,
Constants.XSD_ANYURI)
);
// a xsd:schema
myRegister(Constants.XSD_SCHEMA, org.apache.axis.types.Schema.class,
new BeanSerializerFactory(org.apache.axis.types.Schema.class,
Constants.XSD_SCHEMA),
new BeanDeserializerFactory(org.apache.axis.types.Schema.class,
Constants.XSD_SCHEMA)
);
// Need this at the default TypeMapping level so that we can correctly
// obtain the ArraySerializer when in doc/lit mode and only have a
// Java class available (no XML type metadata) - see TypeMappingImpl
// (getSerializer())
myRegister(Constants.SOAP_ARRAY, java.util.ArrayList.class,
new ArraySerializerFactory(),
new ArrayDeserializerFactory()
);
//
// Now register the schema specific types
//
SchemaVersion.SCHEMA_1999.registerSchemaSpecificTypes(this);
SchemaVersion.SCHEMA_2000.registerSchemaSpecificTypes(this);
SchemaVersion.SCHEMA_2001.registerSchemaSpecificTypes(this);
inInitMappings = false;
}
/**
* Register a "simple" type mapping - in other words, a
* @param xmlType
* @param javaType
*/
protected void myRegisterSimple(QName xmlType, Class javaType) {
SerializerFactory sf = new SimpleSerializerFactory(javaType, xmlType);
DeserializerFactory df = null;
if (javaType != java.lang.Object.class) {
df = new SimpleDeserializerFactory(javaType, xmlType);
}
myRegister(xmlType, javaType, sf, df);
}
/**
* Construct TypeMapping for all the [xmlType, javaType] for all of the
* known xmlType namespaces. This is the shotgun approach, which works
* in 99% of the cases. The other cases that are Schema version specific
* (i.e. timeInstant vs. dateTime) are handled by the SchemaVersion
* Interface registerSchemaSpecificTypes().
*
* @param xmlType is the QName type
* @param javaType is the java type
* @param sf is the ser factory (if null, the simple factory is used)
* @param df is the deser factory (if null, the simple factory is used)
*/
protected void myRegister(QName xmlType, Class javaType,
SerializerFactory sf, DeserializerFactory df) {
// Register all known flavors of the namespace.
try {
if (xmlType.getNamespaceURI().equals(
Constants.URI_DEFAULT_SCHEMA_XSD)) {
for (int i=0; i < Constants.URIS_SCHEMA_XSD.length; i++) {
QName qName = new QName(Constants.URIS_SCHEMA_XSD[i],
xmlType.getLocalPart());
super.internalRegister(javaType, qName, sf, df);
}
}
else if (xmlType.getNamespaceURI().equals(
Constants.URI_DEFAULT_SOAP_ENC)) {
for (int i=0; i < Constants.URIS_SOAP_ENC.length; i++) {
QName qName = new QName(Constants.URIS_SOAP_ENC[i],
xmlType.getLocalPart());
super.internalRegister(javaType, qName, sf, df);
}
} else {
// Register with the specified xmlType.
// This is the prefered mapping and the last registed one wins
super.internalRegister(javaType, xmlType, sf, df);
}
} catch (JAXRPCException e) { }
}
// Don't allow anyone to muck with the default type mapping because
// it is a singleton used for the whole system.
public void register(Class javaType, QName xmlType,
javax.xml.rpc.encoding.SerializerFactory sf,
javax.xml.rpc.encoding.DeserializerFactory dsf)
throws JAXRPCException {
super.register(javaType, xmlType, sf, dsf);
}
public void removeSerializer(Class javaType, QName xmlType)
throws JAXRPCException {
throw new JAXRPCException(Messages.getMessage("fixedTypeMapping"));
}
public void removeDeserializer(Class javaType, QName xmlType)
throws JAXRPCException {
throw new JAXRPCException(Messages.getMessage("fixedTypeMapping"));
}
public void setSupportedEncodings(String[] namespaceURIs) {
}
}
| 7,476 |
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/encoding/SerializationContext.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.encoding;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Stack;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import javax.xml.rpc.holders.QNameHolder;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisProperties;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.attachments.Attachments;
import org.apache.axis.client.Call;
import org.apache.axis.components.encoding.XMLEncoder;
import org.apache.axis.components.encoding.XMLEncoderFactory;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.constants.Use;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.encoding.ser.ArraySerializer;
import org.apache.axis.encoding.ser.BaseSerializerFactory;
import org.apache.axis.encoding.ser.SimpleListSerializerFactory;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.schema.SchemaVersion;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.types.HexBinary;
import org.apache.axis.utils.IDKey;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Mapping;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.NSStack;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.utils.cache.MethodCache;
import org.apache.axis.wsdl.symbolTable.SchemaUtils;
import org.apache.axis.wsdl.symbolTable.SymbolTable;
import org.apache.axis.wsdl.symbolTable.Utils;
import org.apache.commons.logging.Log;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
/** Manage a serialization, including keeping track of namespace mappings
* and element stacks.
*
* @author Glen Daniels (gdaniels@apache.org)
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class SerializationContext implements javax.xml.rpc.encoding.SerializationContext
{
protected static Log log =
LogFactory.getLog(SerializationContext.class.getName());
// invariant member variable to track low-level logging requirements
// we cache this once per instance lifecycle to avoid repeated lookups
// in heavily used code.
private final boolean debugEnabled = log.isDebugEnabled();
private NSStack nsStack = null;
private boolean writingStartTag = false;
private boolean onlyXML = true;
private int indent=0;
private Stack elementStack = new Stack();
private Writer writer;
private int lastPrefixIndex = 1;
private MessageContext msgContext;
private QName currentXMLType;
/** The item QName if we're serializing a literal array... */
private QName itemQName;
/** The item type if we're serializing a literal array... */
private QName itemType;
/** The SOAP context we're using */
private SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS;
private static QName multirefQName = new QName("","multiRef");
private static Class[] SERIALIZER_CLASSES =
new Class[] {String.class, Class.class, QName.class};
private static final String SERIALIZER_METHOD = "getSerializer";
/**
* Should I write out objects as multi-refs?
*
* !!! For now, this is an all-or-nothing flag. Either ALL objects will
* be written in-place as hrefs with the full serialization at the end
* of the body, or we'll write everything inline (potentially repeating
* serializations of identical objects).
*/
private boolean doMultiRefs = false;
/**
* Should I disable the pretty xml completely.
*/
private boolean disablePrettyXML = false;
/**
* Should I disable the namespace prefix optimization.
*/
private boolean enableNamespacePrefixOptimization = false;
/**
* current setting for pretty
*/
private boolean pretty = false;
/**
* Should I send an XML declaration?
*/
private boolean sendXMLDecl = true;
/**
* Should I send xsi:type attributes? By default, yes.
*/
private boolean sendXSIType = true;
/**
* Send an element with an xsi:nil="true" attribute for null
* variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
*/
private Boolean sendNull = Boolean.TRUE;
/**
* A place to hold objects we cache for multi-ref serialization, and
* remember the IDs we assigned them.
*/
private HashMap multiRefValues = null;
private int multiRefIndex = -1;
private boolean noNamespaceMappings = true;
private QName writeXMLType;
private XMLEncoder encoder = null;
/** The flag whether the XML decl should be written */
protected boolean startOfDocument = true;
/** The encoding to serialize */
private String encoding = XMLEncoderFactory.DEFAULT_ENCODING;
class MultiRefItem {
String id;
QName xmlType;
Boolean sendType;
Object value;
MultiRefItem(String id,
QName xmlType,
Boolean sendType, Object value) {
this.id = id;
this.xmlType = xmlType;
this.sendType = sendType;
this.value = value;
}
}
/**
* These three variables are necessary to process
* multi-level object graphs for multi-ref serialization.
* While writing out nested multi-ref objects (via outputMultiRef), we
* will fill the secondLevelObjects vector
* with any new objects encountered.
* The outputMultiRefsFlag indicates whether we are currently within the
* outputMultiRef() method (so that serialization() knows to update the
* secondLevelObjects vector).
* The forceSer variable is the trigger to force actual serialization of the indicated object.
*/
private HashSet secondLevelObjects = null;
private Object forceSer = null;
private boolean outputMultiRefsFlag = false;
/**
* Which schema version are we using?
*/
SchemaVersion schemaVersion = SchemaVersion.SCHEMA_2001;
/**
* A list of particular namespace -> prefix mappings we should prefer.
* See getPrefixForURI() below.
*/
HashMap preferredPrefixes = new HashMap();
/**
* Construct SerializationContext with associated writer
* @param writer java.io.Writer
*/
public SerializationContext(Writer writer)
{
this.writer = writer;
initialize();
}
private void initialize() {
// These are the preferred prefixes we'll use instead of the "ns1"
// style defaults. MAKE SURE soapConstants IS SET CORRECTLY FIRST!
preferredPrefixes.put(soapConstants.getEncodingURI(),
Constants.NS_PREFIX_SOAP_ENC);
preferredPrefixes.put(Constants.NS_URI_XML,
Constants.NS_PREFIX_XML);
preferredPrefixes.put(schemaVersion.getXsdURI(),
Constants.NS_PREFIX_SCHEMA_XSD);
preferredPrefixes.put(schemaVersion.getXsiURI(),
Constants.NS_PREFIX_SCHEMA_XSI);
preferredPrefixes.put(soapConstants.getEnvelopeURI(),
Constants.NS_PREFIX_SOAP_ENV);
nsStack = new NSStack(enableNamespacePrefixOptimization);
}
/**
* Construct SerializationContext with associated writer and MessageContext
* @param writer java.io.Writer
* @param msgContext is the MessageContext
*/
public SerializationContext(Writer writer, MessageContext msgContext)
{
this.writer = writer;
this.msgContext = msgContext;
if ( msgContext != null ) {
soapConstants = msgContext.getSOAPConstants();
// Use whatever schema is associated with this MC
schemaVersion = msgContext.getSchemaVersion();
Boolean shouldSendDecl = (Boolean)msgContext.getProperty(
AxisEngine.PROP_XML_DECL);
if (shouldSendDecl != null)
sendXMLDecl = shouldSendDecl.booleanValue();
Boolean shouldSendMultiRefs =
(Boolean)msgContext.getProperty(AxisEngine.PROP_DOMULTIREFS);
if (shouldSendMultiRefs != null)
doMultiRefs = shouldSendMultiRefs.booleanValue();
Boolean shouldDisablePrettyXML =
(Boolean)msgContext.getProperty(AxisEngine.PROP_DISABLE_PRETTY_XML);
if (shouldDisablePrettyXML != null)
disablePrettyXML = shouldDisablePrettyXML.booleanValue();
Boolean shouldDisableNamespacePrefixOptimization =
(Boolean)msgContext.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION);
if (shouldDisableNamespacePrefixOptimization != null) {
enableNamespacePrefixOptimization = shouldDisableNamespacePrefixOptimization.booleanValue();
} else {
enableNamespacePrefixOptimization = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,
"true"));
}
boolean sendTypesDefault = sendXSIType;
// A Literal use operation overrides the above settings. Don't
// send xsi:type, and don't do multiref in that case.
OperationDesc operation = msgContext.getOperation();
if (operation != null) {
if (operation.getUse() != Use.ENCODED) {
doMultiRefs = false;
sendTypesDefault = false;
}
} else {
// A Literal use service also overrides the above settings.
SOAPService service = msgContext.getService();
if (service != null) {
if (service.getUse() != Use.ENCODED) {
doMultiRefs = false;
sendTypesDefault = false;
}
}
}
// The SEND_TYPE_ATTR and PROP_SEND_XSI options indicate
// whether the elements should have xsi:type attributes.
// Only turn this off is the user tells us to
if ( !msgContext.isPropertyTrue(Call.SEND_TYPE_ATTR, sendTypesDefault ))
sendXSIType = false ;
// Don't need this since the above isPropertyTrue should walk up to the engine's
// properties...?
//
// Boolean opt = (Boolean)optionSource.getOption(AxisEngine.PROP_SEND_XSI);
// if (opt != null) {
// sendXSIType = opt.booleanValue();
// }
} else {
enableNamespacePrefixOptimization = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,
"true"));
disablePrettyXML = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_DISABLE_PRETTY_XML,
"true"));
}
// Set up preferred prefixes based on current schema, soap ver, etc.
initialize();
}
/**
* Get whether the serialization should be pretty printed.
* @return true/false
*/
public boolean getPretty() {
return pretty;
}
/**
* Indicate whether the serialization should be pretty printed.
* @param pretty true/false
*/
public void setPretty(boolean pretty) {
if(!disablePrettyXML) {
this.pretty = pretty;
}
}
/**
* Are we doing multirefs?
* @return true or false
*/
public boolean getDoMultiRefs() {
return doMultiRefs;
}
/**
* Set whether we are doing multirefs
*/
public void setDoMultiRefs (boolean shouldDo)
{
doMultiRefs = shouldDo;
}
/**
* Set whether or not we should write XML declarations.
* @param sendDecl true/false
*/
public void setSendDecl(boolean sendDecl)
{
sendXMLDecl = sendDecl;
}
/**
* Get whether or not to write xsi:type attributes.
* @return true/false
*/
public boolean shouldSendXSIType() {
return sendXSIType;
}
/**
* Get the TypeMapping we're using.
* @return TypeMapping or null
*/
public TypeMapping getTypeMapping()
{
// Always allow the default mappings
if (msgContext == null)
return DefaultTypeMappingImpl.getSingletonDelegate();
String encodingStyle = msgContext.getEncodingStyle();
if (encodingStyle == null)
encodingStyle = soapConstants.getEncodingURI();
return (TypeMapping) msgContext.
getTypeMappingRegistry().getTypeMapping(encodingStyle);
}
/**
* Get the TypeMappingRegistry we're using.
* @return TypeMapping or null
*/
public TypeMappingRegistry getTypeMappingRegistry() {
if (msgContext == null)
return null;
return msgContext.getTypeMappingRegistry();
}
/**
* Get a prefix for a namespace URI. This method will ALWAYS
* return a valid prefix - if the given URI is already mapped in this
* serialization, we return the previous prefix. If it is not mapped,
* we will add a new mapping and return a generated prefix of the form
* "ns<num>".
* @param uri is the namespace uri
* @return prefix
*/
public String getPrefixForURI(String uri)
{
return getPrefixForURI(uri, null, false);
}
/**
* Get a prefix for the given namespace URI. If one has already been
* defined in this serialization, use that. Otherwise, map the passed
* default prefix to the URI, and return that. If a null default prefix
* is passed, use one of the form "ns<num>"
*/
public String getPrefixForURI(String uri, String defaultPrefix)
{
return getPrefixForURI(uri, defaultPrefix, false);
}
/**
* Get a prefix for the given namespace URI. If one has already been
* defined in this serialization, use that. Otherwise, map the passed
* default prefix to the URI, and return that. If a null default prefix
* is passed, use one of the form "ns<num>"
*/
public String getPrefixForURI(String uri, String defaultPrefix, boolean attribute)
{
if ((uri == null) || (uri.length() == 0))
return null;
// If we're looking for an attribute prefix, we shouldn't use the
// "" prefix, but always register/find one.
String prefix = nsStack.getPrefix(uri, attribute);
if (prefix == null) {
prefix = (String)preferredPrefixes.get(uri);
if (prefix == null) {
if (defaultPrefix == null) {
prefix = "ns" + lastPrefixIndex++;
while(nsStack.getNamespaceURI(prefix)!=null) {
prefix = "ns" + lastPrefixIndex++;
}
} else {
prefix = defaultPrefix;
}
}
registerPrefixForURI(prefix, uri);
}
return prefix;
}
/**
* Register prefix for the indicated uri
* @param prefix
* @param uri is the namespace uri
*/
public void registerPrefixForURI(String prefix, String uri)
{
if (debugEnabled) {
log.debug(Messages.getMessage("register00", prefix, uri));
}
if ((uri != null) && (prefix != null)) {
if (noNamespaceMappings) {
nsStack.push();
noNamespaceMappings = false;
}
String activePrefix = nsStack.getPrefix(uri,true);
if(activePrefix == null || !activePrefix.equals(prefix)) {
nsStack.add(uri, prefix);
}
}
}
/**
* Return the current message
*/
public Message getCurrentMessage()
{
if (msgContext == null)
return null;
return msgContext.getCurrentMessage();
}
/**
* Get the MessageContext we're operating with
*/
public MessageContext getMessageContext() {
return msgContext;
}
/**
* Returns this context's encoding style. If we've got a message
* context then we'll get the style from that; otherwise we'll
* return a default.
*
* @return a <code>String</code> value
*/
public String getEncodingStyle() {
return msgContext == null ? Use.DEFAULT.getEncoding() : msgContext.getEncodingStyle();
}
/**
* Returns whether this context should be encoded or not.
*
* @return a <code>boolean</code> value
*/
public boolean isEncoded() {
return Constants.isSOAP_ENC(getEncodingStyle());
}
/**
* Convert QName to a string of the form <prefix>:<localpart>
* @param qName
* @return prefixed qname representation for serialization.
*/
public String qName2String(QName qName, boolean writeNS)
{
String prefix = null;
String namespaceURI = qName.getNamespaceURI();
String localPart = qName.getLocalPart();
if(localPart != null && localPart.length() > 0) {
int index = localPart.indexOf(':');
if(index!=-1){
prefix = localPart.substring(0,index);
if(prefix.length()>0 && !prefix.equals("urn")){
registerPrefixForURI(prefix, namespaceURI);
localPart = localPart.substring(index+1);
} else {
prefix = null;
}
}
localPart = Utils.getLastLocalPart(localPart);
}
if (namespaceURI.length() == 0) {
if (writeNS) {
// If this is unqualified (i.e. prefix ""), set the default
// namespace to ""
String defaultNS = nsStack.getNamespaceURI("");
if (defaultNS != null && defaultNS.length() > 0) {
registerPrefixForURI("", "");
}
}
} else {
prefix = getPrefixForURI(namespaceURI);
}
if ((prefix == null) || (prefix.length() == 0))
return localPart;
return prefix + ':' + localPart;
}
public String qName2String(QName qName)
{
return qName2String(qName, false);
}
/**
* Convert attribute QName to a string of the form <prefix>:<localpart>
* There are slightly different rules for attributes:
* - There is no default namespace
* - any attribute in a namespace must have a prefix
*
* @param qName QName
* @return prefixed qname representation for serialization.
*/
public String attributeQName2String(QName qName) {
String prefix = null;
String uri = qName.getNamespaceURI();
if (uri.length() > 0) {
prefix = getPrefixForURI(uri, null, true);
}
if ((prefix == null) || (prefix.length() == 0))
return qName.getLocalPart();
return prefix + ':' + qName.getLocalPart();
}
/**
* Get the QName associated with the specified class.
* @param cls Class of an object requiring serialization.
* @return appropriate QName associated with the class.
*/
public QName getQNameForClass(Class cls)
{
return getTypeMapping().getTypeQName(cls);
}
/**
* Indicates whether the object should be interpretted as a primitive
* for the purposes of multi-ref processing. A primitive value
* is serialized directly instead of using id/href pairs. Thus
* primitive serialization/deserialization is slightly faster.
* @param value to be serialized
* @return true/false
*/
public boolean isPrimitive(Object value)
{
if (value == null) return true;
Class javaType = value.getClass();
if (javaType.isPrimitive()) return true;
if (javaType == String.class) return true;
if (Calendar.class.isAssignableFrom(javaType)) return true;
if (Date.class.isAssignableFrom(javaType)) return true;
if (HexBinary.class.isAssignableFrom(javaType)) return true;
if (Element.class.isAssignableFrom(javaType)) return true;
if (javaType == byte[].class) return true;
// There has been discussion as to whether arrays themselves should
// be regarded as multi-ref.
// Here are the three options:
// 1) Arrays are full-fledged Objects and therefore should always be
// multi-ref'd (Pro: This is like java. Con: Some runtimes don't
// support this yet, and it requires more stuff to be passed over the wire.)
// 2) Arrays are not full-fledged Objects and therefore should
// always be passed as single ref (note the elements of the array
// may be multi-ref'd.) (Pro: This seems reasonable, if a user
// wants multi-referencing put the array in a container. Also
// is more interop compatible. Con: Not like java serialization.)
// 3) Arrays of primitives should be single ref, and arrays of
// non-primitives should be multi-ref. (Pro: Takes care of the
// looping case. Con: Seems like an obtuse rule.)
//
// Changing the code from (1) to (2) to see if interop fairs better.
if (javaType.isArray()) return true;
// Note that java.lang wrapper classes (i.e. java.lang.Integer) are
// not primitives unless the corresponding type is an xsd type.
// (If the wrapper maps to a soap encoded primitive, it can be nillable
// and multi-ref'd).
QName qName = getQNameForClass(javaType);
if (qName != null && Constants.isSchemaXSD(qName.getNamespaceURI())) {
if (SchemaUtils.isSimpleSchemaType(qName)) {
return true;
}
}
return false;
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive, the
* javaType is the actual unwrapped object type.
* xsi:type is set by using the javaType to
* find an appopriate xmlType from the TypeMappingRegistry.
* Null values and the xsi:type flag will be sent or not depending
* on previous configuration of this SerializationContext.
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value)
throws IOException {
serialize(elemQName, attributes, value, null, null, null, null);
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive, the
* javaType is the actual unwrapped object type.
* The xmlType is the QName of the type that is used to set
* xsi:type. If not specified, xsi:type is set by using the javaType to
* find an appopriate xmlType from the TypeMappingRegistry.
* Null values and the xsi:type flag will be sent or not depending
* on previous configuration of this SerializationContext.
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType is the qname of the type or null.
* @deprecated use serialize(QName, Attributes, Object, QName, Class) instead
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType)
throws IOException {
serialize(elemQName, attributes, value, xmlType, null, null, null);
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive, the
* javaType is the actual unwrapped object type.
* The xmlType is the QName of the type that is used to set
* xsi:type. If not specified, xsi:type is set by using the javaType to
* find an appopriate xmlType from the TypeMappingRegistry.
* Null values and the xsi:type flag will be sent or not depending
* on previous configuration of this SerializationContext.
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType is the qname of the type or null.
* @param javaType is the java type of the value
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType, Class javaType)
throws IOException {
serialize(elemQName, attributes, value, xmlType, javaType, null, null);
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive.
* The xmlType (if specified) is the QName of the type that is used to set
* xsi:type.
* The sendNull flag indicates whether null values should be sent over the
* wire (default is to send such values with xsi:nil="true").
* The sendType flag indicates whether the xsi:type flag should be sent
* (default is true).
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType is the qname of the type or null.
* @param sendNull determines whether to send null values.
* @param sendType determines whether to set xsi:type attribute.
*
* @deprecated use serialize(QName, Attributes, Object, QName,
* Boolean, Boolean) instead.
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType,
boolean sendNull,
Boolean sendType)
throws IOException
{
serialize( elemQName, attributes, value, xmlType, null,
(sendNull) ? Boolean.TRUE : Boolean.FALSE,
sendType);
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive.
* The xmlType (if specified) is the QName of the type that is used to set
* xsi:type.
* The sendNull flag indicates whether to end an element with an xsi:nil="true" attribute for null
* variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
* The sendType flag indicates whether the xsi:type flag should be sent
* (default is true).
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType is the qname of the type or null.
* @param sendNull determines whether to send null values.
* @param sendType determines whether to set xsi:type attribute.
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType,
Boolean sendNull,
Boolean sendType)
throws IOException
{
serialize(elemQName, attributes, value, xmlType, null, sendNull, sendType);
}
/**
* Serialize the indicated value as an element with the name
* indicated by elemQName.
* The attributes are additional attribute to be serialized on the element.
* The value is the object being serialized. (It may be serialized
* directly or serialized as an mult-ref'd item)
* The value is an Object, which may be a wrapped primitive.
* The xmlType (if specified) is the QName of the type that is used to set
* xsi:type.
* The sendNull flag indicates whether to end an element with an xsi:nil="true" attribute for null
* variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
* The sendType flag indicates whether the xsi:type flag should be sent
* (default is true).
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType is the qname of the type or null.
* @param javaClass is the java type of the value
* @param sendNull determines whether to send null values.
* @param sendType determines whether to set xsi:type attribute.
*/
public void serialize(QName elemQName,
Attributes attributes,
Object value,
QName xmlType,
Class javaClass,
Boolean sendNull,
Boolean sendType)
throws IOException
{
if (log.isDebugEnabled()) {
log.debug("Start serializing element; elemQName=" + elemQName
+ "; xmlType=" + xmlType + "; javaClass=" + javaClass
+ "; sendNull=" + sendNull + "; sendType=" + sendType + "; value=" + value);
}
boolean sendXSITypeCache = sendXSIType;
if (sendType != null) {
sendXSIType = sendType.booleanValue();
}
boolean shouldSendType = shouldSendXSIType();
try {
Boolean sendNullCache = this.sendNull;
if (sendNull != null) {
this.sendNull = sendNull;
} else {
sendNull = this.sendNull;
}
if (value == null) {
// If the value is null, the element is
// passed with xsi:nil="true" to indicate that no object is present.
if (this.sendNull.booleanValue()) {
AttributesImpl attrs = new AttributesImpl();
if (attributes != null && 0 < attributes.getLength())
attrs.setAttributes(attributes);
if (shouldSendType)
attrs = (AttributesImpl) setTypeAttribute(attrs, xmlType);
String nil = schemaVersion.getNilQName().getLocalPart();
attrs.addAttribute(schemaVersion.getXsiURI(), nil, "xsi:" + nil,
"CDATA", "true");
startElement(elemQName, attrs);
endElement();
}
this.sendNull = sendNullCache;
return;
}
Message msg= getCurrentMessage();
if(null != msg){
//Get attachments. returns null if no attachment support.
Attachments attachments= getCurrentMessage().getAttachmentsImpl();
if( null != attachments && attachments.isAttachment(value)){
//Attachment support and this is an object that should be treated as an attachment.
//Allow an the attachment to do its own serialization.
serializeActual(elemQName, attributes, value,
xmlType, javaClass, sendType);
//No need to add to mulitRefs. Attachment data stream handled by
// the message;
this.sendNull = sendNullCache;
return;
}
}
// If multi-reference is enabled and this object value is not a primitive
// and we are not forcing serialization of the object, then generate
// an element href (and store the object for subsequent outputMultiRef
// processing).
// NOTE : you'll notice that everywhere we register objects in the
// multiRefValues and secondLevelObjects collections, we key them
// using getIdentityKey(value) instead of the Object reference itself.
// THIS IS IMPORTANT, and please make sure you understand what's
// going on if you change any of this code. It's this way to make
// sure that individual Objects are serialized separately even if the
// hashCode() and equals() methods have been overloaded to make two
// Objects appear equal.
if (doMultiRefs && isEncoded() &&
(value != forceSer) && !isPrimitive(value)) {
if (multiRefIndex == -1)
multiRefValues = new HashMap();
String id;
// Look for a multi-ref descriptor for this Object.
MultiRefItem mri = (MultiRefItem)multiRefValues.get(
getIdentityKey(value));
if (mri == null) {
// Didn't find one, so create one, give it a new ID, and store
// it for next time.
multiRefIndex++;
id = "id" + multiRefIndex;
mri = new MultiRefItem (id, xmlType, sendType, value);
multiRefValues.put(getIdentityKey(value), mri);
/**
* If we're SOAP 1.2, we can "inline" the serializations,
* so put it out now, with it's ID.
*/
if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
AttributesImpl attrs = new AttributesImpl();
if (attributes != null && 0 < attributes.getLength())
attrs.setAttributes(attributes);
attrs.addAttribute("", Constants.ATTR_ID, "id", "CDATA",
id);
serializeActual(elemQName, attrs, value, xmlType, javaClass, sendType);
this.sendNull = sendNullCache;
return;
}
/** If we're in the middle of writing out
* the multi-refs, we've already cloned the list of objects
* and so even though we add a new one to multiRefValues,
* it won't get serialized this time around.
*
* To deal with this, we maintain a list of "second level"
* Objects - ones that need serializing as a result of
* serializing the first level. When outputMultiRefs() is
* nearly finished, it checks to see if secondLevelObjects
* is empty, and if not, it goes back and loops over those
* Objects. This can happen N times depending on how deep
* the Object graph goes.
*/
if (outputMultiRefsFlag) {
if (secondLevelObjects == null)
secondLevelObjects = new HashSet();
secondLevelObjects.add(getIdentityKey(value));
}
} else {
// Found one, remember it's ID
id = mri.id;
}
// Serialize an HREF to our object
AttributesImpl attrs = new AttributesImpl();
if (attributes != null && 0 < attributes.getLength())
attrs.setAttributes(attributes);
attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(),
"CDATA", '#' + id);
startElement(elemQName, attrs);
endElement();
this.sendNull = sendNullCache;
return;
}
// The forceSer variable is set by outputMultiRefs to force
// serialization of this object via the serialize(...) call
// below. However, if the forced object contains a self-reference, we
// get into an infinite loop..which is why it is set back to null
// before the actual serialization.
if (value == forceSer)
forceSer = null;
// Actually serialize the value. (i.e. not an href like above)
serializeActual(elemQName, attributes, value, xmlType, javaClass, sendType);
} finally {
sendXSIType = sendXSITypeCache;
}
}
/**
* Get an IDKey that represents the unique identity of the object.
* This is used as a unique key into a HashMap which will
* not give false hits on other Objects where hashCode() and equals()
* have been overriden to match.
*
* @param value the Object to hash
* @return a unique IDKey for the identity
*/
private IDKey getIdentityKey(Object value) {
return new IDKey(value);
}
/**
* The serialize method uses hrefs to reference all non-primitive
* values. These values are stored and serialized by calling
* outputMultiRefs after the serialize method completes.
*/
public void outputMultiRefs() throws IOException
{
if (!doMultiRefs || (multiRefValues == null) ||
soapConstants == SOAPConstants.SOAP12_CONSTANTS)
return;
outputMultiRefsFlag = true;
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("","","","","");
String encodingURI = soapConstants.getEncodingURI();
// explicitly state that this attribute is not a root
String prefix = getPrefixForURI(encodingURI);
String root = prefix + ":root";
attrs.addAttribute(encodingURI, Constants.ATTR_ROOT, root,
"CDATA", "0");
// Make sure we put the encodingStyle on each multiref element we
// output.
String encodingStyle;
if (msgContext != null) {
encodingStyle = msgContext.getEncodingStyle();
} else {
encodingStyle = soapConstants.getEncodingURI();
}
String encStyle = getPrefixForURI(soapConstants.getEnvelopeURI()) +
':' + Constants.ATTR_ENCODING_STYLE;
attrs.addAttribute(soapConstants.getEnvelopeURI(),
Constants.ATTR_ENCODING_STYLE,
encStyle,
"CDATA",
encodingStyle);
// Make a copy of the keySet because it could be updated
// during processing
HashSet keys = new HashSet();
keys.addAll(multiRefValues.keySet());
Iterator i = keys.iterator();
while (i.hasNext()) {
while (i.hasNext()) {
AttributesImpl attrs2 = new AttributesImpl(attrs);
Object val = i.next();
MultiRefItem mri = (MultiRefItem) multiRefValues.get(val);
attrs2.setAttribute(0, "", Constants.ATTR_ID, "id", "CDATA",
mri.id);
forceSer = mri.value;
// Now serialize the value.
// The sendType parameter is defaulted for interop purposes.
// Some of the remote services do not know how to
// ascertain the type in these circumstances (though Axis does).
serialize(multirefQName, attrs2, mri.value,
mri.xmlType,
null,
this.sendNull,
Boolean.TRUE); // mri.sendType
}
// Done processing the iterated values. During the serialization
// of the values, we may have run into new nested values. These
// were placed in the secondLevelObjects map, which we will now
// process by changing the iterator to locate these values.
if (secondLevelObjects != null) {
i = secondLevelObjects.iterator();
secondLevelObjects = null;
}
}
// Reset maps and flags
forceSer = null;
outputMultiRefsFlag = false;
multiRefValues = null;
multiRefIndex = -1;
secondLevelObjects = null;
}
public void writeXMLDeclaration() throws IOException {
writer.write("<?xml version=\"1.0\" encoding=\"");
writer.write(encoding);
writer.write("\"?>");
startOfDocument = false;
}
/**
* Writes (using the Writer) the start tag for element QName along with the
* indicated attributes and namespace mappings.
* @param qName is the name of the element
* @param attributes are the attributes to write
*/
public void startElement(QName qName, Attributes attributes)
throws IOException
{
java.util.ArrayList vecQNames = null;
if (debugEnabled) {
log.debug(Messages.getMessage("startElem00", qName.toString()));
}
if (startOfDocument && sendXMLDecl) {
writeXMLDeclaration();
}
if (writingStartTag) {
writer.write('>');
if (pretty) writer.write('\n');
indent++;
}
if (pretty) for (int i=0; i<indent; i++) writer.write(' ');
String elementQName = qName2String(qName, true);
writer.write('<');
writer.write(elementQName);
if (writeXMLType != null) {
attributes = setTypeAttribute(attributes, writeXMLType);
writeXMLType = null;
}
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
String qname = attributes.getQName(i);
writer.write(' ');
String prefix = "";
String uri = attributes.getURI(i);
if (uri != null && uri.length() > 0) {
if (qname.length() == 0) {
// If qname isn't set, generate one
prefix = getPrefixForURI(uri);
} else {
// If it is, make sure the prefix looks reasonable.
int idx = qname.indexOf(':');
if (idx > -1) {
prefix = qname.substring(0, idx);
prefix = getPrefixForURI(uri,
prefix, true);
}
}
if (prefix.length() > 0) {
qname = prefix + ':' + attributes.getLocalName(i);
} else {
qname = attributes.getLocalName(i);
}
} else {
qname = attributes.getQName(i);
if(qname.length() == 0)
qname = attributes.getLocalName(i);
}
if (qname.startsWith("xmlns")) {
if (vecQNames == null) vecQNames = new ArrayList();
vecQNames.add(qname);
}
writer.write(qname);
writer.write("=\"");
getEncoder().writeEncoded(writer, attributes.getValue(i));
writer.write('"');
}
}
if (noNamespaceMappings) {
nsStack.push();
} else {
for (Mapping map=nsStack.topOfFrame(); map!=null; map=nsStack.next()) {
if (!(map.getNamespaceURI().equals(Constants.NS_URI_XMLNS) && map.getPrefix().equals("xmlns")) &&
!(map.getNamespaceURI().equals(Constants.NS_URI_XML) && map.getPrefix().equals("xml")))
{
StringBuffer sb = new StringBuffer("xmlns");
if (map.getPrefix().length() > 0) {
sb.append(':');
sb.append(map.getPrefix());
}
String qname = sb.toString();
if ((vecQNames==null) || (vecQNames.indexOf(qname)==-1)) {
writer.write(' ');
writer.write(qname);
writer.write("=\"");
getEncoder().writeEncoded(writer, map.getNamespaceURI());
writer.write('"');
}
}
}
noNamespaceMappings = true;
}
writingStartTag = true;
elementStack.push(elementQName);
onlyXML=true;
}
/**
* Writes the end element tag for the open element.
**/
public void endElement()
throws IOException
{
String elementQName = (String)elementStack.pop();
if (debugEnabled) {
log.debug(Messages.getMessage("endElem00", "" + elementQName));
}
nsStack.pop();
if (writingStartTag) {
writer.write("/>");
if (pretty) writer.write('\n');
writingStartTag = false;
return;
}
if (onlyXML) {
indent--;
if (pretty) for (int i=0; i<indent; i++) writer.write(' ');
}
writer.write("</");
writer.write(elementQName);
writer.write('>');
if (pretty) if (indent>0) writer.write('\n');
onlyXML=true;
}
/**
* Convenience operation to write out (to Writer) the characters
* in p1 starting at index p2 for length p3.
* @param p1 character array to write
* @param p2 starting index in array
* @param p3 length to write
*/
public void writeChars(char [] p1, int p2, int p3)
throws IOException
{
if (startOfDocument && sendXMLDecl) {
writeXMLDeclaration();
}
if (writingStartTag) {
writer.write('>');
writingStartTag = false;
}
writeSafeString(String.valueOf(p1,p2,p3));
onlyXML=false;
}
/**
* Convenience operation to write out (to Writer) the String
* @param string is the String to write.
*/
public void writeString(String string)
throws IOException
{
if (startOfDocument && sendXMLDecl) {
writeXMLDeclaration();
}
if (writingStartTag) {
writer.write('>');
writingStartTag = false;
}
writer.write(string);
onlyXML=false;
}
/**
* Convenience operation to write out (to Writer) the String
* properly encoded with xml entities (like &amp;)
* @param string is the String to write.
*/
public void writeSafeString(String string)
throws IOException
{
if (startOfDocument && sendXMLDecl) {
writeXMLDeclaration();
}
if (writingStartTag) {
writer.write('>');
writingStartTag = false;
}
getEncoder().writeEncoded(writer, string);
onlyXML=false;
}
/**
* Output a DOM representation to a SerializationContext
* @param el is a DOM Element
*/
public void writeDOMElement(Element el)
throws IOException
{
if (startOfDocument && sendXMLDecl) {
writeXMLDeclaration();
}
// If el is a Text element, write the text and exit
if (el instanceof org.apache.axis.message.Text) {
writeSafeString(((Text)el).getData());
return;
}
AttributesImpl attributes = null;
NamedNodeMap attrMap = el.getAttributes();
if (attrMap.getLength() > 0) {
attributes = new AttributesImpl();
for (int i = 0; i < attrMap.getLength(); i++) {
Attr attr = (Attr)attrMap.item(i);
String tmp = attr.getNamespaceURI();
if ( tmp != null && tmp.equals(Constants.NS_URI_XMLNS) ) {
String prefix = attr.getLocalName();
if (prefix != null) {
if (prefix.equals("xmlns"))
prefix = "";
String nsURI = attr.getValue();
registerPrefixForURI(prefix, nsURI);
}
continue;
}
attributes.addAttribute(attr.getNamespaceURI(),
attr.getLocalName(),
attr.getName(),
"CDATA", attr.getValue());
}
}
String namespaceURI = el.getNamespaceURI();
String localPart = el.getLocalName();
if(namespaceURI == null || namespaceURI.length()==0)
localPart = el.getNodeName();
QName qName = new QName(namespaceURI, localPart);
startElement(qName, attributes);
NodeList children = el.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
writeDOMElement((Element)child);
} else if (child instanceof CDATASection) {
writeString("<![CDATA[");
writeString(((Text)child).getData());
writeString("]]>");
} else if (child instanceof Comment) {
writeString("<!--");
writeString(((CharacterData)child).getData());
writeString("-->");
} else if (child instanceof Text) {
writeSafeString(((Text)child).getData());
}
}
endElement();
}
/**
* Convenience method to get the Serializer for a specific
* java type
* @param javaType is Class for a type to serialize
* @return Serializer
*/
public final Serializer getSerializerForJavaType(Class javaType) {
SerializerFactory serF = null;
Serializer ser = null;
try {
serF = (SerializerFactory) getTypeMapping().getSerializer(javaType);
if (serF != null) {
ser = (Serializer) serF.getSerializerAs(Constants.AXIS_SAX);
}
} catch (JAXRPCException e) {
}
return ser;
}
/**
* Obtains the type attribute that should be serialized and returns the new list of Attributes
* @param attributes of the qname
* @param type is the qname of the type
* @return new list of Attributes
*/
public Attributes setTypeAttribute(Attributes attributes, QName type)
{
SchemaVersion schema = SchemaVersion.SCHEMA_2001;
if (msgContext != null) {
schema = msgContext.getSchemaVersion();
}
if (type == null ||
type.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) >= 0 ||
((attributes != null) &&
(attributes.getIndex(schema.getXsiURI(),
"type") != -1)))
return attributes;
if (log.isDebugEnabled()) {
log.debug("Adding xsi:type attribute for type " + type);
}
AttributesImpl attrs = new AttributesImpl();
if (attributes != null && 0 < attributes.getLength() )
attrs.setAttributes(attributes);
String prefix = getPrefixForURI(schema.getXsiURI(),
"xsi");
attrs.addAttribute(schema.getXsiURI(),
"type",
prefix + ":type",
"CDATA", attributeQName2String(type));
return attrs;
}
/**
* Invoked to do the actual serialization of the qName (called by serialize above).
* additional attributes that will be serialized with the qName.
* @param elemQName is the QName of the element
* @param attributes are additional attributes
* @param value is the object to serialize
* @param xmlType (optional) is the desired type QName.
* @param sendType indicates whether the xsi:type attribute should be set.
*/
private void serializeActual(QName elemQName,
Attributes attributes,
Object value,
QName xmlType,
Class javaClass,
Boolean sendType)
throws IOException
{
boolean shouldSendType = (sendType == null) ? shouldSendXSIType() :
sendType.booleanValue();
if (value != null) {
TypeMapping tm = getTypeMapping();
if (tm == null) {
throw new IOException(
Messages.getMessage("noSerializer00",
value.getClass().getName(),
"" + this));
}
// Set currentXMLType to the one desired one.
// Note for maxOccurs usage this xmlType is the
// type of the component not the type of the array.
currentXMLType = xmlType;
// if we're looking for xsd:anyType, accept anything...
if (Constants.equals(Constants.XSD_ANYTYPE,xmlType)){
xmlType = null;
shouldSendType = true;
}
// Try getting a serializer for the prefered xmlType
QNameHolder actualXMLType = new QNameHolder();
Class javaType = getActualJavaClass(xmlType, javaClass, value);
Serializer ser = getSerializer(javaType, xmlType,
actualXMLType);
if ( ser != null ) {
// Send the xmlType if indicated or if
// the actual xmlType is different than the
// prefered xmlType
if (shouldSendType ||
(xmlType != null &&
(!xmlType.equals(actualXMLType.value)))) {
if(!isEncoded()) {
if (Constants.isSOAP_ENC(actualXMLType.value.getNamespaceURI())) {
// Don't write SOAP_ENC types (i.e. Array) if we're not using encoding
} else if (javaType.isPrimitive() && javaClass != null && JavaUtils.getWrapperClass(javaType) == javaClass) {
// Don't write xsi:type when serializing primitive wrapper value as primitive type.
}
else {
if(!(javaType.isArray() && xmlType != null && Constants.isSchemaXSD(xmlType.getNamespaceURI())) ) {
writeXMLType = actualXMLType.value;
}
}
} else {
writeXMLType = actualXMLType.value;
}
}
// -----------------
// NOTE: I have seen doc/lit tests that use
// the type name as the element name in multi-ref cases
// (for example <soapenc:Array ... >)
// In such cases the xsi:type is not passed along.
// -----------------
// The multiref QName is our own fake name.
// It may be beneficial to set the name to the
// type name, but I didn't see any improvements
// in the interop tests.
//if (name.equals(multirefQName) && type != null)
// name = type;
ser.serialize(elemQName, attributes, value, this);
return;
}
throw new IOException(Messages.getMessage("noSerializer00",
value.getClass().getName(), "" + tm));
}
// !!! Write out a generic null, or get type info from somewhere else?
}
/**
* Returns the java class for serialization.
* If the xmlType is xsd:anyType or javaType is array or javaType is java.lang.Object
* the java class for serialization is the class of obj.
* If the obj is not array and the obj's class does not match with the javaType,
* the java class for serialization is the javaType.
* Otherwise, the java class for serialization is the obj's class.
*
* @param xmlType the qname of xml type
* @param javaType the java class from serializer
* @param obj the object to serialize
* @return the java class for serialization
*/
private Class getActualJavaClass(QName xmlType, Class javaType, Object obj) {
Class cls = obj.getClass();
if ((xmlType != null
&& Constants.isSchemaXSD(xmlType.getNamespaceURI()) && "anyType".equals(xmlType.getLocalPart()))
|| (javaType != null
&& (javaType.isArray() || javaType == Object.class))) {
return cls;
}
if (javaType != null && !javaType.isAssignableFrom(cls) && !cls.isArray()) {
return javaType;
}
return cls;
}
private Serializer getSerializerFromClass(Class javaType, QName qname) {
Serializer serializer = null;
try {
Method method =
MethodCache.getInstance().getMethod(javaType,
SERIALIZER_METHOD,
SERIALIZER_CLASSES);
if (method != null) {
serializer = (Serializer) method.invoke(null,
new Object[] {getEncodingStyle(), javaType, qname});
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return serializer;
}
/**
* Get the currently prefered xmlType
* @return QName of xmlType or null
*/
public QName getCurrentXMLType() {
return currentXMLType;
}
/**
* Walk the interfaces of a class looking for a serializer for that
* interface. Include any parent interfaces in the search also.
*
*/
private SerializerFactory getSerializerFactoryFromInterface(Class javaType,
QName xmlType,
TypeMapping tm)
{
SerializerFactory serFactory = null ;
Class [] interfaces = javaType.getInterfaces();
if (interfaces != null) {
for (int i = 0; i < interfaces.length; i++) {
Class iface = interfaces[i];
serFactory = (SerializerFactory) tm.getSerializer(iface,
xmlType);
if (serFactory == null)
serFactory = getSerializerFactoryFromInterface(iface, xmlType, tm);
if (serFactory != null)
break;
}
}
return serFactory;
}
/**
* getSerializer
* Attempts to get a serializer for the indicated javaType and xmlType.
* @param javaType is the type of the object
* @param xmlType is the preferred qname type.
* @param actualXMLType is set to a QNameHolder or null.
* If a QNameHolder, the actual xmlType is returned.
* @return found class/serializer or null
**/
private Serializer getSerializer(Class javaType, QName xmlType,
QNameHolder actualXMLType) {
if (log.isDebugEnabled()) {
log.debug("Getting serializer for javaType=" + javaType + " and xmlType=" + xmlType);
}
SerializerFactory serFactory = null ;
TypeMapping tm = getTypeMapping();
if (actualXMLType != null) {
actualXMLType.value = null;
}
while (javaType != null) {
// check type mapping
serFactory = (SerializerFactory) tm.getSerializer(javaType, xmlType);
if (serFactory != null) {
break;
}
// check the class for serializer
Serializer serializer = getSerializerFromClass(javaType, xmlType);
if (serializer != null) {
if (actualXMLType != null) {
TypeDesc typedesc = TypeDesc.getTypeDescForClass(javaType);
if (typedesc != null) {
actualXMLType.value = typedesc.getXmlType();
}
}
return serializer;
}
// Walk my interfaces...
serFactory = getSerializerFactoryFromInterface(javaType, xmlType, tm);
if (serFactory != null) {
break;
}
// Finally, head to my superclass
javaType = javaType.getSuperclass();
}
// Using the serialization factory, create a serializer
Serializer ser = null;
if ( serFactory != null ) {
ser = (Serializer) serFactory.getSerializerAs(Constants.AXIS_SAX);
if (actualXMLType != null) {
// Get the actual qname xmlType from the factory.
// If not found via the factory, fall back to a less
// performant solution.
if (serFactory instanceof BaseSerializerFactory) {
actualXMLType.value =
((BaseSerializerFactory) serFactory).getXMLType();
}
boolean encoded = isEncoded();
if (actualXMLType.value == null ||
(!encoded &&
(actualXMLType.value.equals(Constants.SOAP_ARRAY) ||
actualXMLType.value.equals(Constants.SOAP_ARRAY12)))) {
actualXMLType.value = tm.getXMLType(javaType,
xmlType,
encoded);
}
}
}
if (log.isDebugEnabled()) {
log.debug("Serializer is " + ser);
if (actualXMLType != null) {
log.debug("Actual XML type is " + actualXMLType.value);
}
}
return ser;
}
public String getValueAsString(Object value, QName xmlType, Class javaClass) throws IOException {
Class cls = value.getClass();
cls = getActualJavaClass(xmlType, javaClass, value);
Serializer ser = getSerializer(cls, xmlType, null);
// The java type is an array, but we need a simple type.
if (ser instanceof ArraySerializer)
{
SimpleListSerializerFactory factory =
new SimpleListSerializerFactory(cls, xmlType);
ser = (Serializer)
factory.getSerializerAs(getEncodingStyle());
}
if (!(ser instanceof SimpleValueSerializer)) {
throw new IOException(
Messages.getMessage("needSimpleValueSer",
ser.getClass().getName()));
}
SimpleValueSerializer simpleSer = (SimpleValueSerializer)ser;
return simpleSer.getValueAsString(value, this);
}
public void setWriteXMLType(QName type) {
writeXMLType = type;
}
public XMLEncoder getEncoder() {
if(encoder == null) {
encoder = XMLUtils.getXMLEncoder(encoding);
}
return encoder;
}
/**
* get the encoding for the serialization
* @return
*/
public String getEncoding() {
return encoding;
}
/**
* set the encoding for the serialization
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public QName getItemQName() {
return itemQName;
}
public void setItemQName(QName itemQName) {
this.itemQName = itemQName;
}
public QName getItemType() {
return itemType;
}
public void setItemType(QName itemType) {
this.itemType = itemType;
}
} | 7,477 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ArrayDeserializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* DeserializerFactory for arrays
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class ArrayDeserializerFactory extends BaseDeserializerFactory {
private QName componentXmlType;
public ArrayDeserializerFactory() {
super(ArrayDeserializer.class);
}
/**
* Constructor
* @param componentXmlType the desired component type for this deser
*/
public ArrayDeserializerFactory(QName componentXmlType) {
super(ArrayDeserializer.class);
this.componentXmlType = componentXmlType;
}
/**
* getDeserializerAs() is overloaded here in order to set the default
* item type on the ArrayDeserializers we create.
*
* @param mechanismType
* @return
*/
public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType) {
ArrayDeserializer dser = (ArrayDeserializer) super.getDeserializerAs(mechanismType);
dser.defaultItemType = componentXmlType;
return dser;
}
public void setComponentType(QName componentType) {
componentXmlType = componentType;
}
} | 7,478 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BaseSerializerFactory.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.encoding.ser;
import org.apache.axis.Constants;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.encoding.SerializerFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Vector;
/**
* Base class for Axis Serialization Factory classes for code reuse
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public abstract class BaseSerializerFactory extends BaseFactory
implements SerializerFactory {
protected static Log log =
LogFactory.getLog(BaseSerializerFactory.class.getName());
transient static Vector mechanisms = null;
protected Class serClass = null;
protected QName xmlType = null;
protected Class javaType = null;
transient protected Serializer ser = null;
transient protected Constructor serClassConstructor = null;
transient protected Method getSerializer = null;
/**
* Constructor
* @param serClass is the class of the Serializer
* Sharing is only valid for xml primitives.
*/
public BaseSerializerFactory(Class serClass) {
if (!Serializer.class.isAssignableFrom(serClass)) {
throw new ClassCastException(
Messages.getMessage("BadImplementation00",
serClass.getName(),
Serializer.class.getName()));
}
this.serClass = serClass;
}
public BaseSerializerFactory(Class serClass,
QName xmlType, Class javaType) {
this(serClass);
this.xmlType = xmlType;
this.javaType = javaType;
}
public javax.xml.rpc.encoding.Serializer
getSerializerAs(String mechanismType)
throws JAXRPCException {
synchronized (this) {
if (ser==null) {
ser = getSerializerAsInternal(mechanismType);
}
return ser;
}
}
protected Serializer getSerializerAsInternal(String mechanismType)
throws JAXRPCException {
// Try getting a specialized Serializer
Serializer serializer = getSpecialized(mechanismType);
// Try getting a general purpose Serializer via constructor
// invocation
if (serializer == null) {
serializer = getGeneralPurpose(mechanismType);
}
try {
// If not successfull, try newInstance
if (serializer == null) {
serializer = (Serializer) serClass.newInstance();
}
} catch (Exception e) {
throw new JAXRPCException(
Messages.getMessage("CantGetSerializer",
serClass.getName()),
e);
}
return serializer;
}
/**
* Obtains a serializer by invoking <constructor>(javaType, xmlType)
* on the serClass.
*/
protected Serializer getGeneralPurpose(String mechanismType) {
if (javaType != null && xmlType != null) {
Constructor serClassConstructor = getSerClassConstructor();
if (serClassConstructor != null) {
try {
return (Serializer)
serClassConstructor.newInstance(
new Object[] {javaType, xmlType});
} catch (InstantiationException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (IllegalAccessException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (InvocationTargetException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
}
}
}
return null;
}
private static final Class[] CLASS_QNAME_CLASS = new Class[] { Class.class, QName.class };
/**
* return constructor for class if any
*/
private Constructor getConstructor(Class clazz) {
try {
return clazz.getConstructor(CLASS_QNAME_CLASS);
} catch (NoSuchMethodException e) {}
return null;
}
/**
* Obtains a serializer by invoking getSerializer method in the
* javaType class or its Helper class.
*/
protected Serializer getSpecialized(String mechanismType) {
if (javaType != null && xmlType != null) {
Method getSerializer = getGetSerializer();
if (getSerializer != null) {
try {
return (Serializer)
getSerializer.invoke(
null,
new Object[] {mechanismType,
javaType,
xmlType});
} catch (IllegalAccessException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (InvocationTargetException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
}
}
}
return null;
}
/**
* Returns a list of all XML processing mechanism types supported
* by this SerializerFactory.
*
* @return List of unique identifiers for the supported XML
* processing mechanism types
*/
public Iterator getSupportedMechanismTypes() {
if (mechanisms == null) {
mechanisms = new Vector(1);
mechanisms.add(Constants.AXIS_SAX);
}
return mechanisms.iterator();
}
/**
* get xmlType
* @return xmlType QName for this factory
*/
public QName getXMLType() {
return xmlType;
}
/**
* get javaType
* @return javaType Class for this factory
*/
public Class getJavaType() {
return javaType;
}
/**
* Utility method that intospects on a factory class to decide how to
* create the factory. Tries in the following order:
* public static create(Class javaType, QName xmlType)
* public <constructor>(Class javaType, QName xmlType)
* public <constructor>()
* @param factory class
* @param xmlType
* @param javaType
*/
public static SerializerFactory createFactory(Class factory,
Class javaType,
QName xmlType) {
if (factory == null) {
return null;
}
try {
if (factory == BeanSerializerFactory.class) {
return new BeanSerializerFactory(javaType, xmlType);
} else if (factory == SimpleSerializerFactory.class) {
return new SimpleSerializerFactory(javaType, xmlType);
} else if (factory == EnumSerializerFactory.class) {
return new EnumSerializerFactory(javaType, xmlType);
} else if (factory == ElementSerializerFactory.class) {
return new ElementSerializerFactory();
} else if (factory == SimpleListSerializerFactory.class) {
return new SimpleListSerializerFactory(javaType, xmlType);
}
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
return null;
}
SerializerFactory sf = null;
try {
Method method =
factory.getMethod("create", CLASS_QNAME_CLASS);
sf = (SerializerFactory)
method.invoke(null,
new Object[] {javaType, xmlType});
} catch (NoSuchMethodException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (IllegalAccessException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (InvocationTargetException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
}
if (sf == null) {
try {
Constructor constructor =
factory.getConstructor(CLASS_QNAME_CLASS);
sf = (SerializerFactory)
constructor.newInstance(
new Object[] {javaType, xmlType});
} catch (NoSuchMethodException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (InstantiationException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (IllegalAccessException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
} catch (InvocationTargetException e) {
if(log.isDebugEnabled()) {
log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e);
}
}
}
if (sf == null) {
try {
sf = (SerializerFactory) factory.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {}
}
return sf;
}
/**
* Returns the getSerializer.
* @return Method
*/
protected Method getGetSerializer() {
if (getSerializer == null) {
getSerializer = getMethod(javaType, "getSerializer");
}
return getSerializer;
}
/**
* Returns the serClassConstructor.
* @return Constructor
*/
protected Constructor getSerClassConstructor() {
if (serClassConstructor == null) {
serClassConstructor = getConstructor(serClass);
}
return serClassConstructor;
}
}
| 7,479 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/OctetStreamDataHandlerSerializer.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.encoding.ser;
import org.apache.axis.attachments.OctetStream;
import org.apache.axis.attachments.OctetStreamDataSource;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.SerializationContext;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import java.io.IOException;
/**
* application/octet-stream DataHandler Serializer
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class OctetStreamDataHandlerSerializer extends JAFDataHandlerSerializer {
protected static Log log =
LogFactory.getLog(OctetStreamDataHandlerSerializer.class.getName());
/**
* Serialize a Source DataHandler quantity.
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException {
DataHandler dh = new DataHandler(
new OctetStreamDataSource("source", (OctetStream) value));
super.serialize(name, attributes, dh, context);
} // serialize
} // class PlainTextDataHandlerSerializer
| 7,480 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DateDeserializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* A DateDeserializer Factory
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class DateDeserializerFactory extends BaseDeserializerFactory {
public DateDeserializerFactory(Class javaType, QName xmlType) {
super(DateDeserializer.class, xmlType, javaType);
}
}
| 7,481 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/JAFDataHandlerSerializerFactory.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.encoding.ser;
import org.apache.axis.attachments.OctetStream;
import javax.mail.internet.MimeMultipart;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import java.awt.*;
/**
* A JAFDataHandlerSerializer Factory
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class JAFDataHandlerSerializerFactory extends BaseSerializerFactory {
public JAFDataHandlerSerializerFactory(Class javaType, QName xmlType) {
super(getSerializerClass(javaType, xmlType), xmlType, javaType);
}
public JAFDataHandlerSerializerFactory() {
super(JAFDataHandlerSerializer.class);
}
private static Class getSerializerClass(Class javaType, QName xmlType) {
Class ser;
if (Image.class.isAssignableFrom(javaType)) {
ser = ImageDataHandlerSerializer.class;
}
else if (String.class.isAssignableFrom(javaType)) {
ser = PlainTextDataHandlerSerializer.class;
}
else if (Source.class.isAssignableFrom(javaType)) {
ser = SourceDataHandlerSerializer.class;
}
else if (MimeMultipart.class.isAssignableFrom(javaType)) {
ser = MimeMultipartDataHandlerSerializer.class;
}
else if (OctetStream.class.isAssignableFrom(javaType)) {
ser = OctetStreamDataHandlerSerializer.class;
}
else {
ser = JAFDataHandlerSerializer.class;
}
return ser;
} // getSerializerClass
}
| 7,482 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ArraySerializer.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.encoding.ser;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
import org.apache.axis.AxisEngine;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.constants.Use;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.encoding.SerializerFactory;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.schema.SchemaVersion;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.wsdl.fromJava.Types;
import org.apache.commons.logging.Log;
/**
* An ArraySerializer handles serializing of arrays.
*
* Some code borrowed from ApacheSOAP - thanks to Matt Duftler!
*
* @author Glen Daniels (gdaniels@apache.org)
*
* Multi-reference stuff:
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class ArraySerializer implements Serializer
{
QName xmlType = null;
Class javaType = null;
QName componentType = null;
QName componentQName = null;
/**
* Constructor
*
*/
public ArraySerializer(Class javaType, QName xmlType) {
this.javaType = javaType;
this.xmlType = xmlType;
}
/**
* Constructor
* Special constructor that takes the component type of the array.
*/
public ArraySerializer(Class javaType, QName xmlType, QName componentType) {
this(javaType, xmlType);
this.componentType = componentType;
}
/**
* Constructor
* Special constructor that takes the component type and QName of the array.
*/
public ArraySerializer(Class javaType, QName xmlType, QName componentType, QName componentQName) {
this(javaType, xmlType, componentType);
this.componentQName = componentQName;
}
protected static Log log =
LogFactory.getLog(ArraySerializer.class.getName());
/**
* Serialize an element that is an array.
* @param name is the element name
* @param attributes are the attributes...serialize is free to add more.
* @param value is the value
* @param context is the SerializationContext
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException
{
if (value == null)
throw new IOException(Messages.getMessage("cantDoNullArray00"));
MessageContext msgContext = context.getMessageContext();
SchemaVersion schema = SchemaVersion.SCHEMA_2001;
SOAPConstants soap = SOAPConstants.SOAP11_CONSTANTS;
boolean encoded = context.isEncoded();
if (msgContext != null) {
schema = msgContext.getSchemaVersion();
soap = msgContext.getSOAPConstants();
}
Class cls = value.getClass();
Collection list = null;
if (!cls.isArray()) {
if (!(value instanceof Collection)) {
throw new IOException(
Messages.getMessage("cantSerialize00", cls.getName()));
}
list = (Collection)value;
}
// Get the componentType of the array/list
Class componentClass;
if (list == null) {
componentClass = cls.getComponentType();
} else {
componentClass = Object.class;
}
// Get the QName of the componentType
// if it wasn't passed in from the constructor
QName componentTypeQName = this.componentType;
// Check to see if componentType is also an array.
// If so, set the componentType to the most nested non-array
// componentType. Increase the dims string by "[]"
// each time through the loop.
// Note from Rich Scheuerle:
// This won't handle Lists of Lists or
// arrays of Lists....only arrays of arrays.
String dims = "";
if (componentTypeQName != null) {
// if we have a Type QName at this point,
// this is because ArraySerializer has been instanciated with it
TypeMapping tm = context.getTypeMapping();
SerializerFactory factory = (SerializerFactory) tm.getSerializer(
componentClass, componentTypeQName);
while (componentClass.isArray()
&& factory instanceof ArraySerializerFactory) {
ArraySerializerFactory asf = (ArraySerializerFactory) factory;
componentClass = componentClass.getComponentType();
QName componentType = null;
if (asf.getComponentType() != null) {
componentType = asf.getComponentType();
if(encoded) {
componentTypeQName = componentType;
}
}
// update factory with the new values
factory = (SerializerFactory) tm.getSerializer(componentClass,
componentType);
if (soap == SOAPConstants.SOAP12_CONSTANTS)
dims += "* ";
else
dims += "[]";
}
} else {
// compatibility mode
while (componentClass.isArray()) {
componentClass = componentClass.getComponentType();
if (soap == SOAPConstants.SOAP12_CONSTANTS)
dims += "* ";
else
dims += "[]";
}
}
// Try the current XML type from the context
if (componentTypeQName == null) {
componentTypeQName = context.getCurrentXMLType();
if (componentTypeQName != null) {
if ((componentTypeQName.equals(xmlType) ||
componentTypeQName.equals(Constants.XSD_ANYTYPE) ||
componentTypeQName.equals(soap.getArrayType()))) {
componentTypeQName = null;
}
}
}
if (componentTypeQName == null) {
componentTypeQName = context.getItemType();
}
// Then check the type mapping for the class
if (componentTypeQName == null) {
componentTypeQName = context.getQNameForClass(componentClass);
}
// If still not found, look at the super classes
if (componentTypeQName == null) {
Class searchCls = componentClass;
while(searchCls != null && componentTypeQName == null) {
searchCls = searchCls.getSuperclass();
componentTypeQName = context.getQNameForClass(searchCls);
}
if (componentTypeQName != null) {
componentClass = searchCls;
}
}
// Still can't find it? Throw an error.
if (componentTypeQName == null) {
throw new IOException(
Messages.getMessage("noType00", componentClass.getName()));
}
int len = (list == null) ? Array.getLength(value) : list.size();
String arrayType = "";
int dim2Len = -1;
if (encoded) {
if (soap == SOAPConstants.SOAP12_CONSTANTS) {
arrayType = dims + len;
} else {
arrayType = dims + "[" + len + "]";
}
// Discover whether array can be serialized directly as a two-dimensional
// array (i.e. arrayType=int[2,3]) versus an array of arrays.
// Benefits:
// - Less text passed on the wire.
// - Easier to read wire format
// - Tests the deserialization of multi-dimensional arrays.
// Drawbacks:
// - Is not safe! It is possible that the arrays are multiply
// referenced. Transforming into a 2-dim array will cause the
// multi-referenced information to be lost. Plus there is no
// way to determine whether the arrays are multi-referenced.
// - .NET currently (Dec 2002) does not support 2D SOAP-encoded arrays
//
// OLD Comment as to why this was ENABLED:
// It is necessary for
// interoperability (echo2DStringArray). It is 'safe' for now
// because Axis treats arrays as non multi-ref (see the note
// in SerializationContext.isPrimitive(...) )
// More complicated processing is necessary for 3-dim arrays, etc.
//
// Axis 1.1 - December 2002
// Turned this OFF because Microsoft .NET can not deserialize
// multi-dimensional SOAP-encoded arrays, and this interopability
// is pretty high visibility. Make it a global configuration parameter:
// <parameter name="enable2DArrayEncoding" value="true"/> (tomj)
//
// Check the message context to see if we should turn 2D processing ON
// Default is OFF
boolean enable2Dim = false;
// Vidyanand : added this check
if( msgContext != null ) {
enable2Dim = JavaUtils.isTrueExplicitly(msgContext.getProperty(
AxisEngine.PROP_TWOD_ARRAY_ENCODING));
}
if (enable2Dim && !dims.equals("")) {
if (cls.isArray() && len > 0) {
boolean okay = true;
// Make sure all of the component arrays are the same size
for (int i=0; i < len && okay; i++) {
Object elementValue = Array.get(value, i);
if (elementValue == null)
okay = false;
else if (dim2Len < 0) {
dim2Len = Array.getLength(elementValue);
if (dim2Len <= 0) {
okay = false;
}
} else if (dim2Len != Array.getLength(elementValue)) {
okay = false;
}
}
// Update the arrayType to use mult-dim array encoding
if (okay) {
dims = dims.substring(0, dims.length()-2);
if (soap == SOAPConstants.SOAP12_CONSTANTS)
arrayType = dims + len + " " + dim2Len;
else
arrayType = dims + "[" + len + "," + dim2Len + "]";
} else {
dim2Len = -1;
}
}
}
}
// Need to distinguish if this is array processing for an
// actual schema array or for a maxOccurs usage.
// For the maxOccurs case, the currentXMLType of the context is
// the same as the componentTypeQName.
QName itemQName = context.getItemQName();
boolean maxOccursUsage = !encoded && itemQName == null &&
componentTypeQName.equals(context.getCurrentXMLType());
if (encoded) {
AttributesImpl attrs;
if (attributes == null) {
attrs = new AttributesImpl();
} else if (attributes instanceof AttributesImpl) {
attrs = (AttributesImpl)attributes;
} else {
attrs = new AttributesImpl(attributes);
}
String compType = context.attributeQName2String(componentTypeQName);
if (attrs.getIndex(soap.getEncodingURI(), soap.getAttrItemType()) == -1) {
String encprefix =
context.getPrefixForURI(soap.getEncodingURI());
if (soap != SOAPConstants.SOAP12_CONSTANTS) {
compType = compType + arrayType;
attrs.addAttribute(soap.getEncodingURI(),
soap.getAttrItemType(),
encprefix + ":arrayType",
"CDATA",
compType);
} else {
attrs.addAttribute(soap.getEncodingURI(),
soap.getAttrItemType(),
encprefix + ":itemType",
"CDATA",
compType);
attrs.addAttribute(soap.getEncodingURI(),
"arraySize",
encprefix + ":arraySize",
"CDATA",
arrayType);
}
}
// Force type to be SOAP_ARRAY for all array serialization.
//
// There are two choices here:
// Force the type to type=SOAP_ARRAY
// Pros: More interop test successes.
// Cons: Since we have specific type information it
// is more correct to use it. Plus the specific
// type information may be important on the
// server side to disambiguate overloaded operations.
// Use the specific type information:
// Pros: The specific type information is more correct
// and may be useful for operation overloading.
// Cons: More interop test failures (as of 2/6/2002).
//
String qname =
context.getPrefixForURI(schema.getXsiURI(),
"xsi") + ":type";
QName soapArray;
if (soap == SOAPConstants.SOAP12_CONSTANTS) {
soapArray = Constants.SOAP_ARRAY12;
} else {
soapArray = Constants.SOAP_ARRAY;
}
int typeI = attrs.getIndex(schema.getXsiURI(),
"type");
if (typeI != -1) {
attrs.setAttribute(typeI,
schema.getXsiURI(),
"type",
qname,
"CDATA",
context.qName2String(soapArray));
} else {
attrs.addAttribute(schema.getXsiURI(),
"type",
qname,
"CDATA",
context.qName2String(soapArray));
}
attributes = attrs;
}
// For the maxOccurs case, each item is named with the QName
// we got in the arguments. For normal array case, we write an element with
// that QName, and then serialize each item as <item>
QName elementName = name;
Attributes serializeAttr = attributes;
if (!maxOccursUsage) {
serializeAttr = null; // since we are putting them here
context.startElement(name, attributes);
if (itemQName != null)
elementName = itemQName;
else if(componentQName != null)
elementName = componentQName;
}
if (dim2Len < 0) {
// Normal case, serialize each array element
if (list == null) {
for (int index = 0; index < len; index++) {
Object aValue = Array.get(value, index);
// Serialize the element.
context.serialize(elementName,
(serializeAttr == null ?
serializeAttr : new AttributesImpl(serializeAttr)),
aValue,
componentTypeQName, componentClass); // prefered type QName
}
} else {
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object aValue = iterator.next();
// Serialize the element.
context.serialize(elementName,
(serializeAttr == null ?
serializeAttr : new AttributesImpl(serializeAttr)),
aValue,
componentTypeQName, componentClass); // prefered type QName
}
}
} else {
// Serialize as a 2 dimensional array
for (int index = 0; index < len; index++) {
for (int index2 = 0; index2 < dim2Len; index2++) {
Object aValue = Array.get(Array.get(value, index), index2);
context.serialize(elementName, null, aValue, componentTypeQName, componentClass);
}
}
}
if (!maxOccursUsage)
context.endElement();
}
public String getMechanismType() { return Constants.AXIS_SAX; }
private 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;
}
}
/**
* Return XML schema for the specified type, suitable for insertion into
* the <types> element of a WSDL document, or underneath an
* <element> or <attribute> declaration.
*
* @param javaType the Java Class we're writing out schema for
* @param types the Java2WSDL Types object which holds the context
* for the WSDL being generated.
* @return a type element containing a schema simpleType/complexType
* @see org.apache.axis.wsdl.fromJava.Types
*/
public Element writeSchema(Class javaType, Types types) throws Exception {
boolean encoded = true;
MessageContext mc = MessageContext.getCurrentContext();
if (mc != null) {
encoded = mc.isEncoded();
} else {
encoded = types.getServiceDesc().getUse() == Use.ENCODED;
}
if (!encoded) {
Class cType = Object.class;
if (javaType.isArray()) {
cType = javaType.getComponentType();
}
String typeName = types.writeType(cType);
return types.createLiteralArrayElement(typeName, null);
}
// If an array the component type should be processed first
String componentTypeName = null;
Class componentType = null;
if (isArray(javaType)) {
String dimString = "[]";
componentType = getComponentType(javaType);
while (isArray(componentType)) {
dimString += "[]";
componentType = getComponentType(componentType);
}
types.writeType(componentType,null);
componentTypeName =
types.getQNameString(types.getTypeQName(componentType)) +
dimString;
}
// Use Types helper method to actually create the complexType
return types.createArrayElement(componentTypeName);
}
}
| 7,483 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SourceDataHandlerSerializer.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.encoding.ser;
import org.apache.axis.attachments.SourceDataSource;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
/**
* SourceDataHandler Serializer
* @author Russell Butek (butek@us.ibm.com)
*/
public class SourceDataHandlerSerializer extends JAFDataHandlerSerializer {
protected static Log log =
LogFactory.getLog(SourceDataHandlerSerializer.class.getName());
/**
* Serialize a Source DataHandler quantity.
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException
{
if (value != null) {
if (!(value instanceof StreamSource)) {
throw new IOException(Messages.getMessage("badSource",
value.getClass().getName()));
}
DataHandler dh = new DataHandler(new SourceDataSource("source",
"text/xml", (StreamSource) value));
super.serialize(name, attributes, dh, context);
}
} // serialize
} // class SourceDataHandlerSerializer
| 7,484 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DocumentDeserializer.java | package org.apache.axis.encoding.ser;
/*
* 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.
*/
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.DeserializerImpl;
import org.apache.axis.message.MessageElement;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import org.xml.sax.SAXException;
import java.util.List;
/**
* Deserializer for DOM Document
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class DocumentDeserializer extends DeserializerImpl
{
protected static Log log =
LogFactory.getLog(DocumentDeserializer.class.getName());
public static final String DESERIALIZE_CURRENT_ELEMENT = "DeserializeCurrentElement";
public final void onEndElement(String namespace, String localName,
DeserializationContext context)
throws SAXException
{
try {
MessageElement msgElem = context.getCurElement();
if ( msgElem != null ) {
MessageContext messageContext = context.getMessageContext();
Boolean currentElement = (Boolean) messageContext.getProperty(DESERIALIZE_CURRENT_ELEMENT);
if (currentElement != null && currentElement.booleanValue()) {
value = msgElem.getAsDocument();
messageContext.setProperty(DESERIALIZE_CURRENT_ELEMENT, Boolean.FALSE);
return;
}
List children = msgElem.getChildren();
if ( children != null ) {
msgElem = (MessageElement) children.get(0);
if ( msgElem != null )
value = msgElem.getAsDocument();
}
}
}
catch( Exception exp ) {
log.error(Messages.getMessage("exception00"), exp);
throw new SAXException( exp );
}
}
}
| 7,485 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/TimeSerializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* SerializerFactory for Time
* @author Florent Benoit
*/
public class TimeSerializerFactory extends BaseSerializerFactory {
public TimeSerializerFactory(Class javaType, QName xmlType) {
super(TimeSerializer.class, xmlType, javaType); // true indicates shared
// class
}
} | 7,486 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/HexDeserializer.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.encoding.ser;
import org.apache.axis.types.HexBinary;
import javax.xml.namespace.QName;
/**
* Deserializer for hexBinary.
*
* @author Davanum Srinivas (dims@yahoo.com)
* Modified by @author Rich scheuerle (scheu@us.ibm.com)
* @see <a href="http://www.w3.org/TR/xmlschema-2/#hexBinary">XML Schema 3.2.16</a>
*/
public class HexDeserializer extends SimpleDeserializer {
public HexDeserializer(Class javaType, QName xmlType) {
super(javaType, xmlType);
}
/**
* Convert the string that has been accumulated into an Object. Subclasses
* may override this. Note that if the javaType is a primitive, the returned
* object is a wrapper class.
* @param source the serialized value to be deserialized
* @throws Exception any exception thrown by this method will be wrapped
*/
public Object makeValue(String source) throws Exception {
Object result;
if (javaType == byte[].class) {
result = HexBinary.decode(source);
} else {
result = new HexBinary(source);
}
if (result == null) result = new HexBinary("");
return result;
}
}
| 7,487 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleSerializer.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.encoding.ser;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.description.FieldDesc;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.SimpleValueSerializer;
import org.apache.axis.encoding.SimpleType;
import org.apache.axis.utils.BeanPropertyDescriptor;
import org.apache.axis.utils.BeanUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.wsdl.fromJava.Types;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.namespace.QName;
import java.io.IOException;
/**
* Serializer for primitives and anything simple whose value is obtained with toString()
*
* @author Rich Scheuerle (dims@yahoo.com)
*/
public class SimpleSerializer implements SimpleValueSerializer {
public QName xmlType;
public Class javaType;
private BeanPropertyDescriptor[] propertyDescriptor = null;
private TypeDesc typeDesc = null;
public static final String VALUE_PROPERTY = "_value";
public SimpleSerializer(Class javaType, QName xmlType) {
this.xmlType = xmlType;
this.javaType = javaType;
init();
}
public SimpleSerializer(Class javaType, QName xmlType, TypeDesc typeDesc) {
this.xmlType = xmlType;
this.javaType = javaType;
this.typeDesc = typeDesc;
init();
}
/**
* Initialize the typeDesc and propertyDescriptor array.
*/
private void init() {
// Set the typeDesc if not already set
if (typeDesc == null) {
typeDesc = TypeDesc.getTypeDescForClass(javaType);
}
// Get the cached propertyDescriptor from the type or
// generate a fresh one.
if (typeDesc != null) {
propertyDescriptor = typeDesc.getPropertyDescriptors();
} else if (!JavaUtils.isBasic(javaType)) {
propertyDescriptor = BeanUtils.getPd(javaType, null);
}
}
/**
* Serialize a primitive or simple value.
* If the object to serialize is a primitive, the Object value below
* is the associated java.lang class.
* To determine if the original value is a java.lang class or a primitive, consult
* the javaType class.
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException
{
if (value != null && value.getClass() == java.lang.Object.class) {
throw new IOException(Messages.getMessage("cantSerialize02"));
}
// get any attributes
attributes = getObjectAttributes(value, attributes, context);
String valueStr = null;
if (value != null) {
valueStr = getValueAsString(value, context);
}
context.startElement(name, attributes);
if (valueStr != null) {
context.writeSafeString(valueStr);
}
context.endElement();
}
public String getValueAsString(Object value, SerializationContext context) {
// We could have separate serializers/deserializers to take
// care of Float/Double cases, but it makes more sence to
// put them here with the rest of the java lang primitives.
if (value instanceof Float ||
value instanceof Double) {
double data = 0.0;
if (value instanceof Float) {
data = ((Float) value).doubleValue();
} else {
data = ((Double) value).doubleValue();
}
if (Double.isNaN(data)) {
return "NaN";
} else if (data == Double.POSITIVE_INFINITY) {
return "INF";
} else if (data == Double.NEGATIVE_INFINITY) {
return "-INF";
}
} else if (value instanceof QName) {
return context.qName2String((QName)value);
}
if (propertyDescriptor != null && !(value instanceof SimpleType)) {
BeanPropertyDescriptor pd = BeanUtils.getSpecificPD(propertyDescriptor, "_value");
if(pd != null) {
try {
return pd.get(value).toString();
} catch (Exception e) {
}
}
}
return value.toString();
}
private Attributes getObjectAttributes(Object value,
Attributes attributes,
SerializationContext context) {
if (typeDesc != null && !typeDesc.hasAttributes())
return attributes;
AttributesImpl attrs;
if (attributes == null) {
attrs = new AttributesImpl();
} else if (attributes instanceof AttributesImpl) {
attrs = (AttributesImpl)attributes;
} else {
attrs = new AttributesImpl(attributes);
}
try {
// Find each property that is an attribute
// and add it to our attribute list
for (int i = 0;
propertyDescriptor != null && i < propertyDescriptor.length;
i++) {
String propName = propertyDescriptor[i].getName();
if (propName.equals("class"))
continue;
QName qname = null;
if(typeDesc != null) {
FieldDesc field = typeDesc.getFieldByName(propName);
// skip it if its not an attribute
if (field == null || field.isElement())
continue;
qname = field.getXmlName();
} else {
if(propName.equals(VALUE_PROPERTY))
continue;
}
if (qname == null) {
qname = new QName("", propName);
}
if (propertyDescriptor[i].isReadable() &&
!propertyDescriptor[i].isIndexed()) {
// add to our attributes
Object propValue = propertyDescriptor[i].get(value);
// If the property value does not exist, don't serialize
// the attribute. In the future, the decision to serializer
// the attribute may be more sophisticated. For example, don't
// serialize if the attribute matches the default value.
if (propValue != null) {
String propString = getValueAsString(propValue, context);
String namespace = qname.getNamespaceURI();
String localName = qname.getLocalPart();
attrs.addAttribute(namespace,
localName,
context.qName2String(qname),
"CDATA",
propString);
}
}
}
} catch (Exception e) {
// no attributes
return attrs;
}
return attrs;
}
public String getMechanismType() { return Constants.AXIS_SAX; }
/**
* Return XML schema for the specified type, suitable for insertion into
* the <types> element of a WSDL document, or underneath an
* <element> or <attribute> declaration.
*
* @param javaType the Java Class we're writing out schema for
* @param types the Java2WSDL Types object which holds the context
* for the WSDL being generated.
* @return a type element containing a schema simpleType/complexType
* @see org.apache.axis.wsdl.fromJava.Types
*/
public Element writeSchema(Class javaType, Types types) throws Exception {
// ComplexType representation of SimpleType bean class
Element complexType = types.createElement("complexType");
types.writeSchemaTypeDecl(xmlType, complexType);
complexType.setAttribute("name", xmlType.getLocalPart());
// Produce simpleContent extending base type.
Element simpleContent = types.createElement("simpleContent");
complexType.appendChild(simpleContent);
Element extension = types.createElement("extension");
simpleContent.appendChild(extension);
// Get the base type from the "value" element of the bean
String base = "string";
for (int i=0; propertyDescriptor != null && i<propertyDescriptor.length; i++) {
String propName = propertyDescriptor[i].getName();
if (!propName.equals("value")) {
if (typeDesc != null) {
FieldDesc field = typeDesc.getFieldByName(propName);
if (field != null) {
if (field.isElement()) {
// throw?
}
QName qname = field.getXmlName();
if (qname == null) {
// Use the default...
qname = new QName("", propName);
}
// write attribute element
Class fieldType = propertyDescriptor[i].getType();
// Attribute must be a simple type, enum or SimpleType
if (!types.isAcceptableAsAttribute(fieldType)) {
throw new AxisFault(Messages.getMessage("AttrNotSimpleType00",
propName,
fieldType.getName()));
}
// write attribute element
// TODO the attribute name needs to be preserved from the XML
Element elem = types.createAttributeElement(propName,
fieldType,
field.getXmlType(),
false,
extension.getOwnerDocument());
extension.appendChild(elem);
}
}
continue;
}
BeanPropertyDescriptor bpd = propertyDescriptor[i];
Class type = bpd.getType();
// Attribute must extend a simple type, enum or SimpleType
if (!types.isAcceptableAsAttribute(type)) {
throw new AxisFault(Messages.getMessage("AttrNotSimpleType01",
type.getName()));
}
base = types.writeType(type);
extension.setAttribute("base", base);
}
// done
return complexType;
}
}
| 7,488 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleSerializerFactory.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.encoding.ser;
import org.apache.axis.utils.JavaUtils;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
public class SimpleSerializerFactory extends BaseSerializerFactory {
private boolean isBasicType = false;
/**
* Note that the factory is constructed with the QName and xmlType. This is important
* to allow distinction between primitive values and java.lang wrappers.
**/
public SimpleSerializerFactory(Class javaType, QName xmlType) {
super(SimpleSerializer.class, xmlType, javaType);
this.isBasicType = JavaUtils.isBasic(javaType);
}
public javax.xml.rpc.encoding.Serializer getSerializerAs(String mechanismType) throws JAXRPCException {
if (this.isBasicType) {
return new SimpleSerializer(javaType, xmlType);
} else {
return super.getSerializerAs(mechanismType);
}
}
}
| 7,489 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/CalendarDeserializer.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.encoding.ser;
import org.apache.axis.utils.Messages;
import javax.xml.namespace.QName;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* The CalendarSerializer deserializes a dateTime.
* Much of the work is done in the base class.
*
* @author Sam Ruby (rubys@us.ibm.com)
* Modified for JAX-RPC @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class CalendarDeserializer extends SimpleDeserializer {
private static SimpleDateFormat zulu =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// 0123456789 0 123456789
static {
zulu.setTimeZone(TimeZone.getTimeZone("GMT"));
}
/**
* The Deserializer is constructed with the xmlType and
* javaType
*/
public CalendarDeserializer(Class javaType, QName xmlType) {
super(javaType, xmlType);
}
/**
* The simple deserializer provides most of the stuff.
* We just need to override makeValue().
*/
public Object makeValue(String source) {
Calendar calendar = Calendar.getInstance();
Date date;
boolean bc = false;
// validate fixed portion of format
if (source == null || source.length() == 0) {
throw new NumberFormatException(
Messages.getMessage("badDateTime00"));
}
if (source.charAt(0) == '+') {
source = source.substring(1);
}
if (source.charAt(0) == '-') {
source = source.substring(1);
bc = true;
}
if (source.length() < 19) {
throw new NumberFormatException(
Messages.getMessage("badDateTime00"));
}
if (source.charAt(4) != '-' || source.charAt(7) != '-' ||
source.charAt(10) != 'T') {
throw new NumberFormatException(Messages.getMessage("badDate00"));
}
if (source.charAt(13) != ':' || source.charAt(16) != ':') {
throw new NumberFormatException(Messages.getMessage("badTime00"));
}
// convert what we have validated so far
try {
synchronized (zulu) {
date = zulu.parse(source.substring(0, 19) + ".000Z");
}
} catch (Exception e) {
throw new NumberFormatException(e.toString());
}
int pos = 19;
// parse optional milliseconds
if (pos < source.length() && source.charAt(pos) == '.') {
int milliseconds = 0;
int start = ++pos;
while (pos < source.length() &&
Character.isDigit(source.charAt(pos))) {
pos++;
}
String decimal = source.substring(start, pos);
if (decimal.length() == 3) {
milliseconds = Integer.parseInt(decimal);
} else if (decimal.length() < 3) {
milliseconds = Integer.parseInt((decimal + "000")
.substring(0, 3));
} else {
milliseconds = Integer.parseInt(decimal.substring(0, 3));
if (decimal.charAt(3) >= '5') {
++milliseconds;
}
}
// add milliseconds to the current date
date.setTime(date.getTime() + milliseconds);
}
// parse optional timezone
if (pos + 5 < source.length() &&
(source.charAt(pos) == '+' || (source.charAt(pos) == '-'))) {
if (!Character.isDigit(source.charAt(pos + 1)) ||
!Character.isDigit(source.charAt(pos + 2)) ||
source.charAt(pos + 3) != ':' ||
!Character.isDigit(source.charAt(pos + 4)) ||
!Character.isDigit(source.charAt(pos + 5))) {
throw new NumberFormatException(
Messages.getMessage("badTimezone00"));
}
int hours = (source.charAt(pos + 1) - '0') * 10
+ source.charAt(pos + 2) - '0';
int mins = (source.charAt(pos + 4) - '0') * 10
+ source.charAt(pos + 5) - '0';
int milliseconds = (hours * 60 + mins) * 60 * 1000;
// subtract milliseconds from current date to obtain GMT
if (source.charAt(pos) == '+') {
milliseconds = -milliseconds;
}
date.setTime(date.getTime() + milliseconds);
pos += 6;
}
if (pos < source.length() && source.charAt(pos) == 'Z') {
pos++;
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
}
if (pos < source.length()) {
throw new NumberFormatException(Messages.getMessage("badChars00"));
}
calendar.setTime(date);
// support dates before the Christian era
if (bc) {
calendar.set(Calendar.ERA, GregorianCalendar.BC);
}
if (super.javaType == Date.class) {
return date;
} else {
return calendar;
}
}
}
| 7,490 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DocumentSerializer.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.encoding.ser;
import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.utils.Messages;
import org.apache.axis.wsdl.fromJava.Types;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.xml.sax.Attributes;
import javax.xml.namespace.QName;
import java.io.IOException;
/**
* Serializer for DOM Document
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class DocumentSerializer implements Serializer {
/**
* Serialize a DOM Document
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException
{
if (!(value instanceof Document))
throw new IOException(Messages.getMessage("cantSerialize01"));
context.startElement(name, attributes);
Document document = (Document)value;
context.writeDOMElement(document.getDocumentElement());
context.endElement();
}
public String getMechanismType() { return Constants.AXIS_SAX; }
/**
* Return XML schema for the specified type, suitable for insertion into
* the <types> element of a WSDL document, or underneath an
* <element> or <attribute> declaration.
*
* @param javaType the Java Class we're writing out schema for
* @param types the Java2WSDL Types object which holds the context
* for the WSDL being generated.
* @return a type element containing a schema simpleType/complexType
* @see Types
*/
public Element writeSchema(Class javaType, Types types) throws Exception {
return null;
}
}
| 7,491 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SourceDataHandlerDeserializer.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.encoding.ser;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.activation.DataHandler;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
/**
* SourceDataHandler Deserializer
* Modified by Russell Butek (butek@us.ibm.com)
*/
public class SourceDataHandlerDeserializer extends JAFDataHandlerDeserializer {
protected static Log log =
LogFactory.getLog(SourceDataHandlerDeserializer.class.getName());
public void startElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException {
super.startElement(namespace, localName, prefix, attributes, context);
if (getValue() instanceof DataHandler) {
try {
DataHandler dh = (DataHandler) getValue();
StreamSource ss = new StreamSource(dh.getInputStream());
setValue(ss);
}
catch (IOException ioe) {
}
}
} // startElement
} // class SourceDataHandlerDeserializer
| 7,492 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/QNameSerializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* SerializerFactory for QName primitive
*/
public class QNameSerializerFactory extends BaseSerializerFactory {
public QNameSerializerFactory(Class javaType, QName xmlType) {
super(QNameSerializer.class, xmlType, javaType); // true indicates shared class
}
}
| 7,493 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/QNameDeserializer.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.encoding.ser;
import org.apache.axis.encoding.DeserializationContext;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
/**
* The DateSerializer deserializes a Date. Much of the work is done in the
* base class.
*
* @author Sam Ruby (rubys@us.ibm.com)
* Modified for JAX-RPC @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class QNameDeserializer extends SimpleDeserializer {
private DeserializationContext context = null;
/**
* The Deserializer is constructed with the xmlType and
* javaType
*/
public QNameDeserializer(Class javaType, QName xmlType) {
super(javaType, xmlType);
} // ctor
/**
* The simple deserializer provides most of the stuff.
* We just need to override makeValue().
*/
public Object makeValue(String source) {
source = source.trim();
int colon = source.lastIndexOf(":");
String namespace = colon < 0 ? "" :
context.getNamespaceURI(source.substring(0, colon));
String localPart = colon < 0 ? source : source.substring(colon + 1);
return new QName(namespace, localPart);
} // makeValue
public void onStartElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
this.context = context;
} // onStartElement
}
| 7,494 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/Base64DeserializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* DeserializerFactory for hexBinary.
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class Base64DeserializerFactory extends BaseDeserializerFactory {
public Base64DeserializerFactory(Class javaType, QName xmlType) {
super(Base64Deserializer.class, xmlType, javaType);
}
}
| 7,495 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleListDeserializerFactory.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.encoding.ser;
import org.apache.axis.utils.JavaUtils;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import java.io.ObjectStreamException;
import java.lang.reflect.Constructor;
/**
* DeserializerFactory for
* <xsd:simpleType ...>
* <xsd:list itemType="...">
* </xsd:simpleType>
* based on SimpleDeserializerFactory
*
* @author Ias (iasandcb@tmax.co.kr)
*/
public class SimpleListDeserializerFactory extends BaseDeserializerFactory {
private static final Class[] STRING_CLASS =
new Class [] {String.class};
private final Class clazzType;
private transient Constructor constructor = null;
/**
* Note that the factory is constructed with the QName and xmlType. This is important
* to allow distinction between primitive values and java.lang wrappers.
**/
public SimpleListDeserializerFactory(Class javaType, QName xmlType) {
super(SimpleListDeserializer.class, xmlType, javaType.getComponentType());
clazzType = javaType;
Class componentType = javaType.getComponentType();
try {
if (!componentType.isPrimitive()) {
constructor =
componentType.getDeclaredConstructor(STRING_CLASS);
}
else {
Class wrapper = JavaUtils.getWrapperClass(componentType);
if (wrapper != null)
constructor =
wrapper.getDeclaredConstructor(STRING_CLASS);
}
} catch (java.lang.NoSuchMethodException e) {
throw new IllegalArgumentException(e.toString());
}
}
/**
* Get the Deserializer and the set the Constructor so the
* deserializer does not have to do introspection.
*/
public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType)
throws JAXRPCException {
if (javaType == java.lang.Object.class) {
return null;
}
SimpleListDeserializer deser = (SimpleListDeserializer) super.getDeserializerAs(mechanismType);
if (deser != null)
deser.setConstructor(constructor);
return deser;
}
private Object readResolve() throws ObjectStreamException {
return new SimpleListDeserializerFactory(clazzType, xmlType);
}
}
| 7,496 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/EnumDeserializer.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.encoding.ser;
import javax.xml.namespace.QName;
import java.beans.IntrospectionException;
import java.lang.reflect.Method;
import org.apache.axis.utils.cache.MethodCache;
/**
* Deserializer for a JAX-RPC enum.
*
* @author Rich Scheuerle (scheu@us.ibm.com)
* @author Sam Ruby (rubys@us.ibm.com)
*/
public class EnumDeserializer extends SimpleDeserializer {
private Method fromStringMethod = null;
private static final Class[] STRING_CLASS = new Class[] { java.lang.String.class };
public EnumDeserializer(Class javaType, QName xmlType) {
super(javaType, xmlType);
}
public Object makeValue(String source) throws Exception
{
// Invoke the fromString static method to get the Enumeration value
if (isNil)
return null;
if (fromStringMethod == null) {
try {
fromStringMethod = MethodCache.getInstance().getMethod(javaType, "fromString", STRING_CLASS);
} catch (Exception e) {
throw new IntrospectionException(e.toString());
}
}
return fromStringMethod.invoke(null,new Object [] { source });
}
}
| 7,497 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/VectorDeserializerFactory.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.encoding.ser;
import javax.xml.namespace.QName;
/**
* A VectorDeserializer Factory
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class VectorDeserializerFactory extends BaseDeserializerFactory {
public VectorDeserializerFactory(Class javaType, QName xmlType) {
super(VectorDeserializer.class, xmlType, javaType);
}
}
| 7,498 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BeanSerializerFactory.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.encoding.ser;
import java.io.IOException;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.utils.BeanPropertyDescriptor;
import org.apache.axis.utils.BeanUtils;
import org.apache.axis.utils.JavaUtils;
import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
/**
* SerializerFactory for Bean
*
* @author Rich Scheuerle (scheu@us.ibm.com)
*/
public class BeanSerializerFactory extends BaseSerializerFactory {
protected transient TypeDesc typeDesc = null;
protected transient BeanPropertyDescriptor[] propertyDescriptor = null;
public BeanSerializerFactory(Class javaType, QName xmlType) {
super(BeanSerializer.class, xmlType, javaType);
init(javaType);
}
private void init(Class javaType) {
// Sometimes an Enumeration class is registered as a Bean.
// If this is the case, silently switch to the EnumSerializer
if (JavaUtils.isEnumClass(javaType)) {
serClass = EnumSerializer.class;
}
typeDesc = TypeDesc.getTypeDescForClass(javaType);
if (typeDesc != null) {
propertyDescriptor = typeDesc.getPropertyDescriptors();
} else {
propertyDescriptor = BeanUtils.getPd(javaType, null);
}
}
public javax.xml.rpc.encoding.Serializer getSerializerAs(String mechanismType)
throws JAXRPCException {
return (Serializer) super.getSerializerAs(mechanismType);
}
/**
* Optimize construction of a BeanSerializer by caching the
* type and property descriptors.
*/
protected Serializer getGeneralPurpose(String mechanismType) {
if (javaType == null || xmlType == null) {
return super.getGeneralPurpose(mechanismType);
}
if (serClass == EnumSerializer.class) {
return super.getGeneralPurpose(mechanismType);
}
return new BeanSerializer(javaType, xmlType, typeDesc,
propertyDescriptor);
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
init(javaType);
}
}
| 7,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.