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/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap12/TestEncodingStyle.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 Andras Avar (andras.avar@nokia.com)
*/
package test.soap12;
import junit.framework.TestCase;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.Messages;
import javax.xml.namespace.QName;
/**
* Test encodingstyle attribute appearance
*/
public class TestEncodingStyle extends TestCase {
private AxisServer server = null;
public TestEncodingStyle(String name) {
super(name);
server = new AxisServer();
}
private final String ENVELOPE =
"<?xml version=\"1.0\"?>\n" +
"<soap:Envelope " +
"xmlns:soap=\"" + Constants.URI_SOAP12_ENV + "\" " +
"xmlns:xsi=\"" + Constants.URI_DEFAULT_SCHEMA_XSI + "\" " +
"xmlns:xsd=\"" + Constants.URI_DEFAULT_SCHEMA_XSD + "\" ";
private final String HEADER =
">\n" +
"<soap:Header ";
private final String BODY =
"/>\n" +
"<soap:Body ";
private final String FAULT_HEAD =
">\n" +
"<soap:Fault ";
private final String FAULT_DETAIL =
">\n" +
"<soap:Code>" +
"<soap:Value>soap:Sender</soap:Value>" +
"</soap:Code>" +
"<soap:Detail ";
private final String FAULT_TAIL =
">\n" +
"<hello/>" +
"</soap:Detail>" +
"</soap:Fault>";
private final String TAIL =
"</soap:Body>\n" +
"</soap:Envelope>\n";
private final String ENCSTYLE_DEF =
"soap:encodingStyle=\"" + Constants.URI_SOAP12_ENC + "\"";
private final String MESSAGE_HEAD =
">\n" +
"<methodResult xmlns=\"http://tempuri.org/\" ";
private final String MESSAGE =
">\n";
private final String MESSAGE_TAIL =
"</methodResult>\n";
private final String ITEM =
"<item xsi:type=\"xsd:string\">abc</item>\n";
private final String INVALID_ENCSTYLE = "http://invalidencodingstyle.org";
private final String NO_ENCSTYLE = Constants.URI_SOAP12_NOENC;
private final String INVALID_ENCSTYLE_DEF =
"soap:encodingStyle=\"" + INVALID_ENCSTYLE + "\"";
private final String NO_ENCSTYLE_DEF =
"soap:encodingStyle=\"" + NO_ENCSTYLE + "\"";
public boolean deserialize(String req, QName expected_code, String expected_str) throws Exception {
Message message = new Message(req);
MessageContext context = new MessageContext(server);
context.setSOAPConstants(SOAPConstants.SOAP12_CONSTANTS);
context.setProperty(Constants.MC_NO_OPERATION_OK, Boolean.TRUE);
message.setMessageContext(context);
boolean expectedFault = false;
try {
SOAPEnvelope envelope = message.getSOAPEnvelope();
} catch (AxisFault af) {
return af.getFaultString().indexOf(expected_str) != -1 &&
expected_code.equals(af.getFaultCode());
}
return expectedFault;
}
public void testEncStyleInEnvelope() throws Exception {
String req = ENVELOPE + ENCSTYLE_DEF + HEADER + BODY + FAULT_HEAD + FAULT_DETAIL + FAULT_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noEncodingStyleAttrAppear", "Envelope")));
}
public void testEncStyleInHeader() throws Exception {
String req = ENVELOPE + HEADER + ENCSTYLE_DEF + BODY + FAULT_HEAD + FAULT_DETAIL + FAULT_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noEncodingStyleAttrAppear", "Header")));
}
public void testEncStyleInBody() throws Exception {
String req = ENVELOPE + HEADER + BODY + ENCSTYLE_DEF + FAULT_HEAD + FAULT_DETAIL + FAULT_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noEncodingStyleAttrAppear", "Body")));
}
public void testEncStyleInFault() throws Exception {
String req = ENVELOPE + HEADER + BODY + FAULT_HEAD + ENCSTYLE_DEF + FAULT_DETAIL + FAULT_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noEncodingStyleAttrAppear", "Fault")));
}
public void testEncStyleInDetail() throws Exception {
String req = ENVELOPE + HEADER + BODY + FAULT_HEAD + FAULT_DETAIL + ENCSTYLE_DEF + FAULT_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_SENDER,
Messages.getMessage("noEncodingStyleAttrAppear", "Detail")));
}
public void testInvalidEncodingStyle() throws Exception {
String req = ENVELOPE + HEADER + BODY + MESSAGE_HEAD + INVALID_ENCSTYLE_DEF + MESSAGE + ITEM + MESSAGE_TAIL + TAIL;
assertTrue(deserialize(req, Constants.FAULT_SOAP12_DATAENCODINGUNKNOWN,
Messages.getMessage("invalidEncodingStyle")));
}
public void testAcceptUserEncodingStyle() throws Exception {
String req = ENVELOPE + HEADER + BODY + MESSAGE_HEAD + INVALID_ENCSTYLE_DEF + MESSAGE + ITEM + MESSAGE_TAIL + TAIL;
Message message = new Message(req);
MessageContext context = new MessageContext(server);
context.setProperty(Constants.MC_NO_OPERATION_OK, Boolean.TRUE);
// Set the "invalid" encoding style
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.createTypeMapping();
tm.setSupportedEncodings(new String[] { INVALID_ENCSTYLE });
reg.register(INVALID_ENCSTYLE, tm);
context.setSOAPConstants(SOAPConstants.SOAP12_CONSTANTS);
message.setMessageContext(context);
SOAPEnvelope envelope = message.getSOAPEnvelope();
assertTrue(envelope != null);
}
public void testNoEncodingStyle() throws Exception {
String req = ENVELOPE + HEADER + BODY + MESSAGE_HEAD + NO_ENCSTYLE_DEF + MESSAGE + ITEM + MESSAGE_TAIL + TAIL;
assertTrue(deserialize(req, null, null) == false);
}
}
| 7,200 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/SuperBean.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 test.encoding;
import org.apache.axis.description.ElementDesc;
/**
* A simple type with several elements for testing serialization
*/
public class SuperBean {
// Definition of three elements
private String zero;
private String one;
private String two;
/**
* Returns the one.
* @return String
*/
public String getOne() {
return one;
}
/**
* Returns the two.
* @return String
*/
public String getTwo() {
return two;
}
/**
* Returns the zero.
* @return String
*/
public String getZero() {
return zero;
}
/**
* Sets the one.
* @param one The one to set
*/
public void setOne(String one) {
this.one = one;
}
/**
* Sets the two.
* @param two The two to set
*/
public void setTwo(String two) {
this.two = two;
}
/**
* Sets the zero.
* @param zero The zero to set
*/
public void setZero(String zero) {
this.zero = zero;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(SuperBean.class);
static {
org.apache.axis.description.ElementDesc field = new org.apache.axis.description.ElementDesc();
field.setFieldName("zero");
field.setXmlName(new javax.xml.namespace.QName("", "zero"));
field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
field.setNillable(true);
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("one");
field.setXmlName(new javax.xml.namespace.QName("", "one"));
field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
field.setNillable(true);
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("two");
field.setXmlName(new javax.xml.namespace.QName("", "two"));
field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
field.setNillable(true);
typeDesc.addFieldDesc(field);
};
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
} | 7,201 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/DerivatedBean.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 test.encoding;
import org.apache.axis.description.ElementDesc;
/**
* A type used for testing serialization of inherited elements
*/
public class DerivatedBean extends SuperBean {
private String three;
private String four;
/**
* Returns the four.
* @return String
*/
public String getFour() {
return four;
}
/**
* Returns the three.
* @return String
*/
public String getThree() {
return three;
}
/**
* Sets the four.
* @param four The four to set
*/
public void setFour(String four) {
this.four = four;
}
/**
* Sets the three.
* @param three The three to set
*/
public void setThree(String three) {
this.three = three;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(DerivatedBean.class);
static {
org.apache.axis.description.ElementDesc field = new org.apache.axis.description.ElementDesc();
field.setFieldName("three");
field.setXmlName(new javax.xml.namespace.QName("", "three"));
field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
field.setNillable(true);
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("four");
field.setXmlName(new javax.xml.namespace.QName("", "four"));
field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
field.setNillable(true);
typeDesc.addFieldDesc(field);
};
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| 7,202 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestDerivatedBeanSerializer.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 test.encoding;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.namespace.QName;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializer;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.server.AxisServer;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* A little testcase for validating the serialization of inherited type.
*/
public class TestDerivatedBeanSerializer extends TestCase {
QName superTypeQName = new QName("typeNS", "SuperBean");
QName inheritedTypeQName = new QName("typeNS", "DerivatedBean");
StringWriter stringWriter;
SerializationContext context;
/**
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
// Initialisation of attribute used in the testMethods.
stringWriter = new StringWriter();
MessageContext msgContext = new MessageContext(new AxisServer());
context = new SerializationContext(stringWriter, msgContext);
// Create a TypeMapping and register the specialized Type Mapping
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.createTypeMapping();
tm.setSupportedEncodings(new String[] {Constants.URI_DEFAULT_SOAP_ENC});
reg.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
tm.register(SuperBean.class, superTypeQName, new BeanSerializerFactory(SuperBean.class,superTypeQName), new BeanDeserializerFactory(SuperBean.class,superTypeQName));
tm.register(DerivatedBean.class, inheritedTypeQName, new BeanSerializerFactory(DerivatedBean.class,inheritedTypeQName), new BeanDeserializerFactory(DerivatedBean.class,inheritedTypeQName));
}
/**
* Test the serialization of an simple sequence. The bean contains three
* elements (zero, one, two). The excepted result is something like:
* <BR>
* <PRE>
* <SuperBean>
* <zero/>
* <one/>
* <two/>
* </SuperBean>
* </PRE>
*/
/*
public void testSuperBeanSerialize() throws Exception {
BeanSerializer ser = new BeanSerializer(SuperBean.class, superTypeQName);
Object object = new SuperBean();
ser.serialize(superTypeQName,null,object,context);
// Check the result
String msgString = stringWriter.toString();
StringReader reader = new StringReader(msgString);
DOMParser parser = new DOMParser();
parser.parse(new InputSource(reader));
Document doc = parser.getDocument();
// We only test the order of the attributes.
NodeList nodes = doc.getFirstChild().getChildNodes();
assertEquals("1st Attribute", "zero", nodes.item(0).getLocalName());
assertEquals("2nd Attribute", "one", nodes.item(1).getLocalName());
assertEquals("3rd Attribute", "two", nodes.item(2).getLocalName());
}
*/
/**
* Test the serialization of an derivated sequence. The derivated bean contains two elements
* (three, four) and the super class has three elements (zero, one, two). The excepted
* result is something like: <BR>
* <PRE>
* <DerivatedBean>
* <zero/>
* <one/>
* <two/>
* <three/>
* <four/>
* </DerivatedBean>
* </PRE>
*/
public void testDerivatedBeanSerialize() throws Exception {
BeanSerializer ser = new BeanSerializer(DerivatedBean.class, inheritedTypeQName);
Object object = new DerivatedBean();
ser.serialize(inheritedTypeQName,null,object,context);
// Check the result
String msgString = stringWriter.toString();
StringReader reader = new StringReader(msgString);
Document doc = XMLUtils.newDocument(new InputSource(reader));
NodeList nodes = doc.getFirstChild().getChildNodes();
assertEquals("1st Attribute", "zero", nodes.item(0).getLocalName());
assertEquals("2nd Attribute", "one", nodes.item(1).getLocalName());
assertEquals("3rd Attribute", "two", nodes.item(2).getLocalName());
assertEquals("4th Attribute", "three", nodes.item(3).getLocalName());
assertEquals("First Attribute", "four", nodes.item(4).getLocalName());
}
}
| 7,203 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/EncodingTest.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.components.encoding.XMLEncoder;
import org.apache.axis.components.encoding.XMLEncoderFactory;
import java.io.UnsupportedEncodingException;
/**
* Tests for the new XMLEncoder components.
* Some of the tests are convoluted; that is to make diagnosis of faults easy, even
* with JUnit's XML reporting intervening in the process.
*/
public class EncodingTest extends TestCase {
private static final String GERMAN_UMLAUTS = " Some text \u00df with \u00fc special \u00f6 chars \u00e4.";
private static final String XML_SPECIAL_CHARS = "< > \" &";
private static final String ENCODED_XML_SPECIAL_CHARS = "< > " &";
private static final String SUPPORT_CHARS_LESS_HEX_20 = "\t\r\n";
private static final String ENCODED_SUPPORT_CHARS_LESS_HEX_20 = "	
";
private static final String INVALID_XML_STRING = "Invalid XML String \u0000";
private static final String FRENCH_ACCENTS="\u00e0\u00e2\u00e4\u00e7\u00e8\u00e9\u00ea\u00eb\u00ee\u00ef\u00f4\u00f6\u00f9\u00fb\u00fc";
public EncodingTest(String s) {
super(s);
}
public void testEncodingFailure() throws Exception {
// now it should return a default encoder
assertTrue( XMLEncoderFactory.getEncoder("XYZ") != null );
assertInvalidStringsDetected(INVALID_XML_STRING);
//run through the first 32 chars
for(int i=0;i<31;i++) {
char c=(char)i;
//ignore legit whitespace
if ("\t\n\r".indexOf(c) == -1) {
//verify the others are caught
String s=(new Character(c)).toString();
assertInvalidStringsDetected(s);
}
}
}
/**
* try a string through the two encoders we have, verify it is invalid
* @param invalidXmlString string we expect to fail
* @throws Exception
*/
private void assertInvalidStringsDetected(String invalidXmlString) throws Exception {
assertInvalidStringsDetected(XMLEncoderFactory.ENCODING_UTF_16,invalidXmlString);
assertInvalidStringsDetected(XMLEncoderFactory.ENCODING_UTF_8, invalidXmlString);
}
/**
* try a string through the two encoders we have, verify it is invalid
* @param encoderChoice name of the encoder to use
* @param invalidXmlString string we expect to fail
*/
private void assertInvalidStringsDetected(String encoderChoice, String invalidXmlString) throws Exception {
try {
XMLEncoder encoder = XMLEncoderFactory.getEncoder(encoderChoice);
encoder.encode(invalidXmlString);
fail("A UnsupportedEncodingException should have been thrown.");
} catch (IllegalArgumentException expected) {
// expected
}
}
public void testUTF8() throws Exception {
XMLEncoder encoder = XMLEncoderFactory.getEncoder(XMLEncoderFactory.ENCODING_UTF_8);
String encodedUmlauts = encoder.encode(GERMAN_UMLAUTS);
assertEquals(XMLEncoderFactory.ENCODING_UTF_8, encoder.getEncoding());
assertEquals(GERMAN_UMLAUTS, encodedUmlauts);
verifyCommonAssertions(encoder);
}
public void testUTF16() throws Exception {
XMLEncoder encoder = XMLEncoderFactory.getEncoder(XMLEncoderFactory.ENCODING_UTF_16);
String encodedUmlauts = encoder.encode(GERMAN_UMLAUTS);
assertEquals(XMLEncoderFactory.ENCODING_UTF_16, encoder.getEncoding());
assertEquals(GERMAN_UMLAUTS, encodedUmlauts);
//verifyCommonAssertions(encoder);
}
public void test2UTF8() throws Exception {
XMLEncoder encoder = XMLEncoderFactory.getEncoder(XMLEncoderFactory.ENCODING_UTF_8);
String encodedAccents = encoder.encode(FRENCH_ACCENTS);
assertEquals(XMLEncoderFactory.ENCODING_UTF_8, encoder.getEncoding());
assertEquals(FRENCH_ACCENTS, encodedAccents);
verifyCommonAssertions(encoder);
}
public void test2UTF16() throws Exception {
XMLEncoder encoder = XMLEncoderFactory.getEncoder(XMLEncoderFactory.ENCODING_UTF_16);
String encodedAccents = encoder.encode(FRENCH_ACCENTS);
assertEquals(XMLEncoderFactory.ENCODING_UTF_16, encoder.getEncoding());
assertEquals(FRENCH_ACCENTS, encodedAccents);
//verifyCommonAssertions(encoder);
}
/**
* assertions here hold for either encoder
* @param encoder
*/
private void verifyCommonAssertions(XMLEncoder encoder) {
String encodedXMLChars = encoder.encode(XML_SPECIAL_CHARS);
assertEquals(ENCODED_XML_SPECIAL_CHARS, encodedXMLChars);
//assert that the whitespace chars are not touched
verifyUntouched(encoder, "\t");
verifyUntouched(encoder, "\n");
verifyUntouched(encoder, "\r");
}
/**
* verify that the support chars are not touched. This is done on a char by
* char basis for easier debugging. One debug problem there is that
* ant's XML logger also encodes the strings, making diagnosing
* the defect from an error report trickier than normal.
* @param encoder
*/
private void verifyUntouched(XMLEncoder encoder, String source) {
for(int i=0;i<source.length();i++) {
char c = source.charAt(i);
Character ch = new Character(c);
String xmlString = ch.toString();
String encoded= encoder.encode(xmlString);
assertEquals("Char " +(int) c + " was encoded as " + hexDump(encoded),
xmlString,encoded);
}
}
private String hexDump(String source) {
StringBuffer out=new StringBuffer(source.length()*5);
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
out.append("0x");
out.append(Integer.toHexString(c));
out.append(" ");
}
return new String(out);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(EncodingTest.class);
}
}
| 7,204 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestString.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.server.AxisServer;
import org.xml.sax.InputSource;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
/** Little serialization test with a struct.
*/
public class TestString extends TestCase {
public static final String myNS = "urn:myNS";
private void runtest(String value, String expected) throws Exception {
MessageContext msgContext = new MessageContext(new AxisServer());
MessageFactory factory = MessageFactory.newInstance();
org.apache.axis.Message message = (org.apache.axis.Message) factory.createMessage();
message.setMessageContext(msgContext);
String requestEncoding = "UTF-8";
msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
message.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
RPCParam input = new RPCParam("urn:myNamespace", "testParam", value);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[]{ input });
message.getSOAPBody().addChildElement(body);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
DeserializationContext dser = new DeserializationContext(
new InputSource(bais), msgContext, org.apache.axis.Message.REQUEST);
dser.parse();
org.apache.axis.message.SOAPEnvelope env = dser.getEnvelope();
RPCElement rpcElem = (RPCElement)env.getFirstBody();
RPCParam output = rpcElem.getParam("testParam");
assertNotNull("No <testParam> param", output);
String result = (String)output.getObjectValue();
assertNotNull("No value for testParam param", result);
assertEquals("Expected result not received.", expected, result);
}
private void runtest(String value) throws Exception {
runtest(value, value);
}
public void testSimpleString() throws Exception {
runtest("a simple string");
}
public void testStringWithApostrophes() throws Exception {
runtest("this isn't a simple string");
}
public void testStringWithEntities() throws Exception {
runtest("&<>'"", "&<>'"");
}
public void testStringWithRawEntities() throws Exception {
runtest("&<>'\"", "&<>'\"");
}
public void testStringWithLeadingAndTrailingSpaces() throws Exception {
runtest(" centered ");
}
public void testWhitespace() throws Exception {
runtest(" \n \t "); // note: \r fails
}
public void testFrenchAccents() throws Exception {
runtest("\u00e0\u00e2\u00e4\u00e7\u00e8\u00e9\u00ea\u00eb\u00ee\u00ef\u00f4\u00f6\u00f9\u00fb\u00fc");
}
public void testFrenchAccents2() throws Exception {
runtest("Une chaîne avec des caractères accentués");
}
public void testGermanUmlauts() throws Exception {
runtest(" Some text \u00df with \u00fc special \u00f6 chars \u00e4.");
}
public void testWelcomeUnicode() throws Exception {
// welcome in several languages
runtest(
"Chinese (trad.) : \u6b61\u8fce ");
}
public void testWelcomeUnicode2() throws Exception {
// welcome in several languages
runtest(
"Greek : \u03ba\u03b1\u03bb\u03ce\u03c2 \u03bf\u03c1\u03af\u03c3\u03b1\u03c4\u03b5");
}
public void testWelcomeUnicode3() throws Exception {
// welcome in several languages
runtest(
"Japanese : \u3088\u3046\u3053\u305d");
}
}
| 7,205 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/DataSerFactory.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 test.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializerFactory;
import java.util.Iterator;
import java.util.Vector;
/**
* SerializerFactory for DataSer
*
* @author Rich Scheuerle <scheu@us.ibm.com>
*/
public class DataSerFactory implements SerializerFactory {
private Vector mechanisms;
public DataSerFactory() {
}
public javax.xml.rpc.encoding.Serializer getSerializerAs(String mechanismType) {
return new DataSer();
}
public Iterator getSupportedMechanismTypes() {
if (mechanisms == null) {
mechanisms = new Vector();
mechanisms.add(Constants.AXIS_SAX);
}
return mechanisms.iterator();
}
}
| 7,206 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestDOM.java | package test.encoding;
import org.apache.axis.AxisEngine;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.message.SOAPBody;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.XMLUtils;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.Diff;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.io.StringWriter;
/**
* Verify that deserialization actually can cause the soap service
* to be set...
*/
public class TestDOM extends XMLTestCase {
private String header =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<SOAP-ENV:Envelope" +
" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <SOAP-ENV:Header>\n" +
" <SOAP-SEC:signature SOAP-ENV:actor=\"null\" SOAP-ENV:mustUnderstand=\"1\"" +
" xmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/\">\n" +
" <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
" </Signature>\n" +
" </SOAP-SEC:signature>\n" +
" </SOAP-ENV:Header>\n" +
" <SOAP-ENV:Body id=\"body\">\n" +
" <ns1:getQuote xmlns:ns1=\"urn:xmltoday-delayed-quotes\">\n";
private String request1 =
" <symbol xsi:type=\"xsd:string\">IBM</symbol>\n";
private String request2 =
" <addResult xsi:type=\"xsd:int\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">4</addResult>\n";
private String footer =
" </ns1:getQuote>\n" +
" </SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>";
public void testDOM() throws Exception {
// setup
AxisEngine engine = new AxisServer();
engine.init();
MessageContext msgContext = new MessageContext(engine);
msgContext.setHighFidelity(true);
String request = header + request1 + footer;
Message message = new Message(request);
message.setMessageContext(msgContext);
// Now completely round trip it
message.getSOAPEnvelope();
// Element dom = message.getAsDOM();
String result = message.getSOAPPartAsString();
assertXMLEqual("Request is not the same as the result.", request, result);
}
public void testHeaders() throws Exception {
AxisEngine engine = new AxisServer();
engine.init();
MessageContext msgContext = new MessageContext(engine);
msgContext.setHighFidelity(true);
String request = header + request1 + footer;
Message message = new Message(request);
message.setMessageContext(msgContext);
// Now completely round trip it
SOAPEnvelope envelope = message.getSOAPEnvelope();
envelope.addHeader(new SOAPHeaderElement("foo1", "foo1"));
envelope.addHeader(new SOAPHeaderElement("foo2", "foo2"));
envelope.addHeader(new SOAPHeaderElement("foo3", "foo3"));
String result = message.getSOAPPartAsString();
assertTrue(result.indexOf("foo1")!=-1);
assertTrue(result.indexOf("foo2")!=-1);
assertTrue(result.indexOf("foo3")!=-1);
Message message2 = new Message(result);
message2.setMessageContext(msgContext);
message2.getSOAPEnvelope();
String result2 = message2.getSOAPPartAsString();
assertTrue(result2.indexOf("foo1")!=-1);
assertTrue(result2.indexOf("foo2")!=-1);
assertTrue(result2.indexOf("foo3")!=-1);
}
/**
* Test for Bug 7132
*/
public void testAttributes() throws Exception {
AxisEngine engine = new AxisServer();
engine.init();
MessageContext msgContext = new MessageContext(engine);
msgContext.setHighFidelity(true);
String request = header + request2 + footer;
Message message = new Message(request);
message.setMessageContext(msgContext);
SOAPEnvelope envelope = message.getSOAPEnvelope();
SOAPBodyElement bodyElement = (SOAPBodyElement)envelope.getBodyElements().elementAt(0);
MessageElement me = (MessageElement) bodyElement.getChildren().get(0);
org.xml.sax.Attributes atts = me.getCompleteAttributes();
assertTrue(atts.getLength()==2);
}
public void testEmptyNode() throws Exception
{
SOAPBodyElement body = new SOAPBodyElement(XMLUtils.newDocument().createElementNS(null,"tmp"));
assertXMLEqual("<tmp/>",body.toString());
}
public void testNodeWithAttribute() throws Exception
{
org.w3c.dom.Element element = XMLUtils.newDocument().createElementNS(null,"tmp");
element.setAttributeNS(null,"attrib", "foo");
SOAPBodyElement body = new SOAPBodyElement(element);
assertXMLEqual("<tmp attrib=\"foo\"/>",body.toString());
}
public void testDOM2() throws Exception
{
// Simulate receiving a signed message.
//
String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <soapenv:Body>\n";
String xml2 = " <SASLResponse xmlns=\"urn:liberty:sa:2004-04\">\n" +
" <Status code=\"OK\" comment=\"Authenticated\"/>\n" +
" </SASLResponse>\n";
String xml3 =
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
DeserializationContext ctx = new DeserializationContext(new InputSource(new StringReader(xml1 + xml2 + xml3)), null, "response");
ctx.parse();
SOAPEnvelope env = ctx.getEnvelope();
SOAPBody body = (SOAPBody) env.getBody();
// I am using the body child as my "token". The basic idea is that
// this element must be serialized _exactly_ as it was received.
MessageElement elt = (MessageElement) body.getFirstChild();
assertTrue(!elt.isDirty());
StringWriter writer = new StringWriter();
SerializationContext serializeContext = new SerializationContext(writer, null);
serializeContext.setSendDecl(false);
elt.output(serializeContext);
writer.close();
assertXMLIdentical("Deserialization invalidated XML",
new Diff(xml2, writer.getBuffer().toString()), true);
}
}
| 7,207 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/DataSer.java | package test.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
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;
public class DataSer implements Serializer
{
public static final String STRINGMEMBER = "stringMember";
public static final String FLOATMEMBER = "floatMember";
/** SERIALIZER STUFF
*/
/**
* 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
{
if (!(value instanceof Data))
throw new IOException("Can't serialize a " + value.getClass().getName() + " with a DataSerializer.");
Data data = (Data)value;
context.startElement(name, attributes);
context.serialize(new QName("", STRINGMEMBER), null, data.stringMember);
context.serialize(new QName("", FLOATMEMBER), null, data.floatMember);
context.endElement();
}
public String getMechanismType() { return Constants.AXIS_SAX; }
public Element writeSchema(Class javaType, Types types) throws Exception {
return null;
}
}
| 7,208 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestGlobalTypeMappings.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 test.encoding;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.constants.Style;
import test.GenericLocalTest;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
/**
* Confirm that global type mappings work in both RPC and Document
* contexts.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestGlobalTypeMappings extends GenericLocalTest {
private QName TYPE_QNAME = new QName("ns", "dataType");
protected void setUp() throws Exception {
super.setUp(false); // don't deploy here
TypeMapping tm = (TypeMapping)config.getTypeMappingRegistry().
getDefaultTypeMapping();
tm.register(Data.class, TYPE_QNAME,
new BeanSerializerFactory(Data.class, TYPE_QNAME),
new BeanDeserializerFactory(Data.class, TYPE_QNAME));
}
public void testDocLit() throws Exception {
deploy("service", this.getClass(), Style.WRAPPED);
Call call = getCall();
call.setOperationStyle("wrapped");
call.setOperationUse("literal");
call.setEncodingStyle("");
call.registerTypeMapping(Data.class, TYPE_QNAME,
new BeanSerializerFactory(Data.class, TYPE_QNAME),
new BeanDeserializerFactory(Data.class, TYPE_QNAME));
call.setReturnClass(Data.class);
call.addParameter("arg0", TYPE_QNAME, ParameterMode.IN);
Data data = new Data();
data.stringMember = "doc lit test";
data.floatMember = new Float(451.0F);
call.invoke("echoData", new Object [] { data });
}
/**
* Our service method. We'll deploy this several ways.
*
* @param data
* @return
*/
public Data echoData(Data data) {
return data;
}
}
| 7,209 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestAttributes.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.BasicServerConfig;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.encoding.ser.SimpleDeserializerFactory;
import org.apache.axis.encoding.ser.SimpleSerializerFactory;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Vector;
/**
* Test the serialization of a bean with attributes
*
* @author Tom Jordahl (tomj@macromedia.com)
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestAttributes extends TestCase {
static Log log =
LogFactory.getLog(TestAttributes.class.getName());
public static final String myNS = "urn:myNS";
public void testBean () throws Exception {
MessageContext msgContext = new MessageContext(new AxisServer(new BasicServerConfig()));
SOAPEnvelope msg = new SOAPEnvelope();
// Create bean with data
AttributeBean bean = new AttributeBean();
bean.setAge(35);
bean.setID(1.15F);
bean.setMale(true);
bean.company = "Majesty's Secret Service";
bean.setName("James Bond");
RPCParam arg = new RPCParam("", "struct", bean);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[]{ arg });
msg.addBodyElement(body);
body.setEncodingStyle(null);
Writer stringWriter = new StringWriter();
SerializationContext context = new SerializationContext(stringWriter, msgContext);
context.setDoMultiRefs(false); // no multirefs
context.setPretty(false);
// Create a TypeMapping and register the Bean serializer/deserializer
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.createTypeMapping();
// The "" namespace is literal (no encoding).
tm.setSupportedEncodings(new String[] {Constants.URI_DEFAULT_SOAP_ENC});
reg.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
QName beanQName = new QName("typeNS", "TheBean");
tm.register(AttributeBean.class,
beanQName,
new BeanSerializerFactory(AttributeBean.class, beanQName),
new BeanDeserializerFactory(AttributeBean.class, beanQName));
// Serialize the bean in to XML
msg.output(context);
// Get the XML as a string
String msgString = stringWriter.toString();
log.debug("---");
log.debug(msgString);
log.debug("---");
System.out.println(msgString);
Message message = new Message(msgString);
message.setMessageContext(msgContext);
SOAPEnvelope env = message.getSOAPEnvelope();
RPCElement rpcEl = (RPCElement)env.getFirstBody();
Vector params = rpcEl.getParams();
assertEquals("Wrong # of params in deserialized message!",
1,
params.size());
Object obj = ((RPCParam)params.get(0)).getObjectValue();
assertTrue("Deserialized param not an AttributeBean!",
(obj instanceof AttributeBean));
AttributeBean deserBean = (AttributeBean)obj;
assertTrue("Deserialized bean not equal to expected values!",
(bean.equals(deserBean)));
}
public void testSimpleType() throws Exception {
checkSimpleBeanRoundTrip("test value", 85.0F);
}
public void testSimpleType2() throws Exception {
//Testcase for 12452 - Axis does not correctly XML-encode ampersands
checkSimpleBeanRoundTrip("http://mysite.com?a=1&b=2", 85.0F);
}
public void testSimpleType3() throws Exception {
//Testcase for 12453 - Axis does not correctly XML-encode <'s and >'s
checkSimpleBeanRoundTrip("</name>", 85.0F);
}
private void checkSimpleBeanRoundTrip(String text, float temp) throws Exception {
SimpleBean bean = new SimpleBean(text);
bean.temp = temp;
MessageContext msgContext = new MessageContext(new AxisServer(new BasicServerConfig()));
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg = new RPCParam("", "simple", bean);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[]{ arg });
msg.addBodyElement(body);
body.setEncodingStyle(null);
StringWriter writer = new StringWriter();
SerializationContext context = new SerializationContext(writer,
msgContext);
context.setDoMultiRefs(false);
// Create a TypeMapping and register the Bean serializer/deserializer
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.createTypeMapping();
// The "" namespace is literal (no encoding).
tm.setSupportedEncodings(new String[] {Constants.URI_DEFAULT_SOAP_ENC});
reg.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
QName beanQName = new QName("typeNS", "Bean");
tm.register(SimpleBean.class,
beanQName,
new SimpleSerializerFactory(SimpleBean.class, beanQName),
new SimpleDeserializerFactory(SimpleBean.class, beanQName));
// Serialize the bean in to XML
msg.output(context);
// Get the XML as a string
String msgString = writer.toString();
Message message = new Message(msgString);
message.setMessageContext(msgContext);
SOAPEnvelope env = message.getSOAPEnvelope();
RPCElement rpcEl = (RPCElement)env.getFirstBody();
Vector params = rpcEl.getParams();
assertEquals("Wrong # of params in deserialized message!",
1,
params.size());
Object obj = ((RPCParam)params.get(0)).getObjectValue();
assertTrue("Deserialized param not a SimpleBean!",
(obj instanceof SimpleBean));
SimpleBean deserBean = (SimpleBean)obj;
assertTrue("Deserialized bean not equal to expected values!",
(bean.equals(deserBean)));
}
}
| 7,210 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/ParentBean.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 test.encoding;
import org.apache.axis.description.AttributeDesc;
import org.apache.axis.description.ElementDesc;
import org.apache.axis.description.FieldDesc;
import org.apache.axis.description.TypeDesc;
import javax.xml.namespace.QName;
/**
* @author Glen Daniels (gdaniels@apache.org)
*/
public class ParentBean {
private float parentFloat; // attribute
private String parentStr; // element
public float getParentFloat() {
return parentFloat;
}
public void setParentFloat(float parentFloat) {
this.parentFloat = parentFloat;
}
public String getParentStr() {
return parentStr;
}
public void setParentStr(String parentStr) {
this.parentStr = parentStr;
}
// Type metadata
private static TypeDesc typeDesc;
static {
typeDesc = new TypeDesc(ParentBean.class);
FieldDesc field;
// An attribute with a specified QName
field = new AttributeDesc();
field.setFieldName("parentFloat");
field.setXmlName(new QName("", "parentAttr"));
typeDesc.addFieldDesc(field);
// An element with a specified QName
field = new ElementDesc();
field.setFieldName("parentStr");
field.setXmlName(new QName("", "parentElement"));
((ElementDesc)field).setNillable(true);
typeDesc.addFieldDesc(field);
}
public static TypeDesc getTypeDesc()
{
return typeDesc;
}
}
| 7,211 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestSer.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.XMLUtils;
import org.apache.commons.logging.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.namespace.QName;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/** Little serialization test with a struct.
*/
public class TestSer extends TestCase {
Log log =
LogFactory.getLog(TestSer.class.getName());
public static final String myNS = "urn:myNS";
public void testDataNoHrefs () throws Exception {
doTestData(false);
}
public void testDataWithHrefs () throws Exception {
doTestData(true);
}
public void doTestData (boolean multiref) throws Exception {
MessageContext msgContext = new MessageContext(new AxisServer());
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg1 = new RPCParam("urn:myNamespace", "testParam", "this is a string");
Data data = new Data();
data.stringMember = "String member";
data.floatMember = new Float("4.54");
RPCParam arg2 = new RPCParam("", "struct", data);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[]{ arg1, arg2 });
msg.addBodyElement(body);
Writer stringWriter = new StringWriter();
SerializationContext context = new SerializationContext(stringWriter, msgContext);
context.setDoMultiRefs(multiref);
// Create a TypeMapping and register the specialized Type Mapping
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.createTypeMapping();
tm.setSupportedEncodings(new String[] {Constants.URI_DEFAULT_SOAP_ENC});
reg.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
QName dataQName = new QName("typeNS", "Data");
tm.register(Data.class, dataQName, new DataSerFactory(), new DataDeserFactory());
msg.output(context);
String msgString = stringWriter.toString();
log.debug("---");
log.debug(msgString);
log.debug("---");
StringReader reader = new StringReader(msgString);
DeserializationContext dser = new DeserializationContext(
new InputSource(reader), msgContext, org.apache.axis.Message.REQUEST);
dser.parse();
SOAPEnvelope env = dser.getEnvelope();
RPCElement rpcElem = (RPCElement)env.getFirstBody();
RPCParam struct = rpcElem.getParam("struct");
assertNotNull("No <struct> param", struct);
Data val = (Data)struct.getObjectValue();
assertNotNull("No value for struct param", val);
assertEquals("Data and Val string members are not equal", data.stringMember, val.stringMember);
assertEquals("Data and Val float members are not equal",data.floatMember.floatValue(),
val.floatMember.floatValue(), 0.00001F);
}
public void testAttributeQNames() throws Exception {
String NS1 = "urn:foo";
MessageContext context = new MessageContext(new AxisServer());
StringWriter writer = new StringWriter();
SerializationContext ser = new SerializationContext(writer);
ser.registerPrefixForURI("", NS1);
ser.startElement(new QName(NS1, "e1"), null);
String foo = ser.attributeQName2String(new QName(NS1, "attr"));
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("a", "a", "a", "CDATA", foo);
ser.startElement(new QName(NS1, "e2"), attrs);
ser.endElement();
foo = ser.attributeQName2String(new QName(NS1, "attr"));
attrs = new AttributesImpl();
attrs.addAttribute("a", "a", "a", "CDATA", foo);
ser.startElement(new QName(NS1, "e3"), null);
ser.endElement();
ser.endElement();
System.out.println(writer.getBuffer().toString());
}
/**
* Test RPC element serialization when we have no MessageContext
*/
public void testRPCElement()
{
try {
SOAPEnvelope env = new SOAPEnvelope();
RPCElement method = new RPCElement("ns",
"method",
new Object [] { "argument" });
env.addBodyElement(method);
env.toString();
} catch (Exception e) {
fail(e.getMessage());
}
// If there was no exception, we succeeded in serializing it.
}
public void testEmptyXMLNS() throws Exception
{
MessageContext msgContext = new MessageContext(new AxisServer());
String req =
"<xsd1:A xmlns:xsd1=\"urn:myNamespace\">"
+ "<xsd1:B>"
+ "<xsd1:C>foo bar</xsd1:C>"
+ "</xsd1:B>"
+ "</xsd1:A>";
StringWriter stringWriter=new StringWriter();
StringReader reqReader = new StringReader(req);
InputSource reqSource = new InputSource(reqReader);
Document document = XMLUtils.newDocument(reqSource);
String msgString = null;
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg1 = new RPCParam("urn:myNamespace", "testParam", document.getFirstChild());
arg1.setXSITypeGeneration(Boolean.FALSE);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[] { arg1 });
msg.addBodyElement(body);
body.setEncodingStyle(Constants.URI_LITERAL_ENC);
SerializationContext context = new SerializationContext(stringWriter, msgContext);
msg.output(context);
msgString = stringWriter.toString();
assertTrue(msgString.indexOf("xmlns=\"\"")==-1);
}
/**
* Confirm that default namespaces when writing doc/lit messages don't
* trample namespace mappings.
*
* @throws Exception
*/
public void testDefaultNamespace() throws Exception
{
MessageContext msgContext = new MessageContext(new AxisServer());
String req =
"<xsd1:A xmlns:xsd1=\"urn:myNamespace\">"
+ "<B>" // Note that B and C are in no namespace!
+ "<C>foo bar</C>"
+ "</B>"
+ "</xsd1:A>";
StringWriter stringWriter=new StringWriter();
StringReader reqReader = new StringReader(req);
InputSource reqSource = new InputSource(reqReader);
Document document = XMLUtils.newDocument(reqSource);
String msgString = null;
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg1 = new RPCParam("urn:myNamespace", "testParam", document.getFirstChild());
arg1.setXSITypeGeneration(Boolean.FALSE);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[] { arg1 });
msg.addBodyElement(body);
body.setEncodingStyle(Constants.URI_LITERAL_ENC);
SerializationContext context = new SerializationContext(stringWriter, msgContext);
msg.output(context);
msgString = stringWriter.toString();
// Now reparse into DOM so we can check namespaces.
StringReader resReader = new StringReader(msgString);
InputSource resSource = new InputSource(resReader);
Document doc = XMLUtils.newDocument(resSource);
// Go make sure B and C are in fact in no namespace
Element el = findChildElementByLocalName(doc.getDocumentElement(),
"B");
assertNotNull("Couldn't find <B> element!", el);
assertNull("Element <B> has a namespace!", el.getNamespaceURI());
el = findChildElementByLocalName(el, "C");
assertNotNull("Couldn't find <C> element!", el);
assertNull("Element <C> has a namespace!", el.getNamespaceURI());
}
private Element findChildElementByLocalName(Element src, String localName) {
NodeList nl = src.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element)node;
if (e.getLocalName().equals(localName)) {
return e;
}
// Depth-first search
e = findChildElementByLocalName(e, localName);
if (e != null) {
return e;
}
}
}
return null;
}
}
| 7,212 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestRoundTrip.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import javax.xml.namespace.QName;
import java.util.Vector;
/**
* Test round-trip serialization/deserialization of SOAP messages
*/
public class TestRoundTrip extends TestCase {
private AxisServer server = new AxisServer();
private String header =
"<?xml version=\"1.0\"?>\n" +
"<SOAP-ENV:Envelope\n" +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
"xmlns:xsd-cr=\"http://www.w3.org/2000/10/XMLSchema\"\n" +
"xmlns:xsd-lc=\"http://www.w3.org/1999/XMLSchema\"\n" +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
"<SOAP-ENV:Body>\n";
private String footer =
"</SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>\n";
private String response =
"<ser-root:SrvResponse xmlns:ser-root=\"urn:test.encoding\">\n" +
" <ser-root:RETURN xsi:type=\"ser-root:RETURN\">\n" +
" <TYPE xsi:type=\"xsd:string\">000</TYPE>\n" +
" <ID xsi:type=\"xsd:string\">001</ID>\n" +
" <NUMBER xsi:type=\"xsd:string\">002</NUMBER>\n" +
" <MESSAGE xsi:type=\"xsd:string\">003</MESSAGE>\n" +
" <LOG_NO xsi:type=\"xsd:string\">004</LOG_NO>\n" +
" <LOG_MSG_NO xsi:type=\"xsd:string\">005</LOG_MSG_NO>\n" +
" <MESSAGE_V1 xsi:type=\"xsd:string\">006</MESSAGE_V1>\n" +
" <MESSAGE_V2 xsi:type=\"xsd:string\">007</MESSAGE_V2>\n" +
" <MESSAGE_V3 xsi:type=\"xsd:string\">008</MESSAGE_V3>\n" +
" <MESSAGE_V4 xsi:type=\"xsd:string\">009</MESSAGE_V4>\n" +
" </ser-root:RETURN>\n" +
"</ser-root:SrvResponse>";
public TestRoundTrip(String name) {
this(name, Constants.URI_DEFAULT_SCHEMA_XSI,
Constants.URI_DEFAULT_SCHEMA_XSD);
}
public TestRoundTrip(String name, String NS_XSI, String NS_XSD) {
super(name);
TypeMappingRegistry tmr = server.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) tmr.createTypeMapping();
tm.setSupportedEncodings(new String[]{Constants.URI_DEFAULT_SOAP_ENC});
tmr.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
tm.register(test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN")));
}
// test if objects are equal
private static boolean equals(Object obj1, Object obj2) {
if ((obj1 == null) || (obj2 == null)) return (obj1 == obj2);
if (obj1.equals(obj2)) return true;
return false;
}
// Test RoundTrip
public void testRoundTrip() throws Exception {
checkRoundTrip(header + response + footer);
}
protected void checkRoundTrip(String xml1) throws Exception {
Message message = new Message(xml1);
message.setMessageContext(new MessageContext(server));
SOAPEnvelope envelope = (SOAPEnvelope) message.getSOAPEnvelope();
RPCElement body = (RPCElement) envelope.getFirstBody();
Vector arglist = body.getParams();
Object ret1 = ((RPCParam) arglist.get(0)).getObjectValue();
String xml2 = message.getSOAPPartAsString();
Message message2 = new Message(xml2);
message2.setMessageContext(new MessageContext(server));
SOAPEnvelope envelope2 = (SOAPEnvelope) message2.getSOAPEnvelope();
RPCElement body2 = (RPCElement) envelope2.getFirstBody();
Vector arglist2 = body2.getParams();
Object ret2 = ((RPCParam) arglist2.get(0)).getObjectValue();
if (!equals(ret1, ret2)) {
assertEquals("The result is not what is expected.", ret1, ret2);
}
}
}
| 7,213 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/SimpleBean.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 test.encoding;
import org.apache.axis.description.AttributeDesc;
import org.apache.axis.description.FieldDesc;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.encoding.SimpleType;
import javax.xml.namespace.QName;
/**
* A simple type with attributes for testing
*/
public class SimpleBean implements SimpleType {
public String value; // Our "actual" value
public float temp; // An attribute
private static TypeDesc typeDesc = new TypeDesc(SimpleBean.class);
static {
FieldDesc fd = new AttributeDesc();
fd.setFieldName("temp");
fd.setXmlName(new QName("foo", "temp"));
typeDesc.addFieldDesc(fd);
}
public static TypeDesc getTypeDesc() { return typeDesc; }
/**
* String constructor
*/
public SimpleBean(String val)
{
value = val;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public String toString() {
return value;
}
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof SimpleBean))
return false;
SimpleBean other = (SimpleBean)obj;
if (other.getTemp() != temp) {
return false;
}
if (value == null) {
return other.getValue() == null;
}
return value.equals(other.getValue());
}
}
| 7,214 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/Data.java | package test.encoding;
public class Data
{
public String stringMember;
public Float floatMember;
}
| 7,215 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestCircularRefs.java | package test.encoding;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import test.GenericLocalTest;
import java.util.Vector;
public class TestCircularRefs extends GenericLocalTest {
public void testCircularVectors() throws Exception {
try {
Call call = getCall();
Object result = call.invoke("getCircle", null);
} catch (AxisFault af){
return;
}
fail("Expected a fault");
// This just tests that we don't get exceptions during deserialization
// for now. We're still getting nulls for some reason, and once that's
// fixed we should uncomment this next line
// assertTrue("Result wasn't an array", result.getClass().isArray());
}
/**
* Service method. Return a Vector containing an object graph with a loop.
*
* @return a Vector with circular references
*/
public Vector getCircle() {
Vector vector1 = new Vector();
vector1.addElement("AString");
Vector vector2 = new Vector();
vector2.addElement(vector1);
vector1.addElement(vector2);
return vector2;
}
}
| 7,216 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestBeanDeser.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.JavaUtils;
import javax.xml.namespace.QName;
import java.util.Vector;
/**
* Test deserialization of SOAP responses
*/
public class TestBeanDeser extends TestCase {
private String header;
private String footer;
private AxisServer server = new AxisServer();
public TestBeanDeser(String name) {
this(name, Constants.URI_DEFAULT_SCHEMA_XSI,
Constants.URI_DEFAULT_SCHEMA_XSD);
}
public TestBeanDeser(String name, String NS_XSI, String NS_XSD) {
super(name);
header =
"<?xml version=\"1.0\"?>\n" +
"<SOAP-ENV:Envelope\n" +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
"xmlns:xsd-cr=\"http://www.w3.org/2000/10/XMLSchema\"\n" +
"xmlns:xsd-lc=\"http://www.w3.org/1999/XMLSchema\"\n" +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"+
"<SOAP-ENV:Body>\n";
footer =
"</SOAP-ENV:Body>\n"+
"</SOAP-ENV:Envelope>\n";
TypeMappingRegistry tmr = server.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) tmr.createTypeMapping();
tm.setSupportedEncodings(new String[]{Constants.URI_DEFAULT_SOAP_ENC});
tmr.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
tm.register(test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.RETURN.class,
new QName("urn:test.encoding", "RETURN")));
}
/**
* Verify that two objects have the same value, handling arrays...
*/
private static boolean equals(Object obj1, Object obj2) {
if ((obj1 == null) || (obj2 == null)) return (obj1 == obj2);
if (obj1.equals(obj2)) return true;
return false;
}
/**
* Verify that a given XML deserialized produces the expected result
*/
protected void deserialize(String data, Object expected)
throws Exception {
deserialize(data, expected, false);
}
protected void deserialize(String data, Object expected, boolean tryConvert)
throws Exception {
Message message = new Message(header + data + footer);
message.setMessageContext(new MessageContext(server));
SOAPEnvelope envelope = (SOAPEnvelope) message.getSOAPEnvelope();
assertNotNull("SOAP envelope should not be null", envelope);
RPCElement body = (RPCElement) envelope.getFirstBody();
assertNotNull("SOAP body should not be null", body);
Vector arglist = body.getParams();
assertNotNull("arglist", arglist);
assertTrue("param.size()<=0 {Should be > 0}", arglist.size() > 0);
RPCParam param = (RPCParam) arglist.get(0);
assertNotNull("SOAP param should not be null", param);
Object result = param.getObjectValue();
if (!equals(result, expected)) {
// Try to convert to the expected class
if (tryConvert) {
Object result2 = JavaUtils.convert(result, expected.getClass());
if (!equals(result2, expected)) {
assertEquals("The result is not what is expected.", expected, result);
}
} else {
assertEquals("The result is not what is expected.", expected, result);
}
}
}
// Struct Return
public void testReturn() throws Exception {
test.encoding.RETURN ret = new test.encoding.RETURN();
ret.setTYPE("000");
ret.setID("001");
ret.setNUMBER("002");
ret.setMESSAGE("003");
ret.setLOGNO("004");
ret.setLOGMSGNO("005");
ret.setMESSAGEV1("006");
ret.setMESSAGEV2("007");
ret.setMESSAGEV3("008");
ret.setMESSAGEV4("009");
String response =
"<ser-root:SrvResponse xmlns:ser-root=\"urn:test.encoding\">\n"+
" <ser-root:RETURN xsi:type=\"ser-root:RETURN\">\n"+
" <TYPE xsi:type=\"xsd:string\">000</TYPE>\n"+
" <ID xsi:type=\"xsd:string\">001</ID>\n"+
" <NUMBER xsi:type=\"xsd:string\">002</NUMBER>\n"+
" <MESSAGE xsi:type=\"xsd:string\">003</MESSAGE>\n"+
" <LOG_NO xsi:type=\"xsd:string\">004</LOG_NO>\n"+
" <LOG_MSG_NO xsi:type=\"xsd:string\">005</LOG_MSG_NO>\n"+
" <MESSAGE_V1 xsi:type=\"xsd:string\">006</MESSAGE_V1>\n"+
" <MESSAGE_V2 xsi:type=\"xsd:string\">007</MESSAGE_V2>\n"+
" <MESSAGE_V3 xsi:type=\"xsd:string\">008</MESSAGE_V3>\n"+
" <MESSAGE_V4 xsi:type=\"xsd:string\">009</MESSAGE_V4>\n"+
" </ser-root:RETURN>\n"+
"</ser-root:SrvResponse>";
deserialize(response,ret,true);
}
/*
// Struct Return - variation
public void testReturn2() throws Exception {
test.encoding.RETURN ret = new test.encoding.RETURN();
ret.setTYPE("000");
ret.setID("001");
ret.setNUMBER("002");
ret.setMESSAGE("003");
ret.setLOGNO("004");
ret.setLOGMSGNO("005");
ret.setMESSAGEV1("006");
ret.setMESSAGEV2("007");
ret.setMESSAGEV3("008");
ret.setMESSAGEV4("009");
String response =
"<SrvResponse xmlns=\"urn:test.encoding\">\n"+
" <RETURN>\n"+
" <TYPE xsi:type=\"xsd:string\">000</TYPE>\n"+
" <ID xsi:type=\"xsd:string\">001</ID>\n"+
" <NUMBER xsi:type=\"xsd:string\">002</NUMBER>\n"+
" <MESSAGE xsi:type=\"xsd:string\">003</MESSAGE>\n"+
" <LOG_NO xsi:type=\"xsd:string\">004</LOG_NO>\n"+
" <LOG_MSG_NO xsi:type=\"xsd:string\">005</LOG_MSG_NO>\n"+
" <MESSAGE_V1 xsi:type=\"xsd:string\">006</MESSAGE_V1>\n"+
" <MESSAGE_V2 xsi:type=\"xsd:string\">007</MESSAGE_V2>\n"+
" <MESSAGE_V3 xsi:type=\"xsd:string\">008</MESSAGE_V3>\n"+
" <MESSAGE_V4 xsi:type=\"xsd:string\">009</MESSAGE_V4>\n"+
" </RETURN>\n"+
"</SrvResponse>";
deserialize(response,ret,true);
}
*/
public static void main(String [] args) throws Exception
{
TestBeanDeser tester = new TestBeanDeser("test");
tester.testReturn();
}
}
| 7,217 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestArrayListConversions.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
public class TestArrayListConversions extends TestCase {
private static final String SERVICE_NAME = "TestArrayConversions";
private AxisServer server;
private LocalTransport transport;
private static boolean equals(List list, Object obj) {
if ((list == null) || (obj == null))
return false;
if (!obj.getClass().isArray()) return false;
Object[] array = (Object[]) obj;
Iterator iter = list.iterator();
for (int i = 0; i < array.length; i++) {
if (!(array[i].equals(iter.next()))) {
return false;
}
}
return true;
}
protected void setUp() throws Exception {
try {
SimpleProvider provider = new SimpleProvider();
server = new AxisServer(provider);
transport = new LocalTransport(server);
SOAPService service = new SOAPService(new RPCProvider());
service.setEngine(server);
service.setOption("className", "test.encoding.TestArrayListConversions");
service.setOption("allowedMethods", "*");
ServiceDesc desc = service.getInitializedServiceDesc(null);
desc.setDefaultNamespace(SERVICE_NAME);
provider.deployService(SERVICE_NAME, service);
} catch (Exception exp) {
exp.printStackTrace();
}
}
public void testVectorConversion() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
Vector v = new Vector();
v.addElement("Hi there!");
v.addElement("This'll be a SOAP Array and then a LinkedList!");
call.setOperationName(new QName(SERVICE_NAME, "echoLinkedList"));
Object ret = call.invoke(new Object[]{v});
if (!equals(v, ret)) assertEquals("Echo LinkedList mangled the result. Result is underneath.\n" + ret, v, ret);
}
public void testLinkedListConversion() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
LinkedList l = new LinkedList();
l.add("Linked list item #1");
l.add("Second linked list item");
l.add("This will be a SOAP Array then a Vector!");
call.setOperationName(new QName(SERVICE_NAME, "echoVector"));
Object ret = call.invoke(new Object[]{l});
if (!equals(l, ret)) assertEquals("Echo Vector mangled the result. Result is underneath.\n" + ret, l, ret);
}
public void testArrayConversion() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
Vector v = new Vector();
v.addElement("Hi there!");
v.addElement("This'll be a SOAP Array");
call.setOperationName(new QName(SERVICE_NAME, "echoArray"));
Object ret = call.invoke(new Object[]{v});
if (!equals(v, ret)) assertEquals("Echo Array mangled the result. Result is underneath\n" + ret, v, ret);
}
/**
* Test the setReturnClass() API on Call by asking the runtime to
* give us back a Vector instead of an array. Confirm we get a Vector
* back, and that it matches the data we send.
*/
public void testReturnAsVector() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
LinkedList l = new LinkedList();
l.add("Linked list item #1");
l.add("Second linked list item");
l.add("This will be a SOAP Array then a Vector!");
call.setOperationName(new QName(SERVICE_NAME, "echoArray"));
call.addParameter("arg0", null, LinkedList.class, ParameterMode.IN);
call.setReturnClass(Vector.class);
Object ret = call.invoke(new Object[]{l});
assertEquals("Return wasn't a Vector!", Vector.class, ret.getClass());
Vector v = (Vector)ret;
assertEquals("Sizes were different", l.size(), v.size());
for (int i = 0; i < l.size(); i++) {
String s = (String)l.get(i);
assertEquals("Value " + i + " didn't match", s, v.get(i));
}
}
/****************************************************************
*
* Service methods - this class is also deployed as an Axis RPC
* service for convenience. These guys just echo various things.
*
*/
public LinkedList echoLinkedList(LinkedList l) {
return l;
}
public Vector echoVector(Vector v) {
return v;
}
public Object[] echoArray(Object[] array) {
return array;
}
}
| 7,218 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestOmittedValues.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 test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.BasicServerConfig;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import javax.xml.namespace.QName;
/**
* A test which confirms that we can correctly call methods where null arguments
* are represented by omission from the SOAP envelope.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestOmittedValues extends TestCase {
String header =
"<?xml version=\"1.0\"?>\n" +
"<soap:Envelope " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:me=\"urn:me\" " +
"xmlns:xsi=\"" + Constants.URI_2001_SCHEMA_XSI + "\" " +
"xmlns:xsd=\"" + Constants.URI_2001_SCHEMA_XSD + "\">\n" +
"<soap:Body>\n" +
"<method>\n";
String missingParam2 =
" <param1 xsi:type=\"xsd:string\">One</param1>\n" +
" <param3 xsi:type=\"xsd:string\">Three</param3>\n";
String footer =
"</method>\n" +
"</soap:Body>\n" +
"</soap:Envelope>\n";
public void testOmittedValue() throws Exception {
// Set up a server and deploy our service
BasicServerConfig config = new BasicServerConfig();
AxisServer server = new AxisServer(config);
SOAPService service = new SOAPService(new RPCProvider());
service.setOption("className", "test.encoding.TestOmittedValues");
service.setOption("allowedMethods", "*");
ServiceDesc desc = service.getServiceDescription();
// We need parameter descriptors to make sure we can match by name
// (the only way omitted==null can work).
ParameterDesc [] params = new ParameterDesc [] {
new ParameterDesc(new QName("", "param1"), ParameterDesc.IN, null),
new ParameterDesc(new QName("", "param2"), ParameterDesc.IN, null),
new ParameterDesc(new QName("", "param3"), ParameterDesc.IN, null),
};
OperationDesc oper = new OperationDesc("method", params, null);
desc.addOperationDesc(oper);
config.deployService("testOmittedValue", service);
String msg = header + missingParam2 + footer;
Message message = new Message(msg);
MessageContext context = new MessageContext(server);
context.setRequestMessage(message);
Call call = new Call(new Service());
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService("testOmittedValue");
call.setTransport(transport);
SOAPEnvelope resEnv = call.invoke(message.getSOAPEnvelope());
RPCElement rpcElem = (RPCElement)resEnv.getFirstBody();
RPCParam param = (RPCParam)rpcElem.getParams().get(0);
assertEquals("OK!", param.getObjectValue());
}
// Server-side test method for omitting values
public String method(String p1, String p2, String p3) {
if (p1.equals("One") && p2 == null && p3.equals("Three")) {
return "OK!";
}
return "Bad arguments!";
}
}
| 7,219 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestOutputter.java | package test.encoding;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.custommonkey.xmlunit.XMLTestCase;
/**
* Test deserialization of SOAP responses
*/
public class TestOutputter extends XMLTestCase {
private String header;
private String footer;
private AxisServer server = new AxisServer();
public TestOutputter(String name) {
this(name, Constants.URI_DEFAULT_SCHEMA_XSI,
Constants.URI_DEFAULT_SCHEMA_XSD);
}
public TestOutputter(String name, String NS_XSI, String NS_XSD) {
super(name);
header =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soap:Envelope " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:xsi=\"" + NS_XSI + "\" " +
"xmlns:xsd=\"" + NS_XSD + "\">\n" +
"<soap:Body>\n" +
"<methodResult xmlns=\"http://tempuri.org/\">\n";
footer =
"</methodResult>\n" +
"</soap:Body>\n" +
"</soap:Envelope>";
}
/**
* Verify that a given XML deserialized produces the expected result
*/
protected void roundtrip(String data)
throws Exception
{
Message message = new Message(header + data + footer);
message.setMessageContext(new MessageContext(server));
message.getSOAPEnvelope();
assertXMLEqual(header+data+footer, message.getSOAPPartAsString());
}
public void testString() throws Exception {
roundtrip("<result xsi:type=\"xsd:string\">abc</result>");
}
public void testEscapedText() throws Exception {
roundtrip("<abc><&></abc>");
}
public void testEscapedAttributes() throws Exception {
roundtrip("<abc foo=\"<&>\"/>");
// roundtrip("<abc foo=\"<&>\"/>");
}
}
| 7,220 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestBody.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.AxisEngine;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.providers.java.JavaProvider;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import javax.xml.namespace.QName;
/**
* Verify that deserialization actually can cause the soap service
* to be set...
*/
public class TestBody extends TestCase {
private String namespace = "http://xml.apache.org/axis/TestBody";
private String request = "<?xml version=\"1.0\"?>\n" + "<soap:Envelope " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<soap:Body>\n" + "<method xmlns=\"" + namespace + "\">\n" + "<arg>5</arg>" + "</method>\n" + "</soap:Body>\n" + "</soap:Envelope>\n";
public void testBodyNamespace() throws Exception {
SimpleProvider provider = new SimpleProvider();
// register the service with the engine
SOAPService target = new SOAPService(new RPCProvider());
target.setOption(JavaProvider.OPTION_CLASSNAME, "test.encoding.TestBody");
provider.deployService(new QName(null,namespace), target);
// setup
AxisEngine engine = new AxisServer(provider);
engine.init();
// create a message in context
MessageContext msgContext = new MessageContext(engine);
Message message = new Message(request);
message.setMessageContext(msgContext);
// ensure that the message is parsed
SOAPEnvelope envelope = message.getSOAPEnvelope();
RPCElement body = (RPCElement) envelope.getFirstBody();
// This is not necessarily true anymore...
//assertEquals("Namespace does not equal the message context target service.", namespace, msgContext.getTargetService());
// verify the service is set
assertEquals("The target is not the same as the message context service handler", target, msgContext.getService());
}
}
| 7,221 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/DataDeser.java | package test.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.Deserializer;
import org.apache.axis.encoding.DeserializerImpl;
import org.apache.axis.encoding.FieldTarget;
import org.apache.axis.message.SOAPHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import java.util.Hashtable;
public class DataDeser extends DeserializerImpl
{
public static final String STRINGMEMBER = "stringMember";
public static final String FLOATMEMBER = "floatMember";
private Hashtable typesByMemberName = new Hashtable();
public DataDeser()
{
typesByMemberName.put(STRINGMEMBER, Constants.XSD_STRING);
typesByMemberName.put(FLOATMEMBER, Constants.XSD_FLOAT);
value = new Data();
}
/** DESERIALIZER STUFF - event handlers
*/
/**
* This method is invoked when an element start tag is encountered.
* @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 SOAPHandler onStartChild(String namespace,
String localName,
String prefix,
Attributes attributes,
DeserializationContext context)
throws SAXException
{
QName typeQName = (QName)typesByMemberName.get(localName);
if (typeQName == null)
throw new SAXException("Invalid element in Data struct - " + localName);
// These can come in either order.
Deserializer dSer = context.getDeserializerForType(typeQName);
try {
dSer.registerValueTarget(new FieldTarget(value, localName));
} catch (NoSuchFieldException e) {
throw new SAXException(e);
}
if (dSer == null)
throw new SAXException("No deserializer for a " + typeQName + "???");
return (SOAPHandler)dSer;
}
}
| 7,222 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/RETURN.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 test.encoding;
public class RETURN implements java.io.Serializable {
private java.lang.String TYPE;
private java.lang.String ID;
private java.lang.String NUMBER;
private java.lang.String MESSAGE;
private java.lang.String LOGNO;
private java.lang.String LOGMSGNO;
private java.lang.String MESSAGEV1;
private java.lang.String MESSAGEV2;
private java.lang.String MESSAGEV3;
private java.lang.String MESSAGEV4;
public RETURN() {
}
public java.lang.String getTYPE() {
return TYPE;
}
public void setTYPE(java.lang.String TYPE) {
this.TYPE = TYPE;
}
public java.lang.String getID() {
return ID;
}
public void setID(java.lang.String ID) {
this.ID = ID;
}
public java.lang.String getNUMBER() {
return NUMBER;
}
public void setNUMBER(java.lang.String NUMBER) {
this.NUMBER = NUMBER;
}
public java.lang.String getMESSAGE() {
return MESSAGE;
}
public void setMESSAGE(java.lang.String MESSAGE) {
this.MESSAGE = MESSAGE;
}
public java.lang.String getLOGNO() {
return LOGNO;
}
public void setLOGNO(java.lang.String LOGNO) {
this.LOGNO = LOGNO;
}
public java.lang.String getLOGMSGNO() {
return LOGMSGNO;
}
public void setLOGMSGNO(java.lang.String LOGMSGNO) {
this.LOGMSGNO = LOGMSGNO;
}
public java.lang.String getMESSAGEV1() {
return MESSAGEV1;
}
public void setMESSAGEV1(java.lang.String MESSAGEV1) {
this.MESSAGEV1 = MESSAGEV1;
}
public java.lang.String getMESSAGEV2() {
return MESSAGEV2;
}
public void setMESSAGEV2(java.lang.String MESSAGEV2) {
this.MESSAGEV2 = MESSAGEV2;
}
public java.lang.String getMESSAGEV3() {
return MESSAGEV3;
}
public void setMESSAGEV3(java.lang.String MESSAGEV3) {
this.MESSAGEV3 = MESSAGEV3;
}
public java.lang.String getMESSAGEV4() {
return MESSAGEV4;
}
public void setMESSAGEV4(java.lang.String MESSAGEV4) {
this.MESSAGEV4 = MESSAGEV4;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(RETURN.class);
static {
org.apache.axis.description.FieldDesc field = new org.apache.axis.description.ElementDesc();
field.setFieldName("LOGNO");
field.setXmlName(new javax.xml.namespace.QName("", "LOG_NO"));
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("MESSAGEV4");
field.setXmlName(new javax.xml.namespace.QName("", "MESSAGE_V4"));
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("MESSAGEV3");
field.setXmlName(new javax.xml.namespace.QName("", "MESSAGE_V3"));
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("MESSAGEV2");
field.setXmlName(new javax.xml.namespace.QName("", "MESSAGE_V2"));
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("MESSAGEV1");
field.setXmlName(new javax.xml.namespace.QName("", "MESSAGE_V1"));
typeDesc.addFieldDesc(field);
field = new org.apache.axis.description.ElementDesc();
field.setFieldName("LOGMSGNO");
field.setXmlName(new javax.xml.namespace.QName("", "LOG_MSG_NO"));
typeDesc.addFieldDesc(field);
};
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
public boolean equals(Object obj) {
// compare elements
RETURN other = (RETURN) obj;
if (obj == null) return false;
if (this == obj) return true;
if (! (obj instanceof RETURN)) return false;
return
((TYPE==null && other.getTYPE()==null) ||
(TYPE!=null &&
TYPE.equals(other.getTYPE()))) &&
((ID==null && other.getID()==null) ||
(ID!=null &&
ID.equals(other.getID()))) &&
((NUMBER==null && other.getNUMBER()==null) ||
(NUMBER!=null &&
NUMBER.equals(other.getNUMBER()))) &&
((MESSAGE==null && other.getMESSAGE()==null) ||
(MESSAGE!=null &&
MESSAGE.equals(other.getMESSAGE()))) &&
((LOGNO==null && other.getLOGNO()==null) ||
(LOGNO!=null &&
LOGNO.equals(other.getLOGNO()))) &&
((LOGMSGNO==null && other.getLOGMSGNO()==null) ||
(LOGMSGNO!=null &&
LOGMSGNO.equals(other.getLOGMSGNO()))) &&
((MESSAGEV1==null && other.getMESSAGEV1()==null) ||
(MESSAGEV1!=null &&
MESSAGEV1.equals(other.getMESSAGEV1()))) &&
((MESSAGEV2==null && other.getMESSAGEV2()==null) ||
(MESSAGEV2!=null &&
MESSAGEV2.equals(other.getMESSAGEV2()))) &&
((MESSAGEV3==null && other.getMESSAGEV3()==null) ||
(MESSAGEV3!=null &&
MESSAGEV3.equals(other.getMESSAGEV3()))) &&
((MESSAGEV4==null && other.getMESSAGEV4()==null) ||
(MESSAGEV4!=null &&
MESSAGEV4.equals(other.getMESSAGEV4())));
}
}
| 7,223 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestArray.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.commons.logging.Log;
/**
* Test the serialization of an array. Test case for Bug 14666
* (NullPointerException taken in ArraySerializer when specifying array as input parameter.)
*/
public class TestArray extends TestCase {
static Log log =
LogFactory.getLog(TestArray.class.getName());
public void testArray1() {
String tab_items [] = new String[4];
tab_items[0] = "table item 1";
tab_items[1] = "table item 2";
tab_items[2] = "table item 3";
tab_items[3] = "table item 4";
RPCParam in_table = new RPCParam("http://local_service.com/", "Input_Array", tab_items);
RPCElement input = new RPCElement("http://localhost:8000/tester", "echoString",
new Object[]{in_table});
SOAPEnvelope env = new SOAPEnvelope();
env.addBodyElement(input);
String text = env.toString();
assertTrue(text != null);
for(int i=0;i<tab_items.length;i++){
assertTrue(text.indexOf(tab_items[i])!=-1);
}
}
}
| 7,224 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestBeanDeser2.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import javax.xml.namespace.QName;
import java.util.Vector;
/**
* Test deserialization of SOAP responses
*/
public class TestBeanDeser2 extends TestCase {
private String header;
private String footer;
private AxisServer server = new AxisServer();
public TestBeanDeser2(String name) {
super(name);
header =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
"<SOAP-ENV:Body>\n";
footer =
"</SOAP-ENV:Body>\n"+
"</SOAP-ENV:Envelope>\n";
TypeMappingRegistry tmr = server.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) tmr.createTypeMapping();
tm.setSupportedEncodings(new String[]{Constants.URI_DEFAULT_SOAP_ENC});
tmr.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
tm.register(test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest")));
tm.register(test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier")));
}
protected Object deserialize(String data)
throws Exception {
Message message = new Message(header + data + footer);
message.setMessageContext(new MessageContext(server));
SOAPEnvelope envelope = (SOAPEnvelope) message.getSOAPEnvelope();
assertNotNull("SOAP envelope should not be null", envelope);
RPCElement body = (RPCElement) envelope.getFirstBody();
assertNotNull("SOAP body should not be null", body);
Vector arglist = body.getParams();
assertNotNull("arglist", arglist);
assertTrue("param.size()<=0 {Should be > 0}", arglist.size() > 0);
RPCParam param = (RPCParam) arglist.get(0);
assertNotNull("SOAP param should not be null", param);
return param.getObjectValue();
}
public void testTravelRequest() throws Exception {
String response =
"<startSearch>\n"+
" <arg0 href=\"#id0\"/>\n"+
"</startSearch>\n"+
"<multiRef id=\"id0\" SOAP-ENC:root=\"0\"\n"+
" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n"+
" xsi:type=\"ns2:SbTravelRequest\"\n"+
" xmlns:ns1=\"http://schemas.xmlsoap.org/soap/envelope/:encodingStyle\"\n"+
" xmlns:ns2=\"http://www.sidestep.com/sbws\">\n"+
"<requestOr xsi:type=\"xsd:string\">SOAP test 1</requestOr>\n"+
"<homeCountry xsi:type=\"xsd:string\">US</homeCountry>\n"+
"<departureLocation xsi:type=\"xsd:string\">SJC</departureLocation>\n"+
"<destinationLocation xsi:type=\"xsd:string\">ATL</destinationLocation>\n"+
"<startDate xsi:type=\"xsd:dateTime\">2002-08-10T13:42:24.024Z</startDate>\n"+
"<endDate xsi:type=\"xsd:dateTime\">2002-06-27T13:42:24.024Z</endDate>\n"+
"<searchTypes xsi:type=\"xsd:string\">AIR:RTACR</searchTypes>\n"+
"<searchParams xsi:nil=\"true\"/>\n"+
"<searchHints xsi:nil=\"true\"/>\n"+
"<supPliers xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"ns2:SbSupplier[1]\">\n"+
" <item href=\"#id1\"/>\n"+
"</supPliers>\n"+
"</multiRef>"+
"<multiRef id=\"id1\" SOAP-ENC:root=\"0\""+
" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""+
" xsi:type=\"ns3:SbSupplier\""+
" xmlns:ns3=\"http://www.sidestep.com/sbws\">"+
" <searchType xsi:type=\"xsd:int\">0</searchType>"+
" <supplierCode xsi:type=\"xsd:string\">SC**</supplierCode>"+
" <chanNel xsi:type=\"xsd:string\">CN**</chanNel>"+
"</multiRef>";
test.encoding.beans.SbTravelRequest travelRequest = (test.encoding.beans.SbTravelRequest) deserialize(response);
assertNotNull("supPliers array missing", travelRequest.supPliers);
assertTrue(travelRequest.supPliers.length==1);
assertTrue(travelRequest.supPliers[0].searchType.intValue()==0);
assertTrue(travelRequest.supPliers[0].supplierCode.equals("SC**"));
assertTrue(travelRequest.supPliers[0].chanNel.equals("CN**"));
}
public static void main(String [] args) throws Exception
{
TestBeanDeser2 tester = new TestBeanDeser2("test");
tester.testTravelRequest();
}
}
| 7,225 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestBeanDeser3.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import javax.xml.namespace.QName;
import java.util.Vector;
/**
* Test deserialization of SOAP responses. Test case for Bug 25179
* (BeanDeserializer cannot deserialize child array unless xsi:type="SE:Array" provided)
*/
public class TestBeanDeser3 extends TestCase {
private String header;
private String footer;
private AxisServer server = new AxisServer();
public TestBeanDeser3(String name) {
super(name);
header =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
"<SOAP-ENV:Body>\n";
footer =
"</SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>\n";
TypeMappingRegistry tmr = server.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) tmr.createTypeMapping();
tm.setSupportedEncodings(new String[]{Constants.URI_DEFAULT_SOAP_ENC});
tmr.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
tm.register(test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.beans.SbTravelRequest.class,
new QName("http://www.sidestep.com/sbws", "SbTravelRequest")));
tm.register(test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier"),
new org.apache.axis.encoding.ser.BeanSerializerFactory(
test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier")),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(
test.encoding.beans.SbSupplier.class,
new QName("http://www.sidestep.com/sbws", "SbSupplier")));
}
protected Object deserialize(String data)
throws Exception {
Message message = new Message(header + data + footer);
message.setMessageContext(new MessageContext(server));
SOAPEnvelope envelope = (SOAPEnvelope) message.getSOAPEnvelope();
assertNotNull("SOAP envelope should not be null", envelope);
RPCElement body = (RPCElement) envelope.getFirstBody();
assertNotNull("SOAP body should not be null", body);
Vector arglist = body.getParams();
assertNotNull("arglist", arglist);
assertTrue("param.size()<=0 {Should be > 0}", arglist.size() > 0);
RPCParam param = (RPCParam) arglist.get(0);
assertNotNull("SOAP param should not be null", param);
return param.getObjectValue();
}
public void testTravelRequest() throws Exception {
String response =
"<startSearch>\n" +
" <arg0 href=\"#id0\"/>\n" +
"</startSearch>\n" +
"<multiRef id=\"id0\" SOAP-ENC:root=\"0\"\n" +
" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
" xsi:type=\"ns2:SbTravelRequest\"\n" +
" xmlns:ns1=\"http://schemas.xmlsoap.org/soap/envelope/:encodingStyle\"\n" +
" xmlns:ns2=\"http://www.sidestep.com/sbws\">\n" +
"<requestOr xsi:type=\"xsd:string\">SOAP test 1</requestOr>\n" +
"<homeCountry xsi:type=\"xsd:string\">US</homeCountry>\n" +
"<departureLocation xsi:type=\"xsd:string\">SJC</departureLocation>\n" +
"<destinationLocation xsi:type=\"xsd:string\">ATL</destinationLocation>\n" +
"<startDate xsi:type=\"xsd:dateTime\">2002-08-10T13:42:24.024Z</startDate>\n" +
"<endDate xsi:type=\"xsd:dateTime\">2002-06-27T13:42:24.024Z</endDate>\n" +
"<searchTypes xsi:type=\"xsd:string\">AIR:RTACR</searchTypes>\n" +
"<searchParams xsi:nil=\"true\"/>\n" +
"<searchHints xsi:nil=\"true\"/>\n" +
"<supPliers xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"ns2:SbSupplier[1]\">\n" +
" <item href=\"#id1\"/>\n" +
"</supPliers>\n" +
"</multiRef>" +
"<multiRef id=\"id1\" SOAP-ENC:root=\"0\"" +
" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"" +
" xsi:type=\"ns3:SbSupplier\"" +
" xmlns:ns3=\"http://www.sidestep.com/sbws\">" +
" <searchType xsi:type=\"xsd:int\">0</searchType>" +
" <supplierCode xsi:type=\"xsd:string\">SC**</supplierCode>" +
" <chanNel xsi:type=\"xsd:string\">CN**</chanNel>" +
"<listOfStrings " +
"SOAP-ENC:arrayType=\"xsd:string[3]\"> " +
"<item xsi:type=\"xsd:string\">abc</item>" +
"<item xsi:nil=\"true\"/>" +
"<item xsi:type=\"xsd:string\">def</item>" +
"</listOfStrings>" +
"</multiRef>";
test.encoding.beans.SbTravelRequest travelRequest = (test.encoding.beans.SbTravelRequest) deserialize(response);
assertNotNull("supPliers array missing", travelRequest.supPliers);
assertTrue(travelRequest.supPliers.length == 1);
assertTrue(travelRequest.supPliers[0].searchType.intValue() == 0);
assertTrue(travelRequest.supPliers[0].supplierCode.equals("SC**"));
assertTrue(travelRequest.supPliers[0].chanNel.equals("CN**"));
}
public static void main(String[] args) throws Exception {
TestBeanDeser3 tester = new TestBeanDeser3("test");
tester.testTravelRequest();
}
}
| 7,226 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestHrefs.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import java.util.Vector;
/**
* Test deserialization of SOAP messages with references, by putting the
* actual value in various places in the message.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestHrefs extends TestCase {
private String header;
private String [] messageParts;
public TestHrefs(String name) {
this(name, Constants.URI_DEFAULT_SCHEMA_XSI,
Constants.URI_DEFAULT_SCHEMA_XSD);
}
public TestHrefs(String name, String NS_XSI, String NS_XSD) {
super(name);
header =
"<?xml version=\"1.0\"?>\n" +
"<soap:Envelope " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:xsi=\"" + NS_XSI + "\" " +
"xmlns:xsd=\"" + NS_XSD + "\">\n" +
"<soap:Body>\n" +
"<methodResult xmlns=\"http://tempuri.org/\">\n" +
"<reference href=\"#1\"/>\n" +
"</methodResult>\n";
messageParts = new String [] {
"</soap:Body>\n",
"</soap:Envelope>\n" };
}
private void deserialize(String data, Object expected, int pos)
throws Exception
{
String msgString = header;
for (int i = 0; i < messageParts.length; i++) {
if (pos == i)
msgString += data;
msgString += messageParts[i];
}
Message message = new Message(msgString);
message.setMessageContext(new MessageContext(new AxisServer()));
SOAPEnvelope envelope = (SOAPEnvelope)message.getSOAPEnvelope();
assertNotNull("SOAP envelope should not be null", envelope);
RPCElement body = (RPCElement)envelope.getFirstBody();
assertNotNull("SOAP body should not be null", body);
Vector arglist = body.getParams();
assertNotNull("arglist", arglist);
assertTrue("SOAP param.size()<=0 {Should be > 0}", arglist.size()>0);
RPCParam param = (RPCParam) arglist.get(0);
assertNotNull("SOAP param should not be null", param);
Object result = param.getObjectValue();
assertEquals("Expected result not received for case " + pos, expected, result);
}
public void testStringReference1() throws Exception {
String result =
"<result root=\"0\" id=\"1\" xsi:type=\"xsd:string\">abc</result>";
deserialize(result, "abc", 0);
}
public void testStringReference2() throws Exception {
String result =
"<result root=\"0\" id=\"1\" xsi:type=\"xsd:string\">abc</result>";
deserialize(result, "abc", 1);
}
public void testIntReference1() throws Exception {
String result =
"<result root=\"0\" id=\"1\" xsi:type=\"xsd:int\">567</result>";
deserialize(result, new Integer(567), 0);
}
}
| 7,227 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestMultiRefIdentity.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 test.encoding;
import junit.framework.TestCase;
import org.apache.axis.encoding.SerializationContext;
import javax.xml.namespace.QName;
import java.io.CharArrayWriter;
/**
* @author John Gregg (john.gregg@techarch.com)
* @author $Author$
* @version $Revision$
*/
public class TestMultiRefIdentity extends TestCase {
/**
Tests when beans are identical and use default hashCode().
*/
public void testIdentity1() throws Exception {
TestBeanA tb1 = new TestBeanA();
tb1.s1 = "john";
TestBeanA tb2 = tb1;
CharArrayWriter caw = new CharArrayWriter();
SerializationContext sci = new SerializationContext(caw);
sci.setDoMultiRefs(true);
sci.serialize(new QName("someLocalPart"), null, tb1);
sci.serialize(new QName("someOtherLocalPart"), null, tb2);
String s = caw.toString();
// Cheap but fragile.
int first = s.indexOf("#id0");
int last = s.lastIndexOf("#id0");
assertTrue(s, first >= 0);
assertTrue(s, last >= 0 && last != first);
}
/**
Tests when beans are identical and use their own hashCode().
*/
public void testIdentity2() throws Exception {
TestBeanB tb1 = new TestBeanB();
tb1.s1 = "john";
TestBeanB tb2 = tb1;
CharArrayWriter caw = new CharArrayWriter();
SerializationContext sci = new SerializationContext(caw);
sci.setDoMultiRefs(true);
sci.serialize(new QName("someLocalPart"), null, tb1);
sci.serialize(new QName("someOtherLocalPart"), null, tb2);
String s = caw.toString();
// Cheap but fragile.
int first = s.indexOf("#id0");
int last = s.lastIndexOf("#id0");
assertTrue(s,first >= 0);
assertTrue(s,last >= 0 && last != first);
}
/**
Tests when beans have different contents and rely on default hashCode().
*/
public void testEquality1() throws Exception {
TestBeanA tb1 = new TestBeanA();
tb1.s1 = "john";
TestBeanA tb2 = new TestBeanA();
tb2.s1 = "gregg";
CharArrayWriter caw = new CharArrayWriter();
SerializationContext sci = new SerializationContext(caw);
sci.setDoMultiRefs(true);
sci.serialize(new QName("someLocalPart"), null, tb1);
sci.serialize(new QName("someOtherLocalPart"), null, tb2);
String s = caw.toString();
// Cheap but fragile.
int first = s.indexOf("#id0");
int last = s.lastIndexOf("#id1");
assertTrue(s,first >= 0);
assertTrue(s,last >= 0);
}
/**
Tests when beans have same contents but rely on default hashCode().
*/
public void testEquality2() throws Exception {
TestBeanA tb1 = new TestBeanA();
tb1.s1 = "john";
TestBeanA tb2 = new TestBeanA();
tb2.s1 = "john";
CharArrayWriter caw = new CharArrayWriter();
SerializationContext sci = new SerializationContext(caw);
sci.setDoMultiRefs(true);
sci.serialize(new QName("someLocalPart"), null, tb1);
sci.serialize(new QName("someOtherLocalPart"), null, tb2);
String s = caw.toString();
// Cheap but fragile.
int first = s.indexOf("#id0");
int last = s.lastIndexOf("#id1");
assertTrue(s,first >= 0);
assertTrue(s,last >= 0);
}
/**
Tests when beans have same contents and use their own hashCode().
*/
public void testEquality3() throws Exception {
TestBeanB tb1 = new TestBeanB();
tb1.s1 = "john";
TestBeanB tb2 = new TestBeanB();
tb2.s1 = "john";
CharArrayWriter caw = new CharArrayWriter();
SerializationContext sci = new SerializationContext(caw);
sci.setDoMultiRefs(true);
sci.serialize(new QName("someLocalPart"), null, tb1);
sci.serialize(new QName("someOtherLocalPart"), null, tb2);
String s = caw.toString();
// Cheap but fragile.
int first = s.indexOf("#id0");
int last = s.lastIndexOf("#id1");
assertTrue(s,first >= 0);
assertTrue(s,last >= 0 && last != first);
}
class TestBeanA {
String s1 = null;
// uses default equals() and hashCode().
}
class TestBeanB {
String s1 = null;
public boolean equals(Object o) {
if (o == null) return false;
if (this == o) return true;
if (!o.getClass().equals(this.getClass())) return false;
TestBeanB tbb = (TestBeanB)o;
if (this.s1 != null) {
return this.s1.equals(tbb.s1);
} else {
return this.s1 == tbb.s1;
}
}
public int hashCode() {
// XXX???
if (this.s1 == null) return super.hashCode();
else return this.s1.hashCode();
}
}
}
| 7,228 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/AttributeBean.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 test.encoding;
import org.apache.axis.description.AttributeDesc;
import org.apache.axis.description.ElementDesc;
import org.apache.axis.description.FieldDesc;
import org.apache.axis.description.TypeDesc;
import javax.xml.namespace.QName;
/**
* Simple Java Bean with fields that should be serialized as attributes
*/
public class AttributeBean extends ParentBean {
private int age;
private float iD;
public String company; // element without getter/setter
private java.lang.String name; // attribute
private boolean male; // attribute
public AttributeBean() {}
public AttributeBean(int age, float iD, String name, String company, boolean male) {
this.age = age;
this.iD = iD;
this.name = name;
this.male = male;
this.company = company;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getID() {
return iD;
}
public void setID(float iD) {
this.iD = iD;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public boolean getMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof AttributeBean))
return false;
AttributeBean other = (AttributeBean)obj;
if (other.getAge() != age)
return false;
if (other.getID() != iD)
return false;
if (other.getMale() != male)
return false;
if (name == null) {
if (other.getName() != null) {
return false;
}
}else if (!name.equals(other.getName())) {
return false;
}
if (company == null) {
if (other.company != null) {
return false;
}
} else if (!company.equals(other.company)) {
return false;
}
if (getParentFloat() != other.getParentFloat())
return false;
if (getParentStr() != null) {
return getParentStr().equals(other.getParentStr());
}
return other.getParentStr() == null;
}
// Type metadata
private static TypeDesc typeDesc;
static {
typeDesc = new TypeDesc(AttributeBean.class);
FieldDesc field;
// An attribute with a specified QName
field = new AttributeDesc();
field.setFieldName("name");
field.setXmlName(new QName("foo", "nameAttr"));
typeDesc.addFieldDesc(field);
// An attribute with a default QName
field = new AttributeDesc();
field.setFieldName("male");
typeDesc.addFieldDesc(field);
// An element with a specified QName
field = new ElementDesc();
field.setFieldName("age");
field.setXmlName(new QName("foo", "ageElement"));
typeDesc.addFieldDesc(field);
}
public static TypeDesc getTypeDesc()
{
return typeDesc;
}
}
| 7,229 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestString3.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.server.AxisServer;
import org.xml.sax.InputSource;
import javax.xml.soap.SOAPMessage;
import java.io.ByteArrayInputStream;
/**
* line feed normalization and character reference processing
*/
public class TestString3 extends TestCase {
public static final String myNS = "urn:myNS";
static String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<soapenv:Body>" +
"<ns1:method1 xmlns:ns1=\"urn:myNamespace\">" +
"<ns1:testParam xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">";
static String xml2 =
"</ns1:testParam>" +
"</ns1:method1>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
private void runtest(String value, String expected) throws Exception {
MessageContext msgContext = new MessageContext(new AxisServer());
String requestEncoding = "UTF-8";
msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
String xml = xml1 + value + xml2;
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
DeserializationContext dser = new DeserializationContext(
new InputSource(bais), msgContext, org.apache.axis.Message.REQUEST);
dser.parse();
org.apache.axis.message.SOAPEnvelope env = dser.getEnvelope();
RPCElement rpcElem = (RPCElement)env.getFirstBody();
RPCParam output = rpcElem.getParam("testParam");
assertNotNull("No <testParam> param", output);
String nodeValue = (String) output.getObjectValue();
assertNotNull("No node value for testParam param", nodeValue);
assertEquals(expected, nodeValue);
}
public void testEntitizedCRLF() throws Exception {
runtest("
Hello
World
", "\r\nHello\r\nWorld\r\n");
}
public void testPlainCRLF() throws Exception {
runtest("\r\nHello\r\nWorld\r\n", "\nHello\nWorld\n");
}
public void testEntitizedCR() throws Exception {
runtest("
Hello
World
", "\rHello\rWorld\r");
}
public void testPlainCR() throws Exception {
runtest("\rHello\rWorld\r", "\nHello\nWorld\n");
}
}
| 7,230 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestAutoTypes.java | package test.encoding;
import javax.xml.namespace.QName;
import junit.framework.TestCase;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.encoding.TypeMappingDelegate;
import org.apache.axis.server.AxisServer;
import org.apache.axis.wsdl.fromJava.Namespaces;
import org.apache.axis.wsdl.fromJava.Types;
/**
* Test auto-typing.
*/
public class TestAutoTypes extends TestCase {
private AxisServer server = new AxisServer();
public void testAutoTypes() throws Exception
{
TypeMappingRegistry tmr = server.getTypeMappingRegistry();
TypeMappingDelegate tm = (TypeMappingDelegate)tmr.getDefaultTypeMapping();
tm.setDoAutoTypes(true);
QName qname = tm.getTypeQName( AttributeBean.class );
assertEquals( "http://encoding.test",
qname.getNamespaceURI() );
assertEquals( "AttributeBean", qname.getLocalPart() );
assertTrue( tm.getDeserializer(qname) != null );
assertTrue( tm.getSerializer(AttributeBean.class) != null );
assertEquals(
"http://encoding.test",
Namespaces.makeNamespace(AttributeBean[].class.getName()));
assertEquals(
"AttributeBean[]",
Types.getLocalNameFromFullName(AttributeBean[].class.getName()));
// qname = tm.getTypeQName( AttributeBean[].class );
// assertEquals( "http://encoding.test",
// qname.getNamespaceURI() );
// assertEquals( "AttributeBean[]", qname.getLocalPart() );
}
}
| 7,231 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestXsiType.java | package test.encoding;
import junit.framework.TestCase;
import org.apache.axis.AxisEngine;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import java.io.StringWriter;
import java.io.Writer;
/**
* Verify that shutting off xsi:types in the Message Context works
* as expected.
*/
public class TestXsiType extends TestCase {
private SimpleProvider provider = new SimpleProvider();
private AxisServer server = new AxisServer(provider);
/**
* Trivial test just to make sure there aren't xsi:type attributes
*/
public void testNoXsiTypes()
throws Exception
{
MessageContext msgContext = new MessageContext(server);
// Don't serialize xsi:type attributes
msgContext.setProperty(Call.SEND_TYPE_ATTR, "false" );
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg1 = new RPCParam("urn:myNamespace",
"testParam",
"this is a string");
RPCElement body = new RPCElement("urn:myNamespace",
"method1",
new Object[]{ arg1 });
msg.addBodyElement(body);
Writer stringWriter = new StringWriter();
SerializationContext context = new SerializationContext(stringWriter,
msgContext);
msg.output(context);
String msgString = stringWriter.toString();
assertTrue("Found unexpected xsi:type!",
msgString.indexOf("xsi:type") == -1);
}
/**
* More complex test which checks to confirm that we can still
* in fact deserialize if we know the type via the Call object.
*/
public void testTypelessDeserialization() throws Exception
{
server.setOption(AxisEngine.PROP_SEND_XSI, Boolean.FALSE);
SOAPService service = new SOAPService(new RPCProvider());
service.setOption("className", "test.encoding.TestXsiType");
service.setOption("allowedMethods", "*");
provider.deployService("TestService", service);
// Call that same server, accessing a method we know returns
// a double. We should figure this out and deserialize it
// correctly, even without the xsi:type attribute, because
// we set the return type manually.
Service S_service = new Service();
Call call = (Call) S_service.createCall();
call.setTransport(new LocalTransport(server));
call.setReturnType(XMLType.XSD_DOUBLE);
Object result = call.invoke("TestService",
"serviceMethod",
new Object [] {});
assertTrue("Return value (" + result.getClass().getName() +
") was not the expected type (Double)!",
(result instanceof Double));
}
/**
* A method for our service, returning a double.
*/
public double serviceMethod()
{
return 3.14159;
}
}
| 7,232 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/DataDeserFactory.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 test.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.DeserializerFactory;
import java.util.Iterator;
import java.util.Vector;
/**
* DeserializerFactory for DataDeser
*
* @author Rich Scheuerle <scheu@us.ibm.com>
*/
public class DataDeserFactory implements DeserializerFactory {
private Vector mechanisms;
public DataDeserFactory() {
}
public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType) {
return new DataDeser();
}
public Iterator getSupportedMechanismTypes() {
if (mechanisms == null) {
mechanisms = new Vector();
mechanisms.add(Constants.AXIS_SAX);
}
return mechanisms.iterator();
}
}
| 7,233 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/TestDefaultTM.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 test.encoding;
import junit.framework.TestCase;
import org.apache.axis.encoding.TypeMappingRegistryImpl;
import org.apache.axis.Constants;
import javax.xml.rpc.encoding.TypeMapping;
/**
* Default Type Mapping tests
*/
public class TestDefaultTM extends TestCase {
/**
* This test makes sure that there aren't any SOAPENC types
* mapped in the default type mappings for any of the valid
* "version" strings.
*
* @throws Exception
*/
public void testNoSOAPENCTypes() throws Exception {
checkTypes(null);
checkTypes("1.0");
checkTypes("1.1");
checkTypes("1.2");
checkTypes("1.3");
}
private void checkTypes(String version) throws Exception {
TypeMappingRegistryImpl tmr = new TypeMappingRegistryImpl();
tmr.doRegisterFromVersion(version);
TypeMapping tm = tmr.getDefaultTypeMapping();
assertNull("Found mapping for soapenc:string in TM version " + version,
tm.getDeserializer(null, Constants.SOAP_STRING));
}
}
| 7,234 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/beans/SbSupplier.java | package test.encoding.beans;
public class SbSupplier implements java.io.Serializable
{
public SbSupplier(){}
public Integer searchType;
public String supplierCode;
public String chanNel;
public String[] listOfStrings;
}
| 7,235 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/encoding/beans/SbTravelRequest.java | package test.encoding.beans;
public class SbTravelRequest implements java.io.Serializable
{
public SbTravelRequest(){}
public String requestOr;
public String homeCountry;
public String departureLocation;
public String destinationLocation;
public java.util.GregorianCalendar startDate;
public java.util.GregorianCalendar endDate;
public String searchTypes;
public String searchParams;
public String searchHints;
public SbSupplier[] supPliers;
}
| 7,236 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/MSGDispatch/TestMessageService.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 test.MSGDispatch;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.configuration.BasicServerConfig;
import org.apache.axis.constants.Style;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.providers.java.MsgProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.util.Vector;
import java.util.Iterator;
/**
* Test for message style service dispatch.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestMessageService extends TestCase {
LocalTransport transport;
protected void setUp() throws Exception {
SOAPService service = new SOAPService(new MsgProvider());
service.setName("MessageService");
service.setOption("className", "test.MSGDispatch.TestService");
service.setOption("allowedMethods", "*");
service.getServiceDescription().setDefaultNamespace("http://db.com");
service.getServiceDescription().setStyle(Style.MESSAGE);
SimpleProvider config = new BasicServerConfig();
config.deployService("MessageService", service);
AxisServer server = new AxisServer(config);
transport = new LocalTransport(server);
transport.setRemoteService("MessageService");
}
public void testBodyMethod() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
String xml = "<m:testBody xmlns:m=\"http://db.com\"></m:testBody>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
SOAPBodyElement[] input = new SOAPBodyElement[1];
input[0] = new SOAPBodyElement(doc.getDocumentElement());
Vector elems = (Vector) call.invoke( input );
assertNotNull("Return was null!", elems);
assertTrue("Return had " + elems.size() + " elements (needed 1)",
elems.size() == 1);
SOAPBodyElement firstBody = (SOAPBodyElement)elems.get(0);
assertEquals("http://db.com", firstBody.getNamespaceURI());
assertEquals("bodyResult", firstBody.getName());
}
public void testElementMethod() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
String xml = "<m:testElement xmlns:m=\"http://db.com\"></m:testElement>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
SOAPBodyElement[] input = new SOAPBodyElement[1];
input[0] = new SOAPBodyElement(doc.getDocumentElement());
Vector elems = (Vector) call.invoke( input );
assertNotNull("Return was null!", elems);
assertTrue("Return had " + elems.size() + " elements (needed 1)",
elems.size() == 1);
SOAPBodyElement firstBody = (SOAPBodyElement)elems.get(0);
assertEquals("http://db.com", firstBody.getNamespaceURI());
assertEquals("elementResult", firstBody.getName());
}
public void testEnvelopeMethod() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
String xml = "<testEnvelope xmlns=\"http://db.com\"></testEnvelope>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
SOAPBodyElement body = new SOAPBodyElement(doc.getDocumentElement());
SOAPEnvelope env = new SOAPEnvelope();
env.addBodyElement(body);
SOAPEnvelope result = call.invoke( env );
assertNotNull("Return was null!", result);
SOAPBodyElement respBody = result.getFirstBody();
assertEquals(new QName("http://db.com", "testEnvelope"), respBody.getQName());
Iterator i = respBody.getNamespacePrefixes();
assertNotNull("No namespace mappings");
assertEquals("Non-default namespace found", "", i.next());
assertTrue("Multiple namespace mappings", !i.hasNext());
Vector headers = result.getHeaders();
assertEquals("Had " + headers.size() + " headers, needed 1", 1, headers.size());
SOAPHeaderElement firstHeader = (SOAPHeaderElement)headers.get(0);
assertEquals("http://db.com", firstHeader.getNamespaceURI());
assertEquals("local", firstHeader.getName());
assertEquals(firstHeader.getValue(), "value");
}
/**
* Confirm that we get back EXACTLY what we put in when using the
* Element[]/Element[] signature for MESSAGE services.
*
* @throws Exception
*/
public void testElementEcho() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
// Create a DOM document using a default namespace, since bug
// http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16666 indicated
// that we might have had a problem here.
String xml = "<testElementEcho xmlns=\"http://db.com\" attr='foo'><Data></Data></testElementEcho>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
SOAPBodyElement body = new SOAPBodyElement(doc.getDocumentElement());
SOAPEnvelope env = new SOAPEnvelope();
env.addBodyElement(body);
// Send it along
SOAPEnvelope result = call.invoke( env );
assertNotNull("Return was null!", result);
// Make sure we get back exactly what we expect, with no extraneous
// namespace mappings
SOAPBodyElement respBody = result.getFirstBody();
assertEquals(new QName("http://db.com", "testElementEcho"), respBody.getQName());
Iterator i = respBody.getNamespacePrefixes();
assertNotNull("No namespace mappings");
assertEquals("Non-default namespace found", "", i.next());
assertTrue("Multiple namespace mappings", !i.hasNext());
}
}
| 7,237 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/MSGDispatch/TestService.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 test.MSGDispatch;
import org.apache.axis.AxisFault;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* This class is a message-based service with three methods. It tests:
*
* 1) Our ability to dispatch to multiple methods for a message service
* 2) That each of the valid signatures works as expected
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestService {
// Adding these dummy methods to make sure that when we deploy this
// service using "allowedMethods="*" that we don't barf on them.
// This will ensure that people can take classes that have public
// methods (some available thru Axis and some not) and still be able
// to deploy them. (We used to throw exceptions about it)
public void testBody(int t) {}
public void testElement(int t) {}
public void testEnvelope(int t) {}
public SOAPBodyElement [] testBody(SOAPBodyElement [] bodies)
throws Exception {
String xml = "<m:bodyResult xmlns:m=\"http://db.com\"/>" ;
InputStream is = new ByteArrayInputStream(xml.getBytes());
SOAPBodyElement result = new SOAPBodyElement(is);
return new SOAPBodyElement [] { result };
}
public Element [] testElement(Element [] bodyElems)
throws Exception {
if (bodyElems == null || bodyElems.length != 1) {
throw new AxisFault("Wrong number of Elements in array!");
}
Element el = bodyElems[0];
if (el == null) {
throw new AxisFault("Null Element in array!");
}
if (!"http://db.com".equals(el.getNamespaceURI())) {
throw new AxisFault("Wrong namespace for Element (was \"" +
el.getNamespaceURI() + "\" should be " +
"\"http://db.com\"!");
}
String xml = "<m:elementResult xmlns:m=\"http://db.com\"/>" ;
Document doc = XMLUtils.newDocument(
new ByteArrayInputStream(xml.getBytes()));
Element result = doc.getDocumentElement();
return new Element [] { result };
}
public Element [] testElementEcho(Element [] bodyElems)
throws Exception {
return bodyElems;
}
public void testEnvelope(SOAPEnvelope req, SOAPEnvelope resp)
throws Exception {
// Throw a header in and echo back.
SOAPBodyElement body = req.getFirstBody();
resp.addBodyElement(body);
resp.addHeader(new SOAPHeaderElement("http://db.com", "local", "value"));
}
}
| 7,238 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestJavaSerialization.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 test.message;
import junit.framework.TestCase;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
/**
* Test certain classes in the message package for java
* serializability.
*
* @author Glyn Normington (glyn@apache.org)
*/
public class TestJavaSerialization extends TestCase {
public void testSOAPEnvelope() throws Exception {
// Create an example SOAP envelope
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
SOAPHeader h = env.getHeader();
SOAPBody b = env.getBody();
Name heName = env.createName("localName", "prefix", "http://uri");
SOAPHeaderElement he = h.addHeaderElement(heName);
he.setActor("actor");
// Serialize the SOAP envelope
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(env);
// Deserializet the SOAP envelope
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream is = new ObjectInputStream(bis);
SOAPEnvelope env2 = (SOAPEnvelope)is.readObject();
// Check that the SOAP envelope survived the round trip
SOAPHeader h2 = env2.getHeader();
SOAPHeaderElement he2 = (SOAPHeaderElement)h2.
examineHeaderElements("actor").next();
Name heName2 = he2.getElementName();
assertEquals("Local name did not survive java ser+deser",
heName.getLocalName(), heName2.getLocalName());
assertEquals("Prefix did not survive java ser+deser",
heName.getPrefix(), heName2.getPrefix());
assertEquals("URI did not survive java ser+deser",
heName.getURI(), heName2.getURI());
}
public void testCDATASection() throws Exception {
// Create a SOAP envelope
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
SOAPBody body = env.getBody();
SOAPBodyElement[] input = new SOAPBodyElement[3];
input[0] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "Hello"));
input[1] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "World"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element cdataElem = doc.createElementNS("urn:foo", "e3");
CDATASection cdata = doc.createCDATASection("Text with\n\tImportant <b> whitespace </b> and tags! ");
cdataElem.appendChild(cdata);
input[2] = new SOAPBodyElement(cdataElem);
for(int i=0; i<input.length; i++) {
body.addChildElement(input[i]);
}
ByteArrayInputStream bais = new ByteArrayInputStream(env.toString().getBytes());
SOAPEnvelope env2 = new org.apache.axis.message.SOAPEnvelope(bais);
Iterator iterator = env2.getBody().getChildElements();
Element element = null;
for(int i=0;iterator.hasNext();i++) {
MessageElement e = (MessageElement) iterator.next();
element = e.getAsDOM();
}
String xml = element.getFirstChild().getNodeValue();
assertEquals(xml, cdata.getData());
}
public void testComments() throws Exception {
// Create a SOAP envelope
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
SOAPBody body = env.getBody();
SOAPBodyElement[] input = new SOAPBodyElement[3];
input[0] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "Hello"));
input[1] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "World"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element commentsElem = doc.createElementNS("urn:foo", "e3");
Text text = doc.createTextNode("This is a comment");
commentsElem.appendChild(text);
input[2] = new SOAPBodyElement(commentsElem);
for(int i=0; i<input.length; i++) {
body.addChildElement(input[i]);
}
ByteArrayInputStream bais = new ByteArrayInputStream(env.toString().getBytes());
SOAPEnvelope env2 = new org.apache.axis.message.SOAPEnvelope(bais);
Iterator iterator = env2.getBody().getChildElements();
Element element = null;
for(int i=0;iterator.hasNext();i++) {
MessageElement e = (MessageElement) iterator.next();
element = e.getAsDOM();
}
String xml = element.getFirstChild().getNodeValue();
assertEquals(xml, text.getData());
}
}
| 7,239 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestMessageSerialization.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 test.message;
import junit.framework.TestCase;
import org.apache.axis.Message;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.ByteArrayInputStream;
/**
* Test serializability of org.apache.axis.Message
*
* @author Davanum Srinivas (dims@yahoo.com)
*/
public class TestMessageSerialization extends TestCase {
public void test1() throws Exception {
String messageText = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ "<soap:Header>"
+ "</soap:Header> "
+ "<soap:Body> "
+ "</soap:Body>"
+ "</soap:Envelope>";
Message message = new Message(messageText);
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(ostream);
os.writeObject(message);
ostream.flush();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ostream.toByteArray()));
Message m2 = (Message) ois.readObject();
}
}
| 7,240 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestSOAPBody.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 test.message;
import junit.framework.TestCase;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.apache.axis.Message;
/**
* @author john.gregg@techarch.com
* @author $Author$
* @version $Revision$
*/
public class TestSOAPBody extends TestCase {
/**
* Constructor TestSOAPBody
*
* @param name
*/
public TestSOAPBody(String name) {
super(name);
}
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <soapenv:Header>\n" +
" <shw:Hello xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n" +
" <shw:Myname>Tony</shw:Myname>\n" +
" </shw:Hello>\n" +
" </soapenv:Header>\n" +
" <soapenv:Body>\n" +
" <shw:Address xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n" +
" <shw:City>GENT</shw:City>\n" +
" </shw:Address>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
/**
* Method testSoapBodyBUG
*
* @throws Exception
*/
public void testSoapBodyBUG() throws Exception {
MimeHeaders mimeheaders = new MimeHeaders();
mimeheaders.addHeader("Content-Type", "text/xml");
ByteArrayInputStream instream = new ByteArrayInputStream(xmlString.getBytes());
MessageFactory factory =
MessageFactory.newInstance();
SOAPMessage msg =
factory.createMessage(mimeheaders, instream);
org.apache.axis.client.AxisClient axisengine =
new org.apache.axis.client.AxisClient();
// need to set it not null , if not nullpointer in sp.getEnvelope()
((org.apache.axis.Message) msg).setMessageContext(
new org.apache.axis.MessageContext(axisengine));
SOAPPart sp = msg.getSOAPPart();
javax.xml.soap.SOAPEnvelope se = sp.getEnvelope();
javax.xml.soap.SOAPHeader sh = se.getHeader();
SOAPBody sb = se.getBody();
Iterator it = sb.getChildElements();
int count = 0;
while (it.hasNext()) {
SOAPBodyElement el = (SOAPBodyElement) it.next();
count++;
Name name = el.getElementName();
System.out.println("Element:" + el);
System.out.println("BODY ELEMENT NAME:" + name.getPrefix() + ":"
+ name.getLocalName() + " " + name.getURI());
}
assertTrue(count == 1);
}
/**
* Method testSaveChanges
*
* @throws Exception
*/
public void testSaveChanges() throws Exception {
MimeHeaders mimeheaders = new MimeHeaders();
mimeheaders.addHeader("Content-Type", "text/xml");
ByteArrayInputStream instream = new ByteArrayInputStream(xmlString.getBytes());
MessageFactory factory =
MessageFactory.newInstance();
SOAPMessage msg =
factory.createMessage(mimeheaders, instream);
org.apache.axis.client.AxisClient axisengine =
new org.apache.axis.client.AxisClient();
((Message) msg).setMessageContext(
new org.apache.axis.MessageContext(axisengine));
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
Node myNode = (Element) sb.getElementsByTagName("City").item(0);
myNode.replaceChild( myNode.getOwnerDocument().createTextNode("NY"), myNode.getFirstChild());
msg.saveChanges();
sp = msg.getSOAPPart();
se = sp.getEnvelope();
sb = se.getBody();
myNode = (Element) sb.getElementsByTagName("City").item(0);
Node city = myNode.getFirstChild();
assertEquals("City name did not change to NY", city.toString(), "NY");
}
}
| 7,241 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestMUValues.java | package test.message;
import junit.framework.TestCase;
import org.apache.axis.AxisEngine;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.server.AxisServer;
/**
* This test confirms the behavior of the various possible values for
* the mustUnderstand attribute in both SOAP 1.1 and SOAP 1.2. In particular:
*
* For SOAP 1.1, the only valid values are "0" and "1"
* For SOAP 1.2, "0"/"false" and "1"/"true" are valid
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestMUValues extends TestCase {
private AxisEngine engine;
private String header =
"<?xml version=\"1.0\"?>\n" +
"<soap:Envelope " +
"xmlns:soap=\"";
private String middle = "\">\n" +
"<soap:Header>\n" +
"<test soap:mustUnderstand=\"";
private String footer =
"\"/>\n" +
"</soap:Header>\n" +
"<soap:Body>\n" +
"<noContent/>\n" +
"</soap:Body>\n" +
"</soap:Envelope>\n";
public void setUp() throws Exception {
SimpleProvider provider = new SimpleProvider();
engine = new AxisServer(provider);
}
public void checkVal(String val, boolean desiredResult, String ns)
throws Exception {
String request = header + ns + middle + val + footer;
// create a message in context
MessageContext msgContext = new MessageContext(engine);
Message message = new Message(request);
message.setMessageContext(msgContext);
// Parse the message and check the mustUnderstand value
SOAPEnvelope envelope = message.getSOAPEnvelope();
SOAPHeaderElement header = envelope.getHeaderByName("", "test");
assertEquals("MustUnderstand value wasn't right using value '" +
val + "'",
desiredResult, header.getMustUnderstand());
}
public void testMustUnderstandValues() throws Exception {
String soap12 = Constants.URI_SOAP12_ENV;
String soap11 = Constants.URI_SOAP11_ENV;
checkVal("0", false, soap12);
checkVal("1", true, soap12);
checkVal("true", true, soap12);
checkVal("false", false, soap12);
try {
checkVal("dennis", false, soap12);
fail("Didn't throw exception with bad MU value");
} catch (Exception e) {
}
checkVal("0", false, soap11);
checkVal("1", true, soap11);
try {
checkVal("true", false, soap11);
fail("Didn't throw exception with bad MU value");
} catch (Exception e) {
}
try {
checkVal("false", false, soap11);
fail("Didn't throw exception with bad MU value");
} catch (Exception e) {
}
try {
checkVal("dennis", false, soap11);
fail("Didn't throw exception with bad MU value");
} catch (Exception e) {
}
}
}
| 7,242 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestSOAPFault.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 test.message;
import junit.framework.TestCase;
import javax.xml.soap.Detail;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import org.apache.axis.AxisFault;
import org.w3c.dom.Element;
import java.io.InputStream;
import java.util.Iterator;
/**
* @author steve.johnson@riskmetrics.com (Steve Johnson)
* @author Davanum Srinivas (dims@yahoo.com)
* @author Andreas Veithen
*
* @version $Revision$
*/
public class TestSOAPFault extends TestCase {
/**
* Regression test for AXIS-1008.
*
* @throws Exception
*/
public void testAxis1008() throws Exception {
InputStream in = TestSOAPFault.class.getResourceAsStream("AXIS-1008.xml");
try {
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage msg = msgFactory.createMessage(null, in);
//now attempt to access the fault
if (msg.getSOAPPart().getEnvelope().getBody().hasFault()) {
SOAPFault fault =
msg.getSOAPPart().getEnvelope().getBody().getFault();
System.out.println("Fault: " + fault.getFaultString());
}
} finally {
in.close();
}
}
/**
* Regression test for AXIS-2705. The issue occurs when a SOAP fault has a detail element
* containing text (and not elements). Note that such a SOAP fault violates the SOAP spec, but
* Axis should nevertheless be able to process it.
*
* @throws Exception
*/
public void testAxis2705() throws Exception {
InputStream in = TestSOAPFault.class.getResourceAsStream("AXIS-2705.xml");
try {
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage msg = msgFactory.createMessage(null, in);
SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
assertTrue(body.hasFault());
SOAPFault fault = body.getFault();
AxisFault axisFault = ((org.apache.axis.message.SOAPFault)fault).getFault();
Element[] details = axisFault.getFaultDetails();
assertEquals(1, details.length);
Element detailElement = details[0];
assertEquals("text", detailElement.getTagName());
} finally {
in.close();
}
}
} | 7,243 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestSOAPEnvelope.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 test.message;
import junit.framework.TestCase;
import org.apache.axis.Message;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPHeaderElement;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
/**
* Test SOAPEnvelope class.
*
* @author Glyn Normington (glyn@apache.org)
*/
public class TestSOAPEnvelope extends TestCase {
// Test JAXM methods...
public void testName() throws Exception {
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
Name n = env.createName("local", "pref", "urn:blah");
assertEquals("local part of name did not match", "local",
n.getLocalName());
assertEquals("qname of name did not match", "pref:local",
n.getQualifiedName());
assertEquals("prefix of name did not match", "pref",
n.getPrefix());
assertEquals("uri of name did not match", "urn:blah",
n.getURI());
Name n2 = env.createName("loc");
assertEquals("local part of name2 did not match", "loc",
n2.getLocalName());
}
public void testHeader() throws Exception {
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
SOAPHeader h1 = env.getHeader();
assertTrue("null initial header", h1 != null);
h1.detachNode();
assertTrue("header not freed", env.getHeader() == null);
SOAPHeader h2 = env.addHeader();
assertTrue("null created header", h2 != null);
assertEquals("wrong header retrieved", h2, env.getHeader());
assertEquals("header parent incorrect", env, h2.getParentElement());
try {
env.addHeader();
assertTrue("second header added", false);
} catch (SOAPException e) {
}
}
public void testBody() throws Exception {
SOAPEnvelope env = new org.apache.axis.message.SOAPEnvelope();
SOAPBody b1 = env.getBody();
assertTrue("null initial body", b1 != null);
b1.detachNode();
assertTrue("body not freed", env.getBody() == null);
SOAPBody b2 = env.addBody();
assertTrue("null created body", b2 != null);
assertEquals("wrong body retrieved", b2, env.getBody());
assertEquals("body parent incorrect", env, b2.getParentElement());
try {
env.addBody();
assertTrue("second body added", false);
} catch (SOAPException e) {
}
}
// Test for bug #14570
public void testNullpointer() throws Exception{
org.apache.axis.message.SOAPEnvelope env=new org.apache.axis.message.SOAPEnvelope();
SOAPBodyElement bdy=new SOAPBodyElement();
bdy.setName("testResponse");
env.addBodyElement(bdy);
Message msg=new Message(env);
SOAPBodyElement sbe = msg.getSOAPEnvelope().getBodyByName(null,"testResponse");
assertTrue(sbe != null);
}
// Test for bug 14574
public void testNullpointerInHeader() throws Exception{
org.apache.axis.message.SOAPEnvelope env=new org.apache.axis.message.SOAPEnvelope();
SOAPHeaderElement hdr=new SOAPHeaderElement("", "testHeader");
env.addHeader(hdr);
Message msg=new Message(env);
SOAPHeaderElement she = msg.getSOAPEnvelope().getHeaderByName(null,"testHeader");
assertTrue(she != null);
}
}
| 7,244 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestSOAPHeader.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 test.message;
import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeader;
import org.apache.axis.message.SOAPHeaderElement;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
/**
* @author john.gregg@techarch.com
* @author $Author$
* @version $Revision$
*/
public class TestSOAPHeader extends TestCase {
/** Field ACTOR */
public static final transient String ACTOR = "http://slashdot.org/";
/** Field HEADER_NAMESPACE */
public static final transient String HEADER_NAMESPACE =
"http://xml.apache.org/";
/** Field env */
protected SOAPEnvelope env = null;
/** Field headerElement1 */
protected SOAPHeaderElement headerElement1 = null;
/** Field headerElement2 */
protected SOAPHeaderElement headerElement2 = null;
/**
* Constructor TestSOAPHeader
*
* @param name
*/
public TestSOAPHeader(String name) {
super(name);
}
/**
* Method setUp
*/
protected void setUp() {
env = new org.apache.axis.message.SOAPEnvelope();
headerElement1 = new SOAPHeaderElement(HEADER_NAMESPACE, "SomeHeader1",
"SomeValue1");
headerElement1.setActor(ACTOR);
env.addHeader(headerElement1);
headerElement2 = new SOAPHeaderElement(HEADER_NAMESPACE, "SomeHeader2",
"SomeValue2");
headerElement2.setActor(Constants.URI_SOAP11_NEXT_ACTOR);
env.addHeader(headerElement2);
}
/**
* Method tearDown
*/
protected void tearDown() {
}
/**
* Tests the happy path.
*
* @throws Exception
*/
public void testExamineHeaderElements1() throws Exception {
SOAPHeader header =
(org.apache.axis.message.SOAPHeader) env.getHeader();
Iterator iter = header.examineHeaderElements(ACTOR);
// This would be a lot simpler if getHeadersByActor() were visible.
SOAPHeaderElement headerElement = null;
int expectedHeaders = 2;
int foundHeaders = 0;
while (iter.hasNext()) {
headerElement = (SOAPHeaderElement) iter.next();
if (Constants.URI_SOAP11_NEXT_ACTOR.equals(headerElement.getActor())
|| ACTOR.equals(headerElement.getActor())) {
foundHeaders++;
}
}
assertEquals("Didn't find all the right actors.", expectedHeaders,
foundHeaders);
}
/**
* Tests when the user submits a null actor.
*
* @throws Exception
*/
public void testExamineHeaderElements2() throws Exception {
SOAPHeader header =
(org.apache.axis.message.SOAPHeader) env.getHeader();
Iterator iter = header.examineHeaderElements(null);
// This would be a lot simpler if getHeadersByActor() were visible.
SOAPHeaderElement headerElement = null;
int expectedHeaders = 1;
int foundHeaders = 0;
while (iter.hasNext()) {
headerElement = (SOAPHeaderElement) iter.next();
if (Constants.URI_SOAP11_NEXT_ACTOR.equals(
headerElement.getActor())) {
foundHeaders++;
}
}
assertEquals("Didn't find all the right actors.", expectedHeaders,
foundHeaders);
}
/**
* Tests the happy path.
*
* @throws Exception
*/
public void testExtractHeaderElements1() throws Exception {
SOAPHeader header =
(org.apache.axis.message.SOAPHeader) env.getHeader();
Iterator iter = header.extractHeaderElements(ACTOR);
// This would be a lot simpler if getHeadersByActor() were visible.
SOAPHeaderElement headerElement = null;
int expectedHeaders = 2;
int foundHeaders = 0;
while (iter.hasNext()) {
headerElement = (SOAPHeaderElement) iter.next();
if (Constants.URI_SOAP11_NEXT_ACTOR.equals(headerElement.getActor())
|| ACTOR.equals(headerElement.getActor())) {
foundHeaders++;
}
}
assertEquals("Didn't find all the right actors.", expectedHeaders,
foundHeaders);
}
/**
* Tests when the user submits a null actor.
*
* @throws Exception
*/
public void testExtractHeaderElements2() throws Exception {
SOAPHeader header =
(org.apache.axis.message.SOAPHeader) env.getHeader();
Iterator iter = header.extractHeaderElements(null);
// This would be a lot simpler if getHeadersByActor() were visible.
SOAPHeaderElement headerElement = null;
int expectedHeaders = 1;
int foundHeaders = 0;
while (iter.hasNext()) {
headerElement = (SOAPHeaderElement) iter.next();
if (Constants.URI_SOAP11_NEXT_ACTOR.equals(
headerElement.getActor())) {
foundHeaders++;
}
}
assertEquals("Didn't find all the right actors.", expectedHeaders,
foundHeaders);
}
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n"+
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"+
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"+
" <soapenv:Header>\n"+
" <shw:Hello xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n"+
" <shw:Myname>Tony</shw:Myname>\n"+
" </shw:Hello>\n"+
" </soapenv:Header>\n"+
" <soapenv:Body>\n"+
" <shw:Address xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n"+
" <shw:City>GENT</shw:City>\n"+
" </shw:Address>\n"+
" </soapenv:Body>\n"+
"</soapenv:Envelope>";
/**
* Method testSoapHeadersBUG
*
* @param filename
*
* @throws Exception
*/
public void testSoapHeadersBUG() throws Exception {
MimeHeaders mimeheaders = new MimeHeaders();
mimeheaders.addHeader("Content-Type", "text/xml");
ByteArrayInputStream instream = new ByteArrayInputStream(xmlString.getBytes());
MessageFactory factory =
MessageFactory.newInstance();
SOAPMessage msg =
factory.createMessage(mimeheaders, instream);
org.apache.axis.client.AxisClient axisengine =
new org.apache.axis.client.AxisClient();
// need to set it not null , if not nullpointer in sp.getEnvelope()
((org.apache.axis.Message) msg).setMessageContext(
new org.apache.axis.MessageContext(axisengine));
SOAPPart sp = msg.getSOAPPart();
javax.xml.soap.SOAPEnvelope se = sp.getEnvelope();
javax.xml.soap.SOAPHeader sh = se.getHeader();
SOAPBody sb = se.getBody();
Iterator it = sh.getChildElements();
int count = 0;
while (it.hasNext()) {
SOAPElement el = (SOAPElement) it.next();
count++;
Name name = el.getElementName();
System.out.println("Element:" + el);
System.out.println("HEADER ELEMENT NAME:" + name.getPrefix() + ":"
+ name.getLocalName() + " " + name.getURI());
}
assertTrue(count==1);
}
}
| 7,245 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestMessageElement.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 test.message;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.apache.axis.client.AxisClient;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.message.EnvelopeBuilder;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.soap.MessageFactoryImpl;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import test.AxisTestBase;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.Text;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringReader;
import java.io.OutputStream;
import java.util.Iterator;
/**
* Test {@link MessageElement} class.
*
* @author Glyn Normington (glyn@apache.org)
*/
public class TestMessageElement extends AxisTestBase {
// Test JAXM methods...
public void testParentage() throws Exception {
SOAPElement parent = new MessageElement("ns", "parent");
SOAPElement child = new MessageElement("ns", "child");
child.setParentElement(parent);
assertEquals("Parent is not as set", parent, child.getParentElement());
}
public void testAddChild() throws Exception {
SOAPConstants sc = SOAPConstants.SOAP11_CONSTANTS;
EnvelopeBuilder eb = new EnvelopeBuilder(Message.REQUEST, sc);
DeserializationContext dc = new DeserializationContext(null, eb);
MessageElement parent = new MessageElement("parent.names",
"parent",
"parns",
null,
dc);
Name c1 = new PrefixedQName("child1.names", "child1" ,"c1ns");
SOAPElement child1 = parent.addChildElement(c1);
SOAPElement child2 = parent.addChildElement("child2");
SOAPElement child3 = parent.addChildElement("child3.names", "parns");
SOAPElement child4 = parent.addChildElement("child4",
"c4ns",
"child4.names");
SOAPElement child5 = new MessageElement("ns", "child5");
parent.addChildElement(child5);
SOAPElement c[] = {child1, child2, child3, child4, child5};
Iterator children = parent.getChildElements();
for (int i = 0; i < 5; i++) {
assertEquals("Child " + (i+1) + " not found",
c[i],
children.next());
}
assertTrue("Unexpected child", !children.hasNext());
Iterator c1only = parent.getChildElements(c1);
assertEquals("Child 1 not found", child1, c1only.next());
assertTrue("Unexpected child", !c1only.hasNext());
}
public void testDetachNode() throws Exception {
SOAPConstants sc = SOAPConstants.SOAP11_CONSTANTS;
EnvelopeBuilder eb = new EnvelopeBuilder(Message.REQUEST, sc);
DeserializationContext dc = new DeserializationContext(null, eb);
SOAPElement parent = new MessageElement("parent.names",
"parent",
"parns",
null,
dc);
SOAPElement child1 = parent.addChildElement("child1");
SOAPElement child2 = parent.addChildElement("child2");
SOAPElement child3 = parent.addChildElement("child3");
child2.detachNode();
SOAPElement c[] = {child1, child3};
Iterator children = parent.getChildElements();
for (int i = 0; i < 2; i++) {
assertEquals("Child not found",
c[i],
children.next());
}
assertTrue("Unexpected child", !children.hasNext());
}
public void testGetCompleteAttributes() throws Exception {
MessageElement me =
new MessageElement("http://www.wolfram.com","Test");
me.addNamespaceDeclaration("pre", "http://www.wolfram2.com");
Attributes attrs = me.getCompleteAttributes();
assertEquals(attrs.getLength(), 1);
}
public void testAddNamespaceDeclaration() throws Exception {
MessageElement me =
new MessageElement("http://www.wolfram.com","Test");
me.addNamespaceDeclaration("pre", "http://www.wolfram2.com");
me.addAttribute(
"http://www.w3.org/2001/XMLSchema-instance",
"type",
"pre:test1");
boolean found = false;
Iterator it = me.getNamespacePrefixes();
while(!found && it.hasNext()){
String prefix = (String)it.next();
if (prefix.equals("pre") &&
me.getNamespaceURI(prefix).equals("http://www.wolfram2.com")) {
found = true;
}
}
assertTrue("Did not find namespace declaration \"pre\"", found);
}
public void testQNameAttrTest() throws Exception {
MessageElement me =
new MessageElement("http://www.wolfram.com","Test");
me.addAttribute(
"http://www.w3.org/2001/XMLSchema-instance",
"type",
new QName("http://www.wolfram2.com", "type1"));
MessageElement me2 =
new MessageElement("http://www.wolfram.com", "Child", (Object)"1");
me2.addAttribute(
"http://www.w3.org/2001/XMLSchema-instance",
"type",
new QName("http://www.w3.org/2001/XMLSchema", "int"));
me.addChildElement(me2);
String s1 = me.toString();
String s2 = me.toString();
assertEquals(s1, s2);
}
public void testMessageElementNullOngetNamespaceURI() throws Exception{
String data="<anElement xmlns:ns1=\"aNamespace\" href=\"unknownProtocol://data\"/>";
data="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body>"+
data+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
MessageContext ctx=new MessageContext(new AxisClient());
DeserializationContext dser = new DeserializationContext(
new org.xml.sax.InputSource(new StringReader(data)),
ctx,
Message.REQUEST);
dser.parse();
MessageElement elem=dser.getEnvelope().getBodyByName("","anElement");
assertEquals("aNamespace",elem.getNamespaceURI("ns1"));
assertEquals("ns1",elem.getPrefix("aNamespace"));
}
public void testSOAPElementMessageDoesNotHavePrefix() throws Exception {
String A_TAG = "A";
String A_PREFIX = "a";
String A_NAMESPACE_URI = "http://schemas.com/a";
String AA_TAG = "AA";
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart part = message.getSOAPPart();
SOAPEnvelope envelope = part.getEnvelope();
SOAPBody body = envelope.getBody();
envelope.getHeader().detachNode();
Name aName = envelope.createName(A_TAG, A_PREFIX, A_NAMESPACE_URI);
SOAPBodyElement aBodyElement = body.addBodyElement(aName);
aBodyElement.addChildElement(AA_TAG, A_PREFIX);
String data = envelope.toString();
MessageContext ctx = new MessageContext(new AxisClient());
DeserializationContext dser = new DeserializationContext(
new org.xml.sax.InputSource(new StringReader(data)),
ctx,
Message.REQUEST);
dser.parse();
MessageElement elem = dser.getEnvelope().getBodyByName(A_NAMESPACE_URI, A_TAG);
Iterator iterator = elem.getChildElements();
while(iterator.hasNext()){
MessageElement childElem = (MessageElement)iterator.next();
Name name = childElem.getElementName();
assertEquals(A_NAMESPACE_URI, name.getURI());
assertEquals(AA_TAG, name.getLocalName());
}
}
public void testSerializable() throws Exception
{
MessageElement m1 =
new MessageElement("http://www.wolfram.com","Test");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(m1);
oos.flush();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
MessageElement m2 = (MessageElement)ois.readObject();
assertEquals("m1 is not the same as m2", m1, m2);
assertEquals("m2 is not the same as m1", m2, m1);
}
public void testElementConstructor() throws Exception {
String xmlIn = "<h:html xmlns:xdc=\"http://www.xml.com/books\"\n" +
" xmlns:h=\"http://www.w3.org/HTML/1998/html4\">\n" +
" <h:head><h:title>Book Review</h:title></h:head>\n" +
" <h:body>\n" +
" <xdc:bookreview>\n" +
" <xdc:title>XML: A Primer</xdc:title>\n" +
" <h:table>\n" +
" <h:tr align=\"center\">\n" +
" <h:td>Author</h:td><h:td>Price</h:td>\n" +
" <h:td>Pages</h:td><h:td>Date</h:td></h:tr>\n" +
" <!-- here is a comment -->\n" +
" <h:tr align=\"left\">\n" +
" <h:td><xdc:author>Simon St. Laurent</xdc:author></h:td>\n" +
" <h:td><xdc:price>31.98</xdc:price></h:td>\n" +
" <h:td><xdc:pages>352</xdc:pages></h:td>\n" +
" <h:td><xdc:date>1998/01</xdc:date></h:td>\n" +
" <h:td><![CDATA[text content]]></h:td>\n" +
" </h:tr>\n" +
" </h:table>\n" +
" </xdc:bookreview>\n" +
" </h:body>\n" +
"</h:html>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xmlIn.getBytes()));
MessageElement me = new MessageElement(doc.getDocumentElement());
String xmlOut = me.getAsString();
this.assertXMLEqual(xmlIn,xmlOut);
}
public void testElementConstructor2() throws Exception {
String xmlIn = "<!-- This file can be used to deploy the echoAttachments sample -->\n" +
"<!-- using this command: java org.apache.axis.client.AdminClient attachdeploy.wsdd -->\n" +
"\n" +
"<!-- This deploys the echo attachment service. -->\n" +
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\" xmlns:ns1=\"urn:EchoAttachmentsService\" >\n" +
" <service name=\"urn:EchoAttachmentsService\" provider=\"java:RPC\" >\n" +
" <parameter name=\"className\" value=\"samples.attachments.EchoAttachmentsService\"/>\n" +
" <parameter name=\"allowedMethods\" value=\"echo echoDir\"/>\n" +
" <operation name=\"echo\" returnQName=\"returnqname\" returnType=\"ns1:DataHandler\" >\n" +
" <parameter name=\"dh\" type=\"ns1:DataHandler\"/>\n" +
" </operation>\n" +
"\n" +
" <typeMapping deserializer=\"org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory\"\n" +
" languageSpecificType=\"java:javax.activation.DataHandler\" qname=\"ns1:DataHandler\"\n" +
" serializer=\"org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory\"\n" +
" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
" />\n" +
" </service>\n" +
"\n" +
"</deployment>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xmlIn.getBytes()));
MessageElement me = new MessageElement(doc.getDocumentElement());
String xmlOut = me.getAsString();
System.out.println(xmlOut);
this.assertXMLEqual(xmlIn,xmlOut);
}
public void testElementConstructorUsingNamespaces() throws Exception {
String xmlIn = "<ns1:document xmlns:ns1=\"urn:someURI\">\n" +
" <ns2:child-element xmlns:ns2=\"urn:someOtherURI\">\n" +
" some text nodes insides\n" +
" </ns2:child-element>\n" +
"</ns1:document>";
Document doc = XMLUtils.newDocument(new ByteArrayInputStream(xmlIn.getBytes()));
MessageElement me = new MessageElement(doc.getDocumentElement());
String xmlOut = me.getAsString();
System.out.println(xmlOut);
// check that the String version of the XML are the same :
// I ensure that the namespaces declaration have not been moved
// this is needed when some elements are signed :
// we sign an element (get a Hashcode)
// if the serialization change that element, the Hashcode will
// change and the signature check will fail.
this.assertEquals(xmlIn, xmlOut);
}
/**
* Test setting the text value on a MessageElement in various ways.
*
* @throws Exception on error
*/
public void testSetValue() throws Exception
{
MessageElement me;
final QName name = new QName( "urn:xyz", "foo", "xyz" );
final String value = "java";
// Test #1: set value via MessageElement(name, value) constructor
me = new MessageElement( name, value );
assertEquals( value, me.getValue() );
assertEquals( value, me.getObjectValue() );
// Test #2a: set value via setValue(value)
me = new MessageElement( name );
me.setValue( value );
assertEquals( value, me.getValue() );
assertEquals( value, me.getObjectValue() );
// Test #2b: call setValue(value) on SOAPElement w/ more than one child (illegal)
me = new MessageElement( name );
me.addTextNode("cobol");
me.addTextNode("fortran");
try
{
me.setValue( value );
fail("setValue() should throw an IllegalStateException when called on a SOAPElement with more than one child");
}
catch ( RuntimeException re )
{
assertTrue(re instanceof IllegalStateException);
}
// Test #2c: call setValue(value) on SOAPElement w/ a non-Text child (illegal)
me = new MessageElement( name );
me.addChildElement("pascal");
try
{
me.setValue( value );
fail("setValue() should throw an IllegalStateException when called on a SOAPElement with a non-Text child");
}
catch ( RuntimeException re )
{
assertTrue(re instanceof IllegalStateException);
}
// Test #2d: set value via setValue(value) on Text child
me = new MessageElement( name );
me.addTextNode( "c++" );
Object child = me.getChildren().get(0);
assertTrue( child instanceof Text );
((Text)child).setValue( value );
assertEquals( value, me.getValue());
assertEquals( null, me.getObjectValue());
// Test #3: set value via setObjectValue(value)
me = new MessageElement( name );
me.setObjectValue( value );
assertEquals( value, me.getValue());
assertEquals( value, me.getObjectValue());
// Test #4: set value via addTextNode(value)
me = new MessageElement( name );
me.addTextNode( value );
assertEquals( value, me.getValue());
assertEquals( null, me.getObjectValue());
// Test #5: set value via dser.parse()
SOAPMessage msg = MessageFactoryImpl.newInstance().createMessage();
msg.getSOAPBody().addChildElement(new org.apache.axis.message.SOAPBodyElement(name, value));
OutputStream os = new ByteArrayOutputStream( );
msg.writeTo(os);
DeserializationContext dser = new DeserializationContext(new InputSource(new StringReader(os.toString())), new MessageContext(new AxisServer()),Message.REQUEST);
dser.parse();
me = (MessageElement) dser.getEnvelope().getBodyElements().get( 0 );
assertEquals( value, me.getValue());
assertEquals( value, me.getObjectValue());
}
public void testGetNodeValue() throws Exception {
String data = null;
data = "<anElement xmlns:ns1=\"aNamespace\"/>";
assertTrue(getNodeValueContext(data) == null);
assertTrue(getNodeValueDOM(data) == null);
data = "<anElement xmlns:ns1=\"aNamespace\">FooBar</anElement>";
assertEquals("FooBar", getNodeValueContext(data));
assertEquals("FooBar", getNodeValueDOM(data));
data = "<anElement xmlns:ns1=\"aNamespace\">A>B</anElement>";
assertEquals("A>B", getNodeValueContext(data));
assertEquals("A>B", getNodeValueDOM(data));
data = "<anElement xmlns:ns1=\"aNamespace\"><bElement>FooBar</bElement></anElement>";
assertTrue(getNodeValueContext(data) == null);
assertTrue(getNodeValueDOM(data) == null);
data = "<anElement xmlns:ns1=\"aNamespace\"><bElement>FooBar</bElement>Mixed</anElement>";
// SAAJ 1.2 requires "Mixed" for this case.
assertEquals("Mixed", getNodeValueContext(data));
assertEquals("Mixed", getNodeValueDOM(data));
// assertTrue(getNodeValueContext(data) == null);
// assertTrue(getNodeValueDOM(data) == null);
data = "<anElement xmlns:ns1=\"aNamespace\">Foo<bElement>FooBar</bElement>Mixed</anElement>";
assertEquals("Foo", getNodeValueContext(data));
assertEquals("Foo", getNodeValueDOM(data));
}
private String getNodeValueDOM(String data) throws Exception {
Document doc =
XMLUtils.newDocument(new org.xml.sax.InputSource(new StringReader(data)));
MessageElement elem = new MessageElement(doc.getDocumentElement());
assertTrue(elem.getDeserializationContext() == null);
return elem.getValue();
}
private String getNodeValueContext(String data) throws Exception {
String env =
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body>" +
data +
"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
MessageContext ctx = new MessageContext(new AxisClient());
DeserializationContext dser = new DeserializationContext(
new org.xml.sax.InputSource(new StringReader(env)),
ctx,
Message.REQUEST);
dser.parse();
MessageElement elem = dser.getEnvelope().getFirstBody();
assertTrue(elem.getDeserializationContext() != null);
return elem.getValue();
}
}
| 7,246 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/message/TestText.java | package test.message;
import junit.framework.TestCase;
import org.apache.axis.message.Text;
/**
* Test case for {@link Text}.
*
* @author Ian P. Springer
*/
public class TestText extends TestCase
{
private static final String VANILLA = "vanilla";
private static final String CHOCOLATE = "chocolate";
private static final String NULL = null;
private Text vanillaText;
private Text chocolateText;
private Text nullText;
private Text vanillaText2;
protected void setUp() throws Exception
{
vanillaText = new org.apache.axis.message.Text( VANILLA );
vanillaText2 = new org.apache.axis.message.Text( VANILLA );
chocolateText = new org.apache.axis.message.Text( CHOCOLATE );
nullText = new org.apache.axis.message.Text( NULL );
}
/**
* Test for {@link org.apache.axis.message.Text#toString()}.
*
* @throws Exception on error
*/
public void testToString() throws Exception
{
assertEquals( VANILLA, vanillaText.toString() );
assertEquals( NULL, nullText.toString() );
}
/**
* Test for {@link org.apache.axis.message.Text#hashCode()}.
*
* @throws Exception on error
*/
public void testHashCode() throws Exception
{
assertEquals( VANILLA.hashCode(), vanillaText.hashCode() );
assertEquals( 0, nullText.hashCode() );
}
/**
* Test for {@link org.apache.axis.message.Text#equals(Object)}.
*
* @throws Exception on error
*/
public void testEquals() throws Exception
{
assertEquals( vanillaText, vanillaText2 );
assertEquals( vanillaText2, vanillaText );
assertTrue( !vanillaText.equals( chocolateText ) );
assertTrue( !chocolateText.equals( vanillaText ) );
assertTrue( !vanillaText.equals( null ) );
assertTrue( !vanillaText.equals( VANILLA ) );
}
}
| 7,247 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestNSStack.java | package test.utils;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.AxisProperties;
import org.apache.axis.AxisEngine;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.xml.sax.InputSource;
import test.AxisTestBase;
import java.io.StringReader;
public class TestNSStack extends AxisTestBase
{
protected void setUp() throws Exception {
AxisProperties.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"false");
}
protected void tearDown() throws Exception {
AxisProperties.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"true");
}
String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">";
String suffix = "</soapenv:Envelope>";
String m1 = "<soapenv:Body wsu:id=\"id-23412344\"\n" +
" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-2004\">\n" +
" <somepfx:SomeTag id=\"e0sdoaeckrpd\" xmlns=\"ns:uri:one\"\n" +
" xmlns:somepfx=\"ns:uri:one\">hello</somepfx:SomeTag>\n" +
" </soapenv:Body>";
String m2 = "<soapenv:Body>" +
" <ns1:MyTag xmlns=\"http://ns1.com\" xmlns:ns1=\"http://ns1.com\">SomeText</ns1:MyTag>" +
" </soapenv:Body>";
public void testNSStack1() throws Exception
{
String msg = prefix+m1+suffix;
StringReader strReader = new StringReader(msg);
DeserializationContext dser = new DeserializationContext(
new InputSource(strReader), null,
org.apache.axis.Message.REQUEST);
dser.parse();
org.apache.axis.message.SOAPEnvelope env = dser.getEnvelope();
String xml = env.toString();
boolean oldIgnore = XMLUnit.getIgnoreWhitespace();
XMLUnit.setIgnoreWhitespace(true);
try {
assertXMLIdentical("NSStack invalidated XML canonicalization",
new Diff(msg, xml), true);
} finally {
XMLUnit.setIgnoreWhitespace(oldIgnore);
}
}
public void testNSStack2() throws Exception
{
String msg = prefix+m2+suffix;
StringReader strReader = new StringReader(msg);
DeserializationContext dser = new DeserializationContext(
new InputSource(strReader), null,
org.apache.axis.Message.REQUEST);
dser.parse();
org.apache.axis.message.SOAPEnvelope env = dser.getEnvelope();
String xml = env.toString();
boolean oldIgnore = XMLUnit.getIgnoreWhitespace();
XMLUnit.setIgnoreWhitespace(true);
try {
assertXMLIdentical("NSStack invalidated XML canonicalization",
new Diff(msg, xml), true);
} finally {
XMLUnit.setIgnoreWhitespace(oldIgnore);
}
}
}
| 7,248 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestJavaUtils.java | package test.utils;
import junit.framework.TestCase;
import org.apache.axis.utils.JavaUtils;
import javax.xml.rpc.holders.ByteHolder;
import javax.xml.rpc.holders.LongHolder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.Vector;
public class TestJavaUtils extends TestCase
{
/**
* See JSR-101: JAX-RPC, Appendix: Mapping of XML Names
*/
public void testXmlNameToJava() {
/* Begin TABLE 20-2 Illustrative Examples from JAXRPC Spec */
assertEquals("mixedCaseName", JavaUtils.xmlNameToJava("mixedCaseName"));
assertEquals("nameWithDashes", JavaUtils.xmlNameToJava("name-with-dashes"));
assertEquals("name_with_underscore", JavaUtils.xmlNameToJava("name_with_underscore"));
assertEquals("other_punctChars", JavaUtils.xmlNameToJava("other_punct.chars"));
assertEquals("answer42", JavaUtils.xmlNameToJava("Answer42"));
/* End TABLE 20-2 Illustrative Examples from JAXRPC Spec */
assertEquals("nameWithDashes",
JavaUtils.xmlNameToJava("name-with-dashes"));
assertEquals("otherPunctChars",
JavaUtils.xmlNameToJava("other.punct\u00B7chars"));
assertEquals("answer42", JavaUtils.xmlNameToJava("Answer42"));
assertEquals("\u2160Foo", JavaUtils.xmlNameToJava("\u2160foo"));
assertEquals("foo", JavaUtils.xmlNameToJava("2foo"));
//assertEquals("_Foo_", JavaUtils.xmlNameToJava("_foo_"));
assertEquals("_foo_", JavaUtils.xmlNameToJava("_foo_"));
assertEquals("foobar", JavaUtils.xmlNameToJava("--foobar--"));
assertEquals("foo22Bar", JavaUtils.xmlNameToJava("foo22bar"));
assertEquals("foo\u2160Bar", JavaUtils.xmlNameToJava("foo\u2160bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo-bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo.bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo:bar"));
//assertEquals("foo_Bar", JavaUtils.xmlNameToJava("foo_bar"));
assertEquals("foo_bar", JavaUtils.xmlNameToJava("foo_bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo\u00B7bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo\u0387bar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo\u06DDbar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo\u06DEbar"));
assertEquals("fooBar", JavaUtils.xmlNameToJava("FooBar"));
assertEquals("FOOBar", JavaUtils.xmlNameToJava("FOOBar"));
assertEquals("a1BBB", JavaUtils.xmlNameToJava("A1-BBB"));
assertEquals("ABBB", JavaUtils.xmlNameToJava("A-BBB"));
assertEquals("ACCC", JavaUtils.xmlNameToJava("ACCC"));
// the following cases are ambiguous in JSR-101
assertEquals("fooBar", JavaUtils.xmlNameToJava("foo bar"));
assertEquals("_1", JavaUtils.xmlNameToJava("-"));
}
/**
* Test for Bug 17994 - wsdl2java generates code with reserved words as variable names
*/
public void testXmlNameToJava2() {
assertEquals("_abstract", JavaUtils.xmlNameToJava("abstract"));
}
/**
* test the convert() function
* verify that we can convert to the Collection, List, and Set interfaces
* NOTE : These should be split out into separate tests...
*/
public void testConvert() {
Integer[] array = new Integer[4];
array[0] = new Integer(5); array[1] = new Integer(4);
array[2] = new Integer(3); array[3] = new Integer(2);
Object ret = JavaUtils.convert(array, List.class);
assertTrue("Converted array not a List", (ret instanceof List));
List list = (List)ret;
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], list.get(i));
}
ret = JavaUtils.convert(array, Collection.class);
assertTrue("Converted array is not a Collection", (ret instanceof Collection));
ret = JavaUtils.convert(array, Set.class);
assertTrue("Converted array not a Set", (ret instanceof Set));
ret = JavaUtils.convert(array, Vector.class);
assertTrue("Converted array not a Vector", (ret instanceof Vector));
HashMap m = new HashMap();
m.put("abcKey", "abcVal");
m.put("defKey", "defVal");
ret = JavaUtils.convert(m, Hashtable.class);
assertTrue("Converted HashMap not a Hashtable", (ret instanceof Hashtable));
LongHolder holder = new LongHolder(1);
ret = JavaUtils.convert(holder, Object.class);
assertTrue(ret != null);
assertTrue(Long.class.isInstance(ret));
ByteHolder holder2 = new ByteHolder((byte)0);
ret = JavaUtils.convert(holder2, Object.class);
assertTrue(ret != null);
assertTrue(Byte.class.isInstance(ret));
// Make sure we convert ArrayList to array in 2D cases
Object[] arrayin = new Object[1];
ArrayList data = new ArrayList(5);
data.add("one"); data.add(new Integer(2)); data.add(new Float(4.0));
data.add(new Double(5.0)); data.add("five");
arrayin[0] = data;
ret = JavaUtils.convert(arrayin, Object[][].class);
assertTrue("Converted 2D array/ArrayList wrong", ret.getClass().equals(Object[][].class));
Object[][] outer = (Object[][]) ret;
assertEquals("Outer array of 2D array/ArrayList is wrong length", 1, outer.length);
Object[] inner = ((Object[][])ret)[0];
assertEquals("Inner array of 2D array/ArrayLis is wrong length", 1, inner.length);
// check 2D ArrayList of ArrayList
ArrayList data2D = new ArrayList(2);
data2D.add(data); data2D.add(data);
ret = JavaUtils.convert(data2D, Object[][].class);
assertTrue("Converted 2D ArrayList wrong", ret.getClass().equals(Object[][].class));
Object[][] outer2 = (Object[][]) ret;
assertEquals("Outer array of 2D ArrayList is wrong length", 2, outer2.length);
Object[] inner2 = ((Object[][]) ret)[0];
assertEquals("Inner array of 2D ArrayList is wrong length", 5, inner2.length);
}
public void test1dTo2d() throws Exception {
byte [] arg = new byte [] { '0', '1' };
byte [][] ret = (byte[][])JavaUtils.convert(arg, byte[][].class);
// ClassCastException above if problems converting
assertNotNull("Conversion result was null", ret);
assertEquals("Outer array size wrong", 1, ret.length);
assertEquals("Inner array size wrong", 2, ret[0].length);
}
/**
* test the isConvertable() function
*/
public void testIsConvert() {
assertTrue(JavaUtils.isConvertable(new Long(1),Long.class));
assertTrue(JavaUtils.isConvertable(new Long(1),long.class));
assertTrue(JavaUtils.isConvertable(new Long(1),Object.class));
assertTrue(!JavaUtils.isConvertable(new Long(1),Float.class));
Class clazz = long.class;
assertTrue(JavaUtils.isConvertable(clazz,Long.class));
assertTrue(JavaUtils.isConvertable(clazz,Object.class));
clazz = byte.class;
assertTrue(JavaUtils.isConvertable(clazz,Byte.class));
assertTrue(JavaUtils.isConvertable(clazz,Object.class));
}
/**
* Make sure we can't say convert from string[] to Calendar[]
*/
public void testIsConvert2()
{
String[] strings = new String[]{"hello"};
Calendar[] calendars = new Calendar[1];
assertTrue(!JavaUtils.isConvertable(strings, calendars.getClass()));
}
}
| 7,249 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestMessages.java | package test.utils;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Vector;
/**
* This TestCase verifies:
* - the contents of resource.properties for well-formedness, and
* - tests calls to Messages.getMessage.
* - tests Messages extension mechanism
*/
public class TestMessages extends TestCase {
/**
* Call getMessage for each key in resource.properties
* to make sure they are all well formed.
*/
private static final int expectedNumberKeysThreshold = 500;
public void testAllMessages() {
String arg0 = "arg0";
String arg1 = "arg1";
String[] args = {arg0, arg1, "arg2"};
int count = 0;
Enumeration keys = Messages.getResourceBundle().getKeys();
while (keys.hasMoreElements()) {
count++;
String key = (String) keys.nextElement();
try {
String message = Messages.getMessage(key);
message = Messages.getMessage(key, arg0);
message = Messages.getMessage(key, arg0, arg1);
message = Messages.getMessage(key, args);
}
catch (IllegalArgumentException iae) {
throw new AssertionFailedError("Test failure on key = " + key + ": " + iae.getMessage());
}
}
assertTrue("expected # keys greater than " + expectedNumberKeysThreshold + ", only got " + count + "! VERIFY HIERARCHICAL MESSAGES WORK/LINKED CORRECTLY",
count > expectedNumberKeysThreshold);
} // testAllMessages
/**
* Make sure the test messages come out as we expect them to.
*/
public void testTestMessages() {
try {
String message = Messages.getMessage("test00");
String expected = "...";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test00", new String[0]);
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test00", new String[] {"one", "two"});
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test01");
expected = ".{0}.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test01", "one");
expected = ".one.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test01", new String[0]);
expected = ".{0}.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test01", new String[] {"one"});
expected = ".one.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test01", new String[] {"one", "two"});
expected = ".one.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test02");
expected = "{0}, {1}.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test02", new String[0]);
expected = "{0}, {1}.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test02", new String[] {"one"});
expected = "one, {1}.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test02", new String[] {"one", "two"});
expected = "one, two.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test03", new String[] {"one", "two", "three"});
expected = ".three, one, two.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
message = Messages.getMessage("test04", new String[] {"one", "two", "three", "four", "five", "six"});
expected = ".one two three ... four three five six.";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
}
catch (Throwable t) {
throw new AssertionFailedError("Test failure: " + t.getMessage());
}
} // testTestMessages
/**
* Make sure the extended test messages come out as we expect them to.
*/
public void testTestExtendedMessages() {
try {
String message = Messages.getMessage("extended.test00");
String expected = "message in extension file";
assertTrue("expected (" + expected + ") got (" + message + ")", expected.equals(message));
}
catch (Throwable t) {
throw new AssertionFailedError("Test failure: " + t.getMessage());
}
} // testTestExtendedMessages
private static final String LS = System.getProperty("line.separator");
private String errors = "";
/**
* If this test is run from xml-axis/java, then walk through the source
* tree looking for all calls to Messages.getMessage. For each of these
* calls:
* 1. Make sure the message key exists in resource.properties
* 2. Make sure the actual number of parameters (in resource.properties)
* matches the excpected number of parameters (in the source code).
*/
public void testForMissingMessages() {
char sep = File.separatorChar;
String srcDirStr = "src" + sep + "main" + sep + "java";
File srcDir = new File(srcDirStr);
if (srcDir.exists()) {
walkTree(srcDir);
}
if (!errors.equals("")) {
throw new AssertionFailedError(errors);
}
} // testForMissingMessages
/**
* Walk the source tree
*/
private void walkTree(File srcDir) {
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; ++i) {
if (files[i].isDirectory()) {
walkTree(files[i]);
}
else if (files[i].getName().endsWith(".java")) {
checkMessages(files[i]);
}
}
} // walkTree
/**
* Check all calls to Messages.getMessages:
* 1. Make sure the message key exists in resource.properties
* 2. Make sure the actual number of parameters (in resource.properties)
* matches the expected number of parameters (in the source code).
*/
private void checkMessages(File file) {
try {
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
final String pattern = "Messages.getMessage(";
String string = new String(bytes);
while (true) {
int index = string.indexOf(pattern);
if (index < 0) break;
// Bump the string past the pattern-string
string = string.substring(index + pattern.length());
// Get the arguments for the getMessage call
String[] msgArgs = args(string);
// The first argument is the key.
// If the key is a literal string, check the usage.
// If the key is not a literal string, accept the usage.
if (msgArgs[0].startsWith("\"")) {
String key = msgArgs[0].substring(1, msgArgs[0].length() - 1);
// Get the raw message
String value = null;
try {
value = Messages.getMessage(key);
}
catch (Throwable t) {
errors = errors + "File: " + file.getPath() + " " + t.getMessage() + LS;
}
// The realParms count is the number of strings in the
// message of the form: {X} where X is 0..9
int realParms = count(value);
// The providedParms count is the number of arguments to
// getMessage, minus the first argument (key).
int providedParms = msgArgs.length - 1;
if (realParms != providedParms) {
errors = errors + "File: '" + file.getPath() + "', Key '" + key + "' specifies " + realParms + " {X} parameters, but " + providedParms + " parameter(s) provided." + LS;
}
}
}
}
catch (Throwable t) {
errors = errors + "File: " + file.getPath() + " " + t.getMessage() + LS;
}
} // checkMessages
/**
* For the given method call string, return the parameter strings.
* This means that everything between the first "(" and the last ")",
* and each "," encountered at the top level delimits a parameter.
*/
private String[] args (String string) {
int innerParens = 0;
Vector args = new Vector();
String arg = "";
while (true) {
if (string.startsWith("\"")) {
// Make sure we don't look for the following characters within quotes:
// , ' " ( )
String quote = readQuote(string);
arg = arg + quote;
string = string.substring(quote.length());
}
else if (string.startsWith("'")) {
// Make sure we ignore a quoted character
arg = arg + string.substring(0, 2);
string = string.substring(2);
}
else if (string.startsWith(",")) {
// If we're at the top level (ie., not inside inner parens like:
// (X, Y, new String(str, 0))), then we are seeing the end of an argument.
if (innerParens == 0) {
args.add(arg);
arg = "";
}
else {
arg = arg + ',';
}
string = string.substring(1);
}
else if (string.startsWith("(")) {
// We are stepping within a subexpression delimited by parens
++innerParens;
arg = arg + '(';
string = string.substring(1);
}
else if (string.startsWith(")")) {
// We are either stepping out of a subexpression delimited by parens, or we
// have reached the end of the parameter list.
if (innerParens == 0) {
args.add(arg);
String[] argsArray = new String[args.size()];
args.toArray(argsArray);
return argsArray;
}
else {
--innerParens;
arg = arg + ')';
string = string.substring(1);
}
}
else {
// We aren't looking at any special character, just add it to the arg string
// we're building.
if (!Character.isWhitespace(string.charAt(0))) {
arg = arg + string.charAt(0);
}
string = string.substring(1);
}
}
} // args
/**
* Collect a quoted string, making sure we really end when the string ends.
*/
private String readQuote(String string) {
String quote = "\"";
string = string.substring(1);
while (true) {
int index = string.indexOf('"');
if (index == 0 || string.charAt(index - 1) != '\\') {
quote = quote + string.substring(0, index + 1);
return quote;
}
else {
quote = quote + string.substring(0, index + 1);
string = string.substring(index);
}
}
} // readQuote
/**
* Count the number of strings of the form {X} where X = 0..9.
*/
private int count(String string) {
int parms = 0;
int index = string.indexOf("{");
while (index >= 0) {
try {
char parmNumber = string.charAt(index + 1);
if (parmNumber >= '0' && parmNumber <= '9' && string.charAt(index + 2) == '}') {
++parms;
}
string = string.substring(index + 1);
index = string.indexOf("{");
} catch (Throwable t) {
}
}
return parms;
} // count
}
| 7,250 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestStringUtils.java | package test.utils;
import junit.framework.TestCase;
import org.apache.axis.utils.StringUtils;
public class TestStringUtils extends TestCase
{
public void testStripWhite() {
assertEquals(null, StringUtils.strip(null, null));
assertEquals("", StringUtils.strip("", null));
assertEquals("", StringUtils.strip(" \r\n ", null));
assertEquals("abc", StringUtils.strip("abc", null));
assertEquals("abc", StringUtils.strip(" abc", null));
assertEquals("abc", StringUtils.strip("abc ", null));
assertEquals("abc", StringUtils.strip(" abc ", null));
}
public void testStripStartWhite() {
assertEquals(null, StringUtils.stripStart(null, null));
assertEquals("", StringUtils.stripStart("", null));
assertEquals("", StringUtils.stripStart(" \r\n ", null));
assertEquals("abc", StringUtils.stripStart("abc", null));
assertEquals("abc", StringUtils.stripStart(" abc", null));
assertEquals("abc ", StringUtils.stripStart("abc ", null));
assertEquals("abc ", StringUtils.stripStart(" abc ", null));
}
public void testStripEndWhite() {
assertEquals(null, StringUtils.stripEnd(null, null));
assertEquals("", StringUtils.stripEnd("", null));
assertEquals("", StringUtils.stripEnd(" \r\n ", null));
assertEquals("abc", StringUtils.stripEnd("abc", null));
assertEquals(" abc", StringUtils.stripEnd(" abc", null));
assertEquals("abc", StringUtils.stripEnd("abc ", null));
assertEquals(" abc", StringUtils.stripEnd(" abc ", null));
}
}
| 7,251 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/Messages.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.utils;
import org.apache.axis.i18n.MessageBundle;
import org.apache.axis.i18n.MessagesConstants;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* @see org.apache.axis.i18n.Messages
*
* Changed projectName to local package (test.utils).
*
* @author Richard A. Sitze (rsitze@us.ibm.com)
* @author Karl Moss (kmoss@macromedia.com)
* @author Glen Daniels (gdaniels@apache.org)
*/
public class Messages {
private static final Class thisClass = Messages.class;
private static final String projectName = "test.utils";
private static final String resourceName = MessagesConstants.resourceName;
private static final Locale locale = MessagesConstants.locale;
private static final String packageName = getPackage(thisClass.getName());
private static final ClassLoader classLoader = thisClass.getClassLoader();
private static final ResourceBundle parent =
(MessagesConstants.rootPackageName == packageName)
? null
: MessagesConstants.rootBundle;
/***** NO NEED TO CHANGE ANYTHING BELOW *****/
private static final MessageBundle messageBundle =
new MessageBundle(projectName, packageName, resourceName,
locale, classLoader, parent);
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @return The formatted message
*/
public static String getMessage(String key)
throws MissingResourceException
{
return messageBundle.getMessage(key);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @return The formatted message
*/
public static String getMessage(String key, String arg0)
throws MissingResourceException
{
return messageBundle.getMessage(key, arg0);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @return The formatted message
*/
public static String getMessage(String key, String arg0, String arg1)
throws MissingResourceException
{
return messageBundle.getMessage(key, arg0, arg1);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @return The formatted message
*/
public static String getMessage(String key, String arg0, String arg1, String arg2)
throws MissingResourceException
{
return messageBundle.getMessage(key, arg0, arg1, arg2);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @param arg3 The argument to place in variable {3}
* @return The formatted message
*/
public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3)
throws MissingResourceException
{
return messageBundle.getMessage(key, arg0, arg1, arg2, arg3);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @param arg3 The argument to place in variable {3}
* @param arg4 The argument to place in variable {4}
* @return The formatted message
*/
public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3, String arg4)
throws MissingResourceException
{
return messageBundle.getMessage(key, arg0, arg1, arg2, arg3, arg4);
}
/**
* Get a message from resource.properties from the package of the given object.
* @param caller The calling object, used to get the package name and class loader
* @param locale The locale
* @param key The resource key
* @param array An array of objects to place in corresponding variables
* @return The formatted message
*/
public static String getMessage(String key, String[] args)
throws MissingResourceException
{
return messageBundle.getMessage(key, args);
}
public static ResourceBundle getResourceBundle() {
return messageBundle.getResourceBundle();
}
public static MessageBundle getMessageBundle() {
return messageBundle;
}
private static final String getPackage(String name) {
return name.substring(0, name.lastIndexOf('.')).intern();
}
}
| 7,252 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestQName.java | package test.utils;
import junit.framework.TestCase;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestQName extends TestCase
{
public void testQName2StringConstructor()
{
QName qname = new QName("rdf","article");
assertNotNull("qname was null. Something really wrong here.", qname);
assertEquals("Namespace URI was not 'rdf', it was: " + qname.getNamespaceURI(),
"rdf", qname.getNamespaceURI());
assertEquals("LocalPart was not 'article', it was: " + qname.getLocalPart(),
"article", qname.getLocalPart());
}
public void testToString()
{
QName qname = new QName("PREFIX", "LOCALPART");
assertEquals("qname was not the same as '{PREFIX}LOCALPART', it was: " + qname.toString(),
"{PREFIX}LOCALPART", qname.toString());
}
public void testNullQname()
{
QName qname1 = new QName("LOCALPART");
QName qname2 = new QName(null, "LOCALPART");
QName qname3 = new QName("", "LOCALPART");
assertEquals("omitted namespace ", "LOCALPART", qname1.toString());
assertEquals("null namespace ", "LOCALPART", qname2.toString());
assertEquals("empty namespace ", "LOCALPART", qname3.toString());
}
public void testEquals()
{
QName qname1 = new QName("", "");
QName qname2 = new QName("PREFIX", "LOCALPART");
QName qname3 = new QName("PREFIX", "LOCALPART");
QName qname4 = new QName("PREFIX", "DIFFLOCALPART");
//need a fully implemented mock Element class...
//Element elem = new MockElement();
////QName qname5 = new QName("PREFIX:LOCALPART", elem);
// the following should NOT throw a NullPointerException
assertTrue("qname1 is the same as qname2", !qname1.equals(qname2));
//Note: this test is comparing the same two QName objects as above, but
//due to the order and the implementation of the QName.equals() method,
//this test passes without incurring a NullPointerException.
assertTrue("qname2 is the same as qname1", !qname2.equals(qname1));
assertTrue("qname2 is not the same as qname2", qname2.equals(qname3));
assertTrue("qname3 is the same as qname4", !qname3.equals(qname4));
}
public void testHashCode()
{
QName control = new QName("xsl", "text");
QName compare = new QName("xsl", "text");
QName contrast = new QName("xso", "text");
assertEquals("control hashcode does not equal compare.hashcode", control.hashCode(), compare.hashCode());
assertTrue("control hashcode is not equivalent to compare.hashcode", !(control.hashCode() == contrast.hashCode()));
}
public void testSerializable() throws Exception
{
QName q1 = new QName("Matthew", "Duftler");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(q1);
oos.flush();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
QName q2 = (QName)ois.readObject();
assertEquals("q1 is not the same as q2", q1, q2);
assertEquals("q2 is not the same as q1", q2, q1);
}
}
| 7,253 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestOptions.java | package test.utils;
import junit.framework.TestCase;
import org.apache.axis.utils.Options;
import java.net.MalformedURLException;
public class TestOptions extends TestCase
{
public void testOptionsConstructor() throws MalformedURLException
{
String[] fake_args = { "-h 127.0.0.1","-p 8081","-u scott","-w tiger" };
Options ops = new Options(fake_args);
}
/*
* Note - by Java conventions, the isFlagSet and isValueSet should either
* return a boolean value, or be given more descriptive names. I might
* suggest getFlagFrequency and getArgValue or something.
*/
public void testIsFlagSet() throws MalformedURLException
{
String[] fake_args = { "-w tiger" };
Options ops = new Options(fake_args);
String result = ops.isValueSet('w');
assertEquals("Result was: " + result + ", not tiger", "tiger", result);
}
}
| 7,254 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestXMLUtils.java | package test.utils;
import org.apache.axis.encoding.DeserializationContext;
import test.AxisTestBase;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.message.MessageElement;
import org.apache.axis.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.custommonkey.xmlunit.XMLUnit;
import javax.xml.parsers.SAXParser;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBodyElement;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PipedOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;
public class TestXMLUtils extends AxisTestBase
{
public void testNewDocumentNoArgConstructor() throws Exception
{
Document doc = XMLUtils.newDocument();
assertNotNull("Did not get a new Document", doc);
}
public void testNewDocumentInputSource() throws Exception
{
Reader reader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(reader);
Document doc = XMLUtils.newDocument(inputsrc);
assertNotNull("Did not get a new Document", doc);
}
public void testNewDocumentInputStream() throws Exception
{
InputStream iostream = (InputStream)this.getTestXml("inputstream");
InputSource inputsrc = new InputSource(iostream);
Document doc = XMLUtils.newDocument(inputsrc);
assertNotNull("Did not get a new Document", doc);
}
/* This test will fail unless you are connected to the Web, so just skip
* it unless you really want to test it. When not connected to the Web you
* will get an UnknownHostException.
*/
public void testNewDocumentURI() throws Exception
{
if(isOnline()) {
String uri = "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd";
Document doc = XMLUtils.newDocument(uri);
assertNotNull("Did not get a new Document", doc);
}
}
public void testDocumentToString() throws Exception
{
Reader reader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(reader);
Document doc = XMLUtils.newDocument(inputsrc);
String xmlString = (String)this.getTestXml("string");
String result = XMLUtils.DocumentToString(doc);
assertXMLEqual("xmlString is not the same as result", xmlString, result);
}
/**
* This test method is somewhat complex, but it solves a problem people have
* asked me about, which is how to unit test a method that has void return
* type but writes its output to a writer. So half the reason for
* creating and using it here is as a reference point.
*/
public void testElementToWriter() throws Exception
{
/* Get the Document and one of its elements. */
Reader xmlReader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(xmlReader);
Document doc = XMLUtils.newDocument(inputsrc);
NodeList nl = doc.getElementsByTagName("display-name");
Element elem = (Element)nl.item(0);
String expected = "<display-name>Apache-Axis</display-name>";
/*
* Create a PipedOutputStream to get the output from the tested method.
* Pass the PipedOutputStream to the ConsumerPipe's constructor, which
* will create a PipedInputStream in a separate thread.
*/
PipedOutputStream out = new PipedOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
ConsumerPipe cpipe = new ConsumerPipe(out);
/*
* Call the method under test, passing the PipedOutStream to trap the
* results.
*/
XMLUtils.ElementToWriter(elem, writer);
/*
* The output of the test will be piped to ConsumerPipe's PipedInputStream, which
* is used to read the bytes of the stream into an array. It then creates a
* String for comparison from that byte array.
*/
out.flush();
String result = cpipe.getResult();
//don't forget to close this end of the pipe (ConsumerPipe closes the other end).
out.close();
assertEquals("Did not get the expected result", expected, result);
}
/**
* For explanation of the methodology used to test this method, see notes in
* previous test method.
*/
public void testDocumentToStream() throws Exception
{
Reader reader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(reader);
Document doc = XMLUtils.newDocument(inputsrc);
PipedOutputStream out = new PipedOutputStream();
ConsumerPipe cpipe = new ConsumerPipe(out);
XMLUtils.DocumentToStream(doc, out);
out.flush();
String result = cpipe.getResult();
out.close();
String expected = (String)this.getTestXml("string");
assertXMLEqual("Did not get the expected result", expected, result);
}
public void testElementToString() throws Exception
{
Reader reader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(reader);
Document doc = XMLUtils.newDocument(inputsrc);
NodeList nl = doc.getElementsByTagName("display-name");
Element elem = (Element)nl.item(0);
String expected = "<display-name>Apache-Axis</display-name>";
String result = XMLUtils.ElementToString(elem);
assertEquals("Element tag name is not 'display-name', it is: " + elem.getTagName(),
"display-name", elem.getTagName());
assertEquals("Did not get the expected result", expected, result);
}
public void testGetInnerXMLString() throws Exception
{
Reader reader = (Reader)this.getTestXml("reader");
InputSource inputsrc = new InputSource(reader);
Document doc = XMLUtils.newDocument(inputsrc);
NodeList nl = doc.getElementsByTagName("display-name");
Element elem = (Element)nl.item(0);
String expected = "Apache-Axis";
String result = XMLUtils.getInnerXMLString(elem);
assertEquals(expected, result);
}
public void testGetPrefix() throws Exception
{
Document doc = XMLUtils.newDocument();
Element elem = doc.createElementNS("", "svg");
elem.setAttribute("xmlns:svg", "\"http://www.w3.org/2000/svg\"");
elem.setAttribute("xmlns:xlink", "\"http://www.w3.org/1999/xlink\"");
elem.setAttribute("xmlns:xhtml", "\"http://www.w3.org/1999/xhtml\"");
String expected = "svg";
String result = XMLUtils.getPrefix("\"http://www.w3.org/2000/svg\"", elem);
assertEquals("Did not get the expected result", expected, result);
expected = "xlink";
result = XMLUtils.getPrefix("\"http://www.w3.org/1999/xlink\"", elem);
assertEquals("Did not get the expected result", expected, result);
expected = "xhtml";
result = XMLUtils.getPrefix("\"http://www.w3.org/1999/xhtml\"", elem);
assertEquals("Did not get the expected result", expected, result);
}
public void testGetNamespace() throws Exception
{
String testDoc = "<svg xmlns:svg=\"http://www.w3.org/2000/svg\"/>";
InputSource inputsrc = new InputSource(new StringReader(testDoc));
Document doc = XMLUtils.newDocument(inputsrc);
assertNotNull("Got a null document", doc);
NodeList nl = doc.getElementsByTagName("svg");
Element elem = (Element)nl.item(0);
String expected = "http://www.w3.org/2000/svg";
String result = XMLUtils.getNamespace("svg", elem);
assertEquals("Did not get the expected result", expected, result);
}
/**
* This is a utility method for creating XML document input sources for this
* JUnit test class. The returned Object should be cast to the type you
* request via the gimme parameter.
*
* @param gimme A String specifying the underlying type you want the XML
* input source returned as; one of "string", "reader", or "inputstream."
*/
public Object getTestXml(String gimme)
{
String lineSep = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + lineSep)
//The System ID will cause an unknown host exception unless you are
//connected to the Internet, so comment it out for testing.
//.append("<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN\"" + lineSep)
//.append("\"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd\">" + lineSep)
.append("<web-app>" + lineSep)
.append("<display-name>Apache-Axis</display-name>" + lineSep)
.append("<servlet>" + lineSep)
.append("<servlet-name>AxisServlet</servlet-name>" + lineSep)
.append("<display-name>Apache-Axis Servlet</display-name>" + lineSep)
.append("<servlet-class>" + lineSep)
.append("org.apache.axis.transport.http.AxisServlet" + lineSep)
.append("</servlet-class>" + lineSep)
.append("</servlet>" + lineSep)
.append("<servlet-mapping>" + lineSep)
.append("<servlet-name>AxisServlet</servlet-name>" + lineSep)
.append("<url-pattern>servlet/AxisServlet</url-pattern>" + lineSep)
.append("<url-pattern>*.jws</url-pattern>" + lineSep)
.append("</servlet-mapping>" + lineSep)
.append("</web-app>");
String xmlString = sb.toString();
if (gimme.equals("string"))
{
return xmlString;
}
else if (gimme.equals("reader"))
{
StringReader strReader = new StringReader(xmlString);
return strReader;
}
else if (gimme.equals("inputstream"))
{
ByteArrayInputStream byteStream = new ByteArrayInputStream(xmlString.getBytes());
return byteStream;
}
else return null;
}
public void testDOM2Writer() throws Exception
{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<xsd:schema targetNamespace=\"http://tempuri.org\"");
sb.append(" xmlns=\"http://tempuri.org\"");
sb.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
sb.append(" <xsd:annotation>");
sb.append(" <xsd:documentation xml:lang=\"en\">");
sb.append(" Purchase order schema for Example.com.");
sb.append(" Copyright 2000 Example.com. All rights reserved.");
sb.append(" </xsd:documentation>");
sb.append(" </xsd:annotation>");
sb.append("</xsd:schema>");
StringReader strReader = new StringReader(sb.toString());
InputSource inputsrc = new InputSource(strReader);
Document doc = XMLUtils.newDocument(inputsrc);
String output = org.apache.axis.utils.DOM2Writer.nodeToString(doc,false);
assertTrue(output.indexOf("http://www.w3.org/XML/1998/namespace")==-1);
}
public void testDOMXXE() throws Exception
{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<!DOCTYPE project [");
sb.append("<!ENTITY buildxml SYSTEM \"file:build.xml\">");
sb.append("]>");
sb.append("<xsd:schema targetNamespace=\"http://tempuri.org\"");
sb.append(" xmlns=\"http://tempuri.org\"");
sb.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
sb.append(" <xsd:annotation>");
sb.append(" <xsd:documentation xml:lang=\"en\">");
sb.append(" &buildxml;");
sb.append(" Purchase order schema for Example.com.");
sb.append(" Copyright 2000 Example.com. All rights reserved.");
sb.append(" </xsd:documentation>");
sb.append(" </xsd:annotation>");
sb.append("</xsd:schema>");
StringReader strReader = new StringReader(sb.toString());
InputSource inputsrc = new InputSource(strReader);
Document doc = XMLUtils.newDocument(inputsrc);
String output = org.apache.axis.utils.DOM2Writer.nodeToString(doc,false);
}
String msg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE project [" +
"<!ENTITY buildxml SYSTEM \"file:pom.xml\">" +
"]>" +
"<SOAP-ENV:Envelope " +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" > " +
"<SOAP-ENV:Body>\n" +
"&buildxml;" +
"<echo:Echo xmlns:echo=\"EchoService\">\n" +
"<symbol>IBM</symbol>\n" +
"</echo:Echo>\n" +
"</SOAP-ENV:Body></SOAP-ENV:Envelope>\n";
public void testSAXXXE1() throws Exception
{
StringReader strReader = new StringReader(msg);
InputSource inputsrc = new InputSource(strReader);
SAXParser parser = XMLUtils.getSAXParser();
parser.getParser().parse(inputsrc);
}
public void testSAXXXE2() throws Exception
{
StringReader strReader2 = new StringReader(msg);
InputSource inputsrc2 = new InputSource(strReader2);
SAXParser parser2 = XMLUtils.getSAXParser();
parser2.getXMLReader().parse(inputsrc2);
}
// If we are using DeserializationContext, we do not allow
// a DOCTYPE to be specified to prevent denial of service attacks
// via the ENTITY processing intstruction.
String msg2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<SOAP-ENV:Envelope " +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" > " +
"<SOAP-ENV:Body>\n" +
"<echo:Echo xmlns:echo=\"EchoService\">\n" +
"<symbol xml:lang=\"en\">IBM</symbol>\n" +
"</echo:Echo>\n" +
"</SOAP-ENV:Body></SOAP-ENV:Envelope>\n";
/**
* Confirm we can parse a SOAP Envelope, and make sure that the
* xml:lang attribute is handled OK while we're at it.
*
* @throws Exception
*/
public void testSAXXXE3() throws Exception
{
StringReader strReader3 = new StringReader(msg2);
DeserializationContext dser = new DeserializationContext(
new InputSource(strReader3), null, org.apache.axis.Message.REQUEST);
dser.parse();
SOAPEnvelope env = dser.getEnvelope();
SOAPBodyElement body = (SOAPBodyElement)env.getBody().getChildElements().next();
assertNotNull(body);
MessageElement child = (MessageElement)body.getChildElements().next();
assertNotNull(child);
Iterator i = child.getAllAttributes();
assertNotNull(i);
PrefixedQName attr = (PrefixedQName)i.next();
assertNotNull(attr);
assertEquals("Prefix for attribute was not 'xml'", attr.getPrefix(), "xml");
assertEquals("Namespace for attribute was not correct", attr.getURI(),
Constants.NS_URI_XML);
}
String msg3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
" <soapenv:Header>" +
" <TrackingHeader xmlns=\"http://testns.org/test\">1234</TrackingHeader>" +
" <ns1:Security soapenv:mustUnderstand=\"0\" xmlns:ns1=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">" +
" <ns1:UsernameToken>" +
" <ns1:Username xsi:type=\"xsd:string\">foobar</ns1:Username>" +
" <ns1:Password xsi:type=\"xsd:string\">wibble</ns1:Password>" +
" </ns1:UsernameToken>" +
" </ns1:Security>" +
" </soapenv:Header>" +
" <soapenv:Body>" +
" <EchoString>asdadsf</EchoString>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
/**
* Test for Bug 22980
* @throws Exception
*/
public void testNSStack() throws Exception
{
StringReader strReader3 = new StringReader(msg3);
DeserializationContext dser = new DeserializationContext(
new InputSource(strReader3), null, org.apache.axis.Message.REQUEST);
dser.parse();
org.apache.axis.message.SOAPEnvelope env = dser.getEnvelope();
String xml = env.toString();
boolean oldIgnore = XMLUnit.getIgnoreWhitespace();
XMLUnit.setIgnoreWhitespace(true);
try {
assertXMLEqual(xml,msg3);
} finally {
XMLUnit.setIgnoreWhitespace(oldIgnore);
}
}
}
| 7,255 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/ConsumerPipe.java | package test.utils;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class ConsumerPipe implements Runnable
{
PipedInputStream consumer = null;
String result;
private static int pipecount = 0; //thread counter for debuggers and stack traces.
boolean done = false;
public ConsumerPipe(PipedOutputStream out) throws IOException {
consumer = new PipedInputStream(out);
pipecount++;
}
public void run()
{
try
{
char[] chars = new char[consumer.available()];
for (int i =0; i < chars.length; i++)
{
chars[i] = (char)consumer.read();
}
result = new String(chars);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally {
try {
consumer.close();
}
catch (IOException e) {
e.printStackTrace();
}
done = true;
synchronized (this) {
notifyAll();
}
}
}
/**
* Starts this object as a thread, which results in the run() method being
* invoked and work being done.
*/
public String getResult() {
Thread reader = new Thread(this, "Piper-"+pipecount);
reader.start();
while (!done) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return result;
}
}
| 7,256 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/TestSrcContent.java | package test.utils;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import java.io.File;
import java.io.FileInputStream;
/**
* This TestCase verifies that content of the source files adheres
* to certain coding practices by matching regular expressions
* (string patterns):
*
* - Verify that Log4J logger is not being used directly
* ("org.apache.log4j" is not in source files).
*
* - Verify that System.out.println is not used except
* in wsdl to/from java tooling.
*
* - Verify that log.info(), log.warn(), log.error(), and log.fatal()
* use Messages.getMessage() (i18n).
*
* - Verify that exceptions are created with Messages.getMessage() (i18n).
*
* To add new patterns, search for and append to the
* private attribute 'avoidPatterns'.
*
* Based on code in TestMessages.java.
*/
public class TestSrcContent extends TestCase {
private static final String LS = System.getProperty("line.separator");
private String errors = "";
/**
* If this test is run from xml-axis/java, then walk through the source
* tree (xml-axis/java/src), calling checkFile for each file.
*/
public void testSourceFiles() {
File srcDir = new File("src/main/java");
if (srcDir.exists()) {
walkTree(srcDir);
}
if (!errors.equals("")) {
throw new AssertionFailedError(errors);
}
} // testSourceFiles
/**
* Walk the source tree
*/
private void walkTree(File srcDir) {
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; ++i) {
if (files[i].isDirectory()) {
walkTree(files[i]);
}
else {
checkFile(files[i]);
}
}
} // walkTree
static private class FileNameContentPattern
{
private PatternCompiler compiler = new Perl5Compiler();
private PatternMatcher matcher = new Perl5Matcher();
private Pattern namePattern = null;
private Pattern contentPattern = null;
private boolean expectContent = true;
FileNameContentPattern(String namePattern,
String contentPattern,
boolean expectContentInFile)
{
try {
this.namePattern = compiler.compile(namePattern);
this.contentPattern = compiler.compile(contentPattern);
this.expectContent = expectContentInFile;
}
catch (MalformedPatternException e) {
throw new AssertionFailedError(e.getMessage());
}
}
/**
* This is not a match IFF
* - the name matches, AND
* - the content is not as expected
*/
boolean noMatch(String name, String content)
{
return
matcher.matches(name, namePattern) &&
matcher.contains(content, contentPattern) != expectContent;
}
String getContentPattern() { return contentPattern.getPattern(); }
boolean getExpectContent() { return expectContent; }
};
/**
* Patterns to be checked. Each pattern has three parameters:
* (i) a pattern that matches filenames that are to be checked,
* (ii) a pattern to be searched for in the chosen files
* (iii) whether the pattern is to be allowed (typically false indicating
* not allowed)
* See the Axis Developer's Guide for more information.
*/
private static final FileNameContentPattern avoidPatterns[] =
{
//**
//** For escape ('\'), remember that Java gets first dibs..
//** so double-escape for pattern-matcher to see it.
//**
// Verify that java files do not use Log4j
//
//new FileNameContentPattern(".+\\.java",
// "org\\.apache\\.log4j", false),
new FileNameContentPattern(".+([\\\\/])"
+ "java\\1"
// + "(?!src\\1org\\1apache\\1axis\\1client\\1HappyClient\\.java)"
+ "([a-zA-Z0-9_]+\\1)*"
+ "[^\\\\/]+\\.java",
"org\\.apache\\.log4j", false),
// Verify that axis java files do not use System.out.println
// or System.err.println, except:
// - utils/tcpmon.java
// - providers/BSFProvider.java
// - utils/CLArgsParser.java
// - Version.java
// - tooling in 'org/apache/axis/wsdl'
// - client/AdminClient.java
// - utils/Admin.java
new FileNameContentPattern(".+([\\\\/])"
+ "java\\1src\\1org\\1apache\\1axis\\1"
+ "(?!utils\\1tcpmon\\.java"
+ "|client\\1AdminClient\\.java"
+ "|utils\\1Admin\\.java"
+ "|utils\\1SOAPMonitor\\.java"
+ "|providers\\1BSFProvider\\.java"
+ "|utils\\1CLArgsParser\\.java"
+ "|transport\\1jms\\1SimpleJMSListener\\.java"
+ "|Version\\.java"
+ "|wsdl\\1)"
+ "([a-zA-Z0-9_]+\\1)*"
+ "[^\\\\/]+\\.java",
"System\\.(out|err)\\.println", false),
// Verify that internationalization is being used properly
// with logger. Exceptions:
// - all log.debug calls
// - client/AdminClient.java
// - utils/tcpmon.java
// - utils/Admin.java
// - handlers/LogMessage.java
// - tooling in 'org/apache/axis/wsdl'
//
new FileNameContentPattern(".+([\\\\/])"
+ "java\\1src\\1org\\1apache\\1axis\\1"
+ "(?!utils\\1tcpmon\\.java"
+ "|client\\1AdminClient\\.java"
+ "|utils\\1Admin\\.java"
+ "|utils\\1SOAPMonitor\\.java"
+ "|handlers\\1LogMessage\\.java"
+ "|wsdl\\1)"
+ "([a-zA-Z0-9_]+\\1)*"
+ "[^\\\\/]+\\.java",
"log\\.(info|warn|error|fatal)"
+ "[ \\t]*\\("
+ "(?=[ \\t]*\\\")",
false),
// Verify that exceptions are built with messages.
new FileNameContentPattern(".+([\\\\/])"
+ "java\\1src\\1org\\1apache\\1axis\\1"
+ "([a-zA-Z0-9_]+\\1)*"
+ "[^\\\\/]+\\.java",
"new[ \\t]+[a-zA-Z0-9_]*"
+ "Exception\\(\\)",
false),
// Verify that we don't explicitly create NPEs.
new FileNameContentPattern(".+([\\\\/])"
+ "java\\1src\\1org\\1apache\\1axis\\1"
+ "([a-zA-Z0-9_]+\\1)*"
+ "[^\\\\/]+\\.java",
"new[ \\t]+"
+ "NullPointerException",
false),
};
private void checkFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
try {
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
String content = new String(bytes);
for (int i = 0; i < avoidPatterns.length; i++) {
if (avoidPatterns[i].noMatch(file.getPath(), content)) {
// if (content.indexOf(avoidStrings[i]) >= 0) {
errors = errors
+ "File: " + file.getPath() + ": "
+ (avoidPatterns[i].getExpectContent()
? "Expected: "
: "Unexpected: ")
+ avoidPatterns[i].getContentPattern()
+ LS;
}
}
} finally {
fis.close();
}
}
catch (Throwable t) {
errors = errors
+ "File: " + file.getPath()
+ ": " + t.getMessage()
+ LS;
}
} // checkFile
}
| 7,257 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/cache/TestJavaClass.java | package test.utils.cache;
import junit.framework.TestCase;
import org.apache.axis.utils.cache.JavaClass;
import java.lang.reflect.Method;
public class TestJavaClass extends TestCase
{
public void testGetJavaClass()
{
Class c = new java.util.Date().getClass();
JavaClass jc = new JavaClass(c);
assertNotNull("The JavaClass was null", jc);
assertTrue("JavaClass name is not 'java.util.Date', it is: " + jc.getClass().getName(),
jc.getJavaClass().getName().equals("java.util.Date"));
assertTrue("JavaClass cut off the name of the real class.",
!jc.getJavaClass().getName().equals("java.util.D"));
}
public void testGetMethod()
{
Class v = new java.util.Vector().getClass();
Class st = new java.util.StringTokenizer("some string").getClass();
JavaClass jcVec = new JavaClass(v);
JavaClass jcST = new JavaClass(st);
Method countTkns = jcST.getMethod("countTokens")[0];
Method nextTkn = jcST.getMethod("nextToken")[0];
Method[] adds = jcVec.getMethod("add");
assertEquals("countTkns name was not 'countTokens', it is: " + countTkns.getName(),
"countTokens", countTkns.getName());
assertEquals("nextTkn name was not 'nextToken', it is: " + nextTkn.getName(),
"nextToken", nextTkn.getName());
assertEquals("There are not 2 add methods as expected, there are " + adds.length, 2, adds.length);
for (int i = 0; i < adds.length; ++i) {
if (adds[i].getReturnType().equals(boolean.class)) {
assertEquals("Unexpected boolean add signature",
"public synchronized boolean java.util.Vector.add(java.lang.Object)",
adds[i].toString());
}
else {
assertEquals("Unexpected void add signature",
"public void java.util.Vector.add(int,java.lang.Object)",
adds[i].toString());
}
}
}
public void testNoSuchMethod()
{
Class v = new java.util.Vector().getClass();
JavaClass jcVec = new JavaClass(v);
Method[] gorp = jcVec.getMethod("gorp");
assertNull("gorp was not null", gorp);
}
}
| 7,258 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/cache/TestJavaMethod.java | package test.utils.cache;
import junit.framework.TestCase;
import org.apache.axis.utils.cache.JavaMethod;
import java.lang.reflect.Method;
public class TestJavaMethod extends TestCase
{
public void testGetMethodWithVectorMethods()
{
Class vector = new java.util.Vector().getClass();
JavaMethod jmAdd = new JavaMethod(vector, "add");
assertNotNull("jmAdd was null", jmAdd);
Method[] adds = jmAdd.getMethod();
assertEquals("There are not 2 add methods as expected, there are " + adds.length, 2, adds.length);
for (int i = 0; i < adds.length; ++i) {
if (adds[i].getReturnType().equals(boolean.class)) {
assertEquals("Unexpected boolean add signature",
"public synchronized boolean java.util.Vector.add(java.lang.Object)",
adds[i].toString());
}
else {
assertEquals("Unexpected void add signature",
"public void java.util.Vector.add(int,java.lang.Object)",
adds[i].toString());
}
}
}
public void testGetMethodWithOverloadedStringValueOf()
{
/* RJB - now that I've removed the numArgs parameter, is this test really testing anything?
Class str = new String().getClass();
JavaMethod jm = new JavaMethod(str, "valueOf");
assertNotNull("JavaMethod is null", jm);
Method methodWithOneParam = jm.getMethod()[0];
assertEquals("Method with one param is not 'valueOf'", "valueOf",methodWithOneParam.getName());
Method methodWithThreeParams = jm.getMethod()[0];
assertEquals("Method with two params is not 'valueOf'", "valueOf",methodWithThreeParams.getName());
assertEquals("Method with one param return type is not 'java.lang.String'", "java.lang.String", methodWithOneParam.getReturnType().getName());
assertEquals("Method with two parama return type is not 'java.lang.String'", "java.lang.String", methodWithThreeParams.getReturnType().getName());
boolean gotError = false;
try {
Method nonceMethod = jm.getMethod()[0]; //should be no valueOf() method with 2 params
nonceMethod.getName();
}
catch (NullPointerException ex) {
gotError = true;
}
assertTrue("Expected NullPointerException", gotError);
*/
}
}
| 7,259 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/bytecode/TestParamNameExtractor.java | package test.utils.bytecode;
import junit.framework.TestCase;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ArrayList;
import org.apache.axis.utils.bytecode.ParamNameExtractor;
/**
* Description
* User: pengyu
* Date: Sep 12, 2003
* Time: 11:47:48 PM
*
*/
public class TestParamNameExtractor extends TestCase {
public void testExtractParameter() {
//now get the nonoverloadmethod
Method[] methods = TestClass.class.getMethods();
Method method = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("nonOverloadMethod")) {
method = methods[i];
}
}
assertTrue("Find nonOverloadMethod", method != null);
String[] params = ParamNameExtractor.getParameterNamesFromDebugInfo(method);
assertTrue("Number of parameter is right", params.length == 2);
assertTrue("First name of parameter is intValue", params[0].equals("intValue"));
assertTrue("Second name of parameter is boolValue", params[1].equals("boolValue"));
}
public void testExtractOverloadedParameter() {
Method[] methods = TestClass.class.getMethods();
List matchMethods = new ArrayList();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("overloadedMethod")) {
matchMethods.add(methods[i]);
}
}
assertTrue("Found two overloaded methods", matchMethods.size() == 2);
boolean foundBoolean = false;
boolean foundInt = false;
for (int i = 0; i < 2; i++) {
Method method = (Method) matchMethods.get(i);
Class[] paramTypes = method.getParameterTypes();
assertTrue("only one parameter found", paramTypes.length == 1);
assertTrue("It has to be either boolean or int",
(paramTypes[0] == Integer.TYPE) ||
(paramTypes[0] == Boolean.TYPE));
String[] params = ParamNameExtractor.getParameterNamesFromDebugInfo(method);
assertTrue("Only parameter found", params.length == 1);
if (paramTypes[0] == Integer.TYPE) {
if (foundInt) { //already found such method so something is wrong
fail("It is wrong type, should not be int");
}else {
foundInt = true;
}
assertTrue("parameter is 'intValue'", params[0].equals("intValue"));
} else if (paramTypes[0] == Boolean.TYPE) {
if (foundBoolean) {
fail("It is wrong type, should not be boolean");
}else {
foundBoolean = true;
}
assertTrue("parameter is 'boolValue'", params[0].equals("boolValue"));
}
}
}
class TestClass {
public void nonOverloadMethod(int intValue, boolean boolValue) {
}
public void overloadedMethod(int intValue) {
}
public void overloadedMethod(boolean boolValue) {
}
}
}
| 7,260 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/bytecode/TestChainedParamReader.java | package test.utils.bytecode;
import junit.framework.TestCase;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import org.apache.axis.utils.bytecode.ChainedParamReader;
/**
* Description
* User: pengyu
* Date: Sep 13, 2003
* Time: 10:59:00 PM
*
*/
public class TestChainedParamReader extends TestCase{
private TestDerivedClass test =null;
private ChainedParamReader reader;
public void testGetMethodParameters(){
try {
reader = new ChainedParamReader(TestDerivedClass.class);
} catch (IOException e) {
fail("failed to setup paramreader:" + e.getMessage());
}
assertTrue("should not be null", reader != null);
//first get method1
try {
Method method1 = TestDerivedClass.class.getMethod("method1", new Class[] {Boolean.TYPE});
String [] params = reader.getParameterNames(method1);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'boolValue'", params[0].equals("boolValue"));
Method method2 = TestDerivedClass.class.getMethod("method2", new Class[] {Boolean.TYPE});
params = reader.getParameterNames(method2);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'boolValue'", params[0].equals("boolValue"));
method2= TestDerivedClass.class.getMethod("method2", new Class[] {Integer.TYPE});
params = reader.getParameterNames(method2);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'intValue'", params[0].equals("intValue"));
} catch (NoSuchMethodException e) {
fail(e.toString());
} catch (SecurityException e) {
fail(e.toString());
}
}
public void testGetConstructorParameters() {
try {
reader = new ChainedParamReader(TestDerivedClass.class);
assertTrue("should not be null", reader != null);
Constructor ctor = TestDerivedClass.class.getConstructor(new Class[] {
TestChainedParamReader.class, Integer.TYPE});
String [] params = reader.getParameterNames(ctor);
assertTrue("params is not null" , params.length == 2);
assertTrue("param name is 'in'", params[1].equals("in"));
}
catch (IOException e) {
fail("failed to setup paramreader:" + e.getMessage());
}
catch (NoSuchMethodException e) {
fail(e.getMessage());
}
}
public void testGetInheritedMethodParameters() {
try {
reader = new ChainedParamReader(TestDerivedClass.class);
Method method3 = TestDerivedClass.class.getMethod("subClassInherit", new Class[] {Integer.TYPE});
String [] params = reader.getParameterNames(method3);
assertTrue("It should find inherited method", params != null);
} catch (IOException e) {
fail("failed to setup paramreader:" + e.getMessage());
} catch (NoSuchMethodException e) {
fail(e.toString());
}
}
class TestBaseClass {
public void subClassInherit(int intValue) {
}
}
class TestDerivedClass extends TestBaseClass{
public TestDerivedClass() {
}
public TestDerivedClass(int in) {
}
public void method1(boolean boolValue) {
}
public void method2(int intValue) {
}
public void method2(boolean boolValue) {
}
}
}
| 7,261 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/utils/bytecode/TestParamReader.java | package test.utils.bytecode;
import junit.framework.TestCase;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.io.IOException;
import org.apache.axis.utils.bytecode.ParamReader;
/**
* Description
* User: pengyu
* Date: Sep 12, 2003
* Time: 11:51:28 PM
*
*/
public class TestParamReader extends TestCase{
private ParamReader reader;
public void testGetMethodParameters(){
try {
reader = new ParamReader(TestDerivedClass.class);
} catch (IOException e) {
fail("failed to setup paramreader:" + e.getMessage());
}
assertTrue("should not be null", reader != null);
//first get method1
try {
Method method1 = TestDerivedClass.class.getMethod("method1", new Class[] {Boolean.TYPE});
String [] params = reader.getParameterNames(method1);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'boolValue'", params[0].equals("boolValue"));
Method method2 = TestDerivedClass.class.getMethod("method2", new Class[] {Boolean.TYPE});
params = reader.getParameterNames(method2);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'boolValue'", params[0].equals("boolValue"));
method2= TestDerivedClass.class.getMethod("method2", new Class[] {Integer.TYPE});
params = reader.getParameterNames(method2);
assertTrue("one parameter only",params.length == 1);
assertTrue("It is 'intValue'", params[0].equals("intValue"));
Method method3 = TestDerivedClass.class.getMethod("subClassInherit", new Class[] {Integer.TYPE});
params = reader.getParameterNames(method3);
assertTrue("It should not find inherited method", params == null);
} catch (NoSuchMethodException e) {
fail(e.toString());
} catch (SecurityException e) {
fail(e.toString());
}
}
public void testGetConstructorParameters() {
try {
reader = new ParamReader(TestDerivedClass.class);
assertTrue("should not be null", reader != null);
Constructor ctor = TestDerivedClass.class.getConstructor(new Class[] {
TestParamReader.class, Integer.TYPE});
String [] params = reader.getParameterNames(ctor);
assertTrue("params is not null" , params.length == 2);
assertTrue("param name is 'in'", params[1].equals("in"));
}
catch (IOException e) {
fail("failed to setup paramreader:" + e.getMessage());
}
catch (NoSuchMethodException e) {
fail(e.getMessage());
}
}
class TestBaseClass {
public void subClassInherit(int intValue) {
}
}
class TestDerivedClass extends TestBaseClass{
public TestDerivedClass() {
}
public TestDerivedClass(int in) {
}
public void method1(boolean boolValue) {
}
public void method2(int intValue) {
}
public void method2(boolean boolValue) {
}
}
}
| 7,262 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestPrefixes.java | package test.saaj;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
/**
* Test case for Prefixes
*/
public class TestPrefixes extends junit.framework.TestCase {
/**
* Test for Bug 18274 - prefix name not set during adding child element
* @throws Exception
*/
public void testAddingPrefixesForChildElements() throws Exception {
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage msg = factory.createMessage();
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
SOAPElement el1 = sb.addBodyElement(se.createName
("element1", "prefix1", "http://www.sun.com"));
SOAPElement el2 = el1.addChildElement(se.createName
("element2", "prefix2", "http://www.apache.org"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
String xml = new String(baos.toByteArray());
assertTrue(xml.indexOf("prefix1") != -1);
assertTrue(xml.indexOf("prefix2") != -1);
assertTrue(xml.indexOf("http://www.sun.com") != -1);
assertTrue(xml.indexOf("http://www.apache.org") != -1);
}
public void testAttribute() throws Exception {
String soappacket = "<SOAP-ENV:Envelope xmlns:SOAP-ENV =\"http://schemas.xmlsoap.org/soap/envelope/\"" +
" xmlns:xsi =\"http://www.w3.org/1999/XMLSchema-instance\"" +
" xmlns:xsd =\"http://www.w3.org/1999/XMLSchema\">" +
" <SOAP-ENV:Body> " +
" <helloworld name=\"tester\" />" +
" </SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
SOAPMessage msg = MessageFactory.newInstance().createMessage(new MimeHeaders(), new ByteArrayInputStream(soappacket.getBytes()));
SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
SOAPElement ele = (SOAPElement) body.getChildElements().next();
Iterator attit = ele.getAllAttributes();
Name n = (Name) attit.next();
assertEquals("Test fail prefix problem",n.getQualifiedName(),"name");
}
}
| 7,263 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestHeaders.java | package test.saaj;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
public class TestHeaders extends junit.framework.TestCase {
public void testAddingHeaderElements() throws Exception {
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope();
SOAPHeader header = soapEnv.getHeader();
header.addChildElement("ebxmlms");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
soapMessage.writeTo(baos);
String xml = new String(baos.toByteArray());
assertTrue(xml.indexOf("ebxmlms") != -1);
}
private final String actor = "ACTOR#1";
private final String localName = "Local1";
private final String namespace = "http://ws.apache.org";
private final String prefix = "P1";
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <soapenv:Body>\n" +
" <shw:Address xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n" +
" <shw:City>GENT</shw:City>\n" +
" </shw:Address>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
public void testAddingHeaderElements2() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage soapMessage = mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope();
SOAPHeader header = soapEnv.getHeader();
Name headerName = soapEnv.createName(localName, prefix, prefix);
SOAPHeaderElement he = header.addHeaderElement(headerName);
he.setActor(actor);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
soapMessage.writeTo(baos);
String xml = new String(baos.toByteArray());
assertTrue(xml.indexOf(localName) != -1);
}
public void testExtractAllHeaders() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage soapMessage = mf.createMessage();
SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
SOAPHeader hdr = envelope.getHeader();
SOAPHeaderElement she1 = hdr.addHeaderElement(envelope.createName("foo1", "f1", "foo1-URI"));
she1.setActor("actor-URI");
Iterator iterator = hdr.extractAllHeaderElements();
SOAPHeaderElement she = null;
int cnt = 0;
while (iterator.hasNext()) {
cnt++;
she = (SOAPHeaderElement) iterator.next();
assertEquals(she, she1);
}
assertEquals(1, cnt);
iterator = hdr.extractAllHeaderElements();
assertTrue(!iterator.hasNext());
}
public void testExamineAllHeaders() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage soapMessage = mf.createMessage();
SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
SOAPHeader hdr = envelope.getHeader();
SOAPHeaderElement she1 = hdr.addHeaderElement(envelope.createName("foo1", "f1", "foo1-URI"));
she1.setActor("actor-URI");
Iterator iterator = hdr.examineAllHeaderElements();
SOAPHeaderElement she = null;
int cnt = 0;
while (iterator.hasNext()) {
cnt++;
she = (SOAPHeaderElement) iterator.next();
assertEquals(she, she1);
}
assertEquals(1, cnt);
iterator = hdr.examineAllHeaderElements();
assertTrue(iterator.hasNext());
}
}
| 7,264 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestMessageProperty.java | package test.saaj;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.Text;
public class TestMessageProperty extends junit.framework.TestCase {
private static final String textValue = "\uc548\ub155\ud558\uc138\uc694";
private SOAPMessage createTestMessage() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPBody sb = msg.getSOAPBody();
SOAPElement se1 = sb.addChildElement("echoString", "ns1", "http://tempuri.org");
SOAPElement se2 = se1.addChildElement("string");
se2.addTextNode(textValue);
return msg;
}
public void testWriteXmlDeclPropertyTrue() throws Exception {
testXmlDecl("true", "<?xml");
}
public void testWriteXmlDeclPropertyFalse() throws Exception {
testXmlDecl("false", "<soapenv:Envelope");
}
public void testEncodingPropertyUTF16() throws Exception {
testEncoding("UTF-16");
}
public void testEncodingPropertyUTF8() throws Exception {
testEncoding("UTF-8");
}
private void testXmlDecl(String xmlDecl, String expected) throws Exception {
SOAPMessage msg = createTestMessage();
msg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, xmlDecl);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
String msgString = new String(baos.toByteArray(), "UTF-8");
System.out.println("msgString =" + msgString);
assertTrue(msgString.startsWith(expected));
}
private void testEncoding(String encoding) throws Exception {
SOAPMessage msg = createTestMessage();
msg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
msg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encoding);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
String msgString = new String(baos.toByteArray(), encoding);
System.out.println("msgString (" + encoding + ")=" + msgString);
assertTrue(msgString.startsWith("<?xml version=\"1.0\" encoding=\"" + encoding + "\""));
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
SOAPMessage msg1 = createMessageFromInputStream(bais);
SOAPElement se1 = (SOAPElement) msg1.getSOAPBody().getChildElements().next();
SOAPElement se2 = (SOAPElement) se1.getChildElements().next();
Text text = (Text)se2.getChildElements().next();
assertEquals(textValue, text.getValue());
}
private SOAPMessage createMessageFromInputStream(InputStream is) throws Exception {
MessageFactory mf = MessageFactory.newInstance();
return mf.createMessage(new MimeHeaders(), is);
}
}
| 7,265 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestDOM.java | package test.saaj;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.RPCElement;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.custommonkey.xmlunit.XMLUnit;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPBodyElement;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import test.AxisTestBase;
public class TestDOM extends AxisTestBase {
public void testOwnerDocument() throws Exception {
final SOAPMessage message = MessageFactory.newInstance().createMessage();
SOAPPart soapPart = message.getSOAPPart();
assertNotNull("envelope should have an owner document",
message.getSOAPPart().getEnvelope().getOwnerDocument());
assertNotNull("soap part must have a document element",
soapPart.getDocumentElement());
assertNotNull(
"soap part's document element's owner document should not be null",
soapPart.getDocumentElement().getOwnerDocument());
}
private static final String SAMPLE_1 =
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "\n" +
"<SOAP-ENV:Body> " + "\n" +
"<m:GetLastTradePrice xmlns:m=\"http://wombat.ztrade.com\">" + "\n" +
"<symbol>SUNW</symbol> " + "\n" +
"</m:GetLastTradePrice> " + "\n" +
"</SOAP-ENV:Body> " + "\n" +
"</SOAP-ENV:Envelope>";
private SOAPMessage getSOAPMessageFromString(String str) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("content-type", "text/xml");
SOAPMessage message = MessageFactory.newInstance().createMessage(
mimeHeaders,
new ByteArrayInputStream(str.getBytes()));
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
SOAPHeader header = message.getSOAPHeader();
if (header == null) {
header = envelope.addHeader();
}
return message;
}
public void testSAAJSerialization() throws Exception {
SOAPMessage message1 = this.getSOAPMessageFromString(SAMPLE_1);
SOAPHeader header1 = message1.getSOAPHeader();
boolean oldIgnore = XMLUnit.getIgnoreWhitespace();
XMLUnit.setIgnoreWhitespace(true);
try {
//this is how header element is added in sun's example
SOAPFactory soapFactory = SOAPFactory.newInstance();
Name headerName = soapFactory.createName("Claim",
"wsi", "http://ws-i.org/schemas/conformanceClaim/");
SOAPHeaderElement headerElement =
header1.addHeaderElement(headerName);
headerElement.addAttribute(soapFactory.createName("conformsTo"), "http://ws-i.org/profiles/basic1.0/");
final String domToString1 = XMLUtils.PrettyDocumentToString(
message1.getSOAPPart());
final String messageToString1 = messageToString(message1);
assertXMLEqual(domToString1, messageToString1);
} finally {
XMLUnit.setIgnoreWhitespace(oldIgnore);
}
}
public void testSAAJSerialization2() throws Exception {
SOAPMessage message2 = this.getSOAPMessageFromString(SAMPLE_1);
SOAPHeader header2 = message2.getSOAPHeader();
boolean oldIgnore = XMLUnit.getIgnoreWhitespace();
XMLUnit.setIgnoreWhitespace(true);
try {
Element header2Element = header2.getOwnerDocument().createElementNS(
"http://ws-i.org/schemas/conformanceClaim/", "wsi:Claim");
header2Element.setAttributeNS(
"http://ws-i.org/schemas/conformanceClaim/",
"wsi:conformsTo", "http://ws-i.org/profiles/basic1.0/");
header2.appendChild(header2Element);
final String domToString2 = XMLUtils.PrettyDocumentToString(
message2.getSOAPPart());
final String messageToString2 = messageToString(message2);
assertXMLEqual(domToString2, messageToString2);
} finally {
XMLUnit.setIgnoreWhitespace(oldIgnore);
}
}
public void testRPCParams() throws Exception {
SOAPMessage message = MessageFactory.newInstance().createMessage();
RPCParam arg1 = new RPCParam("urn:myNamespace", "testParam1",
"this is a string #1");
RPCParam arg2 = new RPCParam("urn:myNamespace", "testParam2",
"this is a string #2");
RPCElement body = new RPCElement("urn:myNamespace", "method1",
new Object[]{arg1, arg2});
SOAPPart sp = message.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
sb.addChildElement(body);
Iterator it = sb.getChildElements();
assertTrue(it.hasNext());
SOAPElement elem = (SOAPElement) it.next();
Name name2 = se.createName("testParam1", "", "urn:myNamespace");
Iterator it2 = elem.getChildElements(name2);
assertTrue(it2.hasNext());
while (it2.hasNext()) {
SOAPElement elem2 = (SOAPElement) it2.next();
System.out.println("child = " + elem2);
}
Name name3 = se.createName("testParam2", "", "urn:myNamespace");
Iterator it3 = elem.getChildElements(name3);
assertTrue(it3.hasNext());
while (it3.hasNext()) {
SOAPElement elem3 = (SOAPElement) it3.next();
System.out.println("child = " + elem3);
}
}
public void testAddDocument() throws Exception {
String xml = "<bank:getBalance xmlns:bank=\"http://myservice.test.com/banking/\">\n" +
" <gb:getBalanceReq xmlns:gb=\"http://myservice.test.com/banking/getBalance\">\n" +
" <bt:account acctType=\"domestic\" customerId=\"654321\" xmlns:bt=\"http://myservice.test.com/banking/bankTypes\">\n" +
" <bt:accountNumber>1234567890</bt:accountNumber>\n" +
" <bt:currency>USD</bt:currency>\n" +
" </bt:account>\n" +
" </gb:getBalanceReq>\n" +
"</bank:getBalance>";
Document document = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
MessageFactory factory = new org.apache.axis.soap.MessageFactoryImpl();
SOAPMessage msg = factory.createMessage();
msg.getSOAPBody();
SOAPBody body = msg.getSOAPBody();
SOAPBodyElement soapBodyElt = body.addDocument(document);
assertXMLEqual(xml, soapBodyElt.toString());
}
public void testForParent() throws Exception {
String NL = System.getProperty("line.separator");
String SOAP_STR =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"+NL+
" <soapenv:Body>"+NL+
" <rtnElement>"+NL+
" <USAddress>"+NL+
" <name>Robert Smith</name>"+NL+
" </USAddress>"+NL+
" </rtnElement>"+NL+
" </soapenv:Body>"+NL+
"</soapenv:Envelope>";
java.io.InputStream is =
new java.io.ByteArrayInputStream(SOAP_STR.getBytes());
org.apache.axis.Message msg = new org.apache.axis.Message
(is, false, "text/xml;charset=utf-8", null);
// get the SOAPEnvelope (a SAAJ instance)
javax.xml.soap.SOAPEnvelope senv = msg.getSOAPEnvelope();
javax.xml.soap.SOAPBody sbody = senv.getBody();
javax.xml.soap.SOAPElement rtnElement =
(javax.xml.soap.SOAPElement) sbody.getChildElements().next();
javax.xml.soap.SOAPElement addrElement =
(javax.xml.soap.SOAPElement) rtnElement.getChildElements().next();
javax.xml.soap.SOAPElement nameElement =
(javax.xml.soap.SOAPElement) addrElement.getChildElements().next();
javax.xml.soap.Node textNode =
(javax.xml.soap.Node) nameElement.getChildElements().next();
assertNotNull
("A DOM node parent (within a SOAPElement) should never be null.",
(org.w3c.dom.Node) textNode.getParentNode());
}
private String messageToString(SOAPMessage message) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
message.writeTo(baos);
return new String(baos.toByteArray());
}
}
| 7,266 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestSOAPFaults.java | package test.saaj;
import test.AxisTestBase;
import javax.xml.soap.Detail;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.DetailEntry;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import org.custommonkey.xmlunit.XMLUnit;
public class TestSOAPFaults extends AxisTestBase {
public void testQuick() throws Exception {
MessageFactory msgfactory = MessageFactory.newInstance();
SOAPFactory factory = SOAPFactory.newInstance();
SOAPMessage outputmsg = msgfactory.createMessage();
String valueCode = "faultcode";
String valueString = "faultString";
SOAPFault fault = outputmsg.getSOAPPart().getEnvelope().getBody().addFault();
fault.setFaultCode(valueCode);
fault.setFaultString(valueString);
Detail d;
d = fault.addDetail();
d.addDetailEntry(factory.createName("Hello"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (outputmsg != null) {
if (outputmsg.saveRequired()) {
outputmsg.saveChanges();
}
outputmsg.writeTo(baos);
}
String xml = new String(baos.toByteArray());
assertTrue(xml.indexOf("Hello")!=-1);
}
public void testSOAPFaultSaveChanges() throws Exception {
MessageFactory msgFactory =
MessageFactory.newInstance();
SOAPMessage msg = msgFactory.createMessage();
SOAPEnvelope envelope =
msg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
SOAPFault fault = body.addFault();
fault.setFaultCode("Client");
fault.setFaultString(
"Message does not have necessary info");
fault.setFaultActor("http://gizmos.com/order");
Detail detail = fault.addDetail();
Name entryName = envelope.createName("order", "PO",
"http://gizmos.com/orders/");
DetailEntry entry = detail.addDetailEntry(entryName);
entry.addTextNode(
"quantity element does not have a value");
Name entryName2 = envelope.createName("confirmation",
"PO", "http://gizmos.com/confirm");
DetailEntry entry2 = detail.addDetailEntry(entryName2);
entry2.addTextNode("Incomplete address: no zip code");
msg.saveChanges();
// Now retrieve the SOAPFault object and its contents
//after checking to see that there is one
if (body.hasFault()) {
fault = body.getFault();
String code = fault.getFaultCode();
String string = fault.getFaultString();
String actor = fault.getFaultActor();
System.out.println("SOAP fault contains: ");
System.out.println(" fault code = " + code);
System.out.println(" fault string = " + string);
if (actor != null) {
System.out.println(" fault actor = " + actor);
}
detail = fault.getDetail();
if (detail != null) {
Iterator it = detail.getDetailEntries();
while (it.hasNext()) {
entry = (DetailEntry) it.next();
String value = entry.getValue();
System.out.println(" Detail entry = " + value);
}
}
}
}
public void testAxis1432() throws Exception {
String xml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:cwmp=\"http://cwmp.com\">\n" +
" <soapenv:Header>\n" +
" <cwmp:ID soapenv:mustUnderstand=\"1\">HEADERID-7867678</cwmp:ID>\n" +
" </soapenv:Header>\n" +
" <soapenv:Body>\n" +
" <soapenv:Fault>\n" +
" <faultcode>soapenv:Client</faultcode>\n" +
" <faultstring>CWMP fault</faultstring>\n" +
" <detail>\n" +
" <cwmp:Fault>\n" +
" <cwmp:FaultCode>This is the fault code</cwmp:FaultCode>\n" +
" <cwmp:FaultString>Fault Message</cwmp:FaultString>\n" +
" </cwmp:Fault>\n" +
" </detail>\n" +
" </soapenv:Fault>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
MessageFactory fac = MessageFactory.newInstance();
SOAPMessage faultMessage = fac.createMessage();
// Create the response to the message
faultMessage = fac.createMessage();
SOAPPart part = faultMessage.getSOAPPart();
SOAPEnvelope envelope = part.getEnvelope();
envelope.addNamespaceDeclaration("cwmp", "http://cwmp.com");
SOAPBody body = envelope.getBody();
SOAPHeader header = envelope.getHeader();
Name idName = envelope.createName("ID", "cwmp", "http://cwmp.com");
SOAPHeaderElement id = header.addHeaderElement(idName);
id.setMustUnderstand(true);
id.addTextNode("HEADERID-7867678");
id.setActor(null);
// Create the SOAPFault object
SOAPFault fault = body.addFault();
fault.setFaultCode("Client");
fault.setFaultString("CWMP fault");
fault.setFaultActor(null);
// Add Fault Detail information
Detail faultDetail = fault.addDetail();
Name cwmpFaultName = envelope.createName("Fault", "cwmp",
"http://cwmp.com");
DetailEntry cwmpFaultDetail =
faultDetail.addDetailEntry(cwmpFaultName);
SOAPElement e = cwmpFaultDetail.addChildElement("FaultCode");
e.addTextNode("This is the fault code");
SOAPElement e2 = cwmpFaultDetail.addChildElement(envelope.createName("FaultString", "cwmp", "http://cwmp.com"));
e2.addTextNode("Fault Message");
faultMessage.saveChanges();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
faultMessage.writeTo(baos);
String xml2 = new String(baos.toByteArray());
boolean ws = XMLUnit.getIgnoreWhitespace();
try {
XMLUnit.setIgnoreWhitespace(true);
assertXMLEqual(xml,xml2);
} finally {
XMLUnit.setIgnoreWhitespace(ws);
}
}
}
| 7,267 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestSOAPElement.java | package test.saaj;
import junit.framework.TestCase;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.Text;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.ByteArrayInputStream;
import org.w3c.dom.NodeList;
/**
* Test case for Axis impl of SAAJ {@link SOAPElement} interface ({@link org.apache.axis.message.MessageElement}).
*
* @author Ian P. Springer
*/
public class TestSOAPElement extends TestCase
{
private SOAPElement soapElem;
protected void setUp() throws Exception
{
soapElem = SOAPFactory.newInstance().createElement( "Test", "test", "http://test.apache.org/" );
}
public void testGetElementsByTagName() throws Exception {
String soapMessageWithLeadingComment =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<env:Body>" +
"<echo>" +
" <data>\n" +
" <tag name=\"First\" >\n" +
" <Line> One </Line>\n" +
" <Line> Two </Line>\n" +
" </tag>\n" +
" <tag name =\"Second\" >\n" +
" <Line> Three </Line>\n" +
" <Line> Four </Line>\n" +
" </tag>\n" +
" <tag name =\"Third\" >\n" +
" <Line> Five </Line>\n" +
" <Line> Six </Line>\n" +
" </tag>\n" +
"</data>" +
"</echo>" +
"</env:Body>" +
"</env:Envelope>";
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message =
factory.createMessage(new MimeHeaders(),
new ByteArrayInputStream(soapMessageWithLeadingComment.getBytes()));
SOAPPart part = message.getSOAPPart();
SOAPEnvelope envelope = (SOAPEnvelope) part.getEnvelope();
NodeList nodes = envelope.getElementsByTagName("tag");
assertEquals(nodes.getLength(), 3);
NodeList nodes2 = envelope.getElementsByTagName("Line");
assertEquals(nodes2.getLength(), 6);
NodeList nodes3 = part.getElementsByTagName("tag");
assertEquals(nodes3.getLength(), 3);
NodeList nodes4 = part.getElementsByTagName("Line");
assertEquals(nodes4.getLength(), 6);
}
/**
* Test for Axis impl of {@link SOAPElement#addTextNode(String)}.
*
* @throws Exception on error
*/
public void testAddTextNode() throws Exception
{
assertNotNull( soapElem );
final String value = "foo";
soapElem.addTextNode( value );
assertEquals( value, soapElem.getValue() );
Text text = assertContainsText( soapElem );
assertEquals( value, text.getValue() );
}
private Text assertContainsText( SOAPElement soapElem )
{
assertTrue( soapElem.hasChildNodes() );
List childElems = toList( soapElem.getChildElements() );
assertTrue( childElems.size() == 1 );
Node node = (Node) childElems.get( 0 );
assertTrue( node instanceof Text );
return (Text) node;
}
private List toList( Iterator iter )
{
List list = new ArrayList();
while ( iter.hasNext() )
{
list.add( iter.next() );
}
return list;
}
}
| 7,268 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestImport.java | package test.saaj;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import test.AxisTestBase;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
public class TestImport extends AxisTestBase {
private static final String SAMPLE_1 =
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"\n" +
"<SOAP-ENV:Body> " + "\n" +
"<m:GetLastTradePrice xmlns:m=\"http://wombat.ztrade.com\">" +
"\n" +
"<symbol>SUNW</symbol> " + "\n" +
"</m:GetLastTradePrice> " + "\n" +
"</SOAP-ENV:Body> " + "\n" +
"</SOAP-ENV:Envelope>";
private SOAPMessage getSOAPMessageFromString(String str) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("content-type", "text/xml");
SOAPMessage message = MessageFactory.newInstance().createMessage(
mimeHeaders,
new ByteArrayInputStream(str.getBytes()));
return message;
}
public void testImports() throws Exception {
//DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//DocumentBuilder db = dbf.newDocumentBuilder();
//Document doc1 = db.parse(new ByteArrayInputStream(SAMPLE_1.getBytes()));
Document doc2 = testImportFromSaajToDom();
Document body = testImportFromDomToSaaj(doc2);
XMLUtils.PrettyDocumentToStream(body, System.out);
//assertXMLEqual(doc1, body);
//assertXMLEqual(doc2, body);
//assertXMLEqual(doc1, doc2);
}
private Document testImportFromSaajToDom() throws Exception {
SOAPMessage message = getSOAPMessageFromString(SAMPLE_1);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
org.w3c.dom.Node fromNode = message.getSOAPBody().getFirstChild();
Node n = doc.importNode(fromNode, true);
doc.appendChild(n);
return doc;
}
private Document testImportFromDomToSaaj(Document doc) throws Exception {
SOAPMessage sm = MessageFactory.newInstance().createMessage();
SOAPPart sp = sm.getSOAPPart();
SOAPBody body = sm.getSOAPBody();
org.w3c.dom.Node node = sp.importNode(doc.getDocumentElement(), true);
body.appendChild(node);
return sp;
}
}
| 7,269 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestAttachmentSerialization.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 test.saaj;
import junit.framework.TestCase;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import javax.activation.DataHandler;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/** Test the attachments load/save sample code.
*/
public class TestAttachmentSerialization extends TestCase {
static Log log = LogFactory.getLog(TestAttachmentSerialization.class.getName());
public void testAttachments() throws Exception {
try {
ByteArrayOutputStream bais = new ByteArrayOutputStream();
int count1 = saveMsgWithAttachments(bais);
int count2 = loadMsgWithAttachments(new ByteArrayInputStream(bais.toByteArray()));
assertEquals(count1, count2);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Fault returned from test: " + e);
}
}
public static final String MIME_MULTIPART_RELATED = "multipart/related";
public static final String MIME_APPLICATION_DIME = "application/dime";
public static final String NS_PREFIX = "jaxmtst";
public static final String NS_URI = "http://www.jcommerce.net/soap/jaxm/TestJaxm";
public int saveMsgWithAttachments(OutputStream os) throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope envelope = sp.getEnvelope();
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();
SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
SOAPElement el3 = el2.addTextNode("field4value");
el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
el2.addTextNode("bodyvalue3a");
el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
el2.addTextNode("bodyvalue3b");
el2 = el.addChildElement("datefield", NS_PREFIX);
AttachmentPart ap = msg.createAttachmentPart();
ap.setContent("some attachment text...", "text/plain");
msg.addAttachmentPart(ap);
DataHandler dh = new DataHandler("test content", "text/plain");
AttachmentPart ap2 = msg.createAttachmentPart(dh);
ap2.setContentType("text/plain");
msg.addAttachmentPart(ap2);
// Test for Bug #17664
if(msg.saveRequired()) {
msg.saveChanges();
}
MimeHeaders headers = msg.getMimeHeaders();
assertTrue(headers != null);
String [] contentType = headers.getHeader("Content-Type");
assertTrue(contentType != null);
msg.writeTo(os);
os.flush();
return msg.countAttachments();
}
public int loadMsgWithAttachments(InputStream is) throws Exception {
MimeHeaders headers = new MimeHeaders();
headers.setHeader("Content-Type", MIME_MULTIPART_RELATED);
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage(headers, is);
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope envelope = sp.getEnvelope();
assertTrue(sp != null);
assertTrue(envelope != null);
return msg.countAttachments();
}
}
| 7,270 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestSOAPFaultDetail.java |
package test.saaj;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPFault;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.encoding.DeserializationContext;
import org.xml.sax.InputSource;
import javax.xml.soap.DetailEntry;
import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;
public class TestSOAPFaultDetail extends junit.framework.TestCase
{
private MessageContext _msgContext;
public TestSOAPFaultDetail(String name)
{
super(name);
_msgContext = new MessageContext(new AxisServer());
}
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
" <soapenv:Body>" +
" <soapenv:Fault>" +
" <faultcode>soapenv:Server.generalException</faultcode>" +
" <faultstring></faultstring>" +
" <detail>" +
" <tickerSymbol xsi:type=\"xsd:string\">MACR</tickerSymbol>" +
" <ns1:exceptionName xmlns:ns1=\"http://xml.apache.org/axis/\">test.wsdl.faults.InvalidTickerFaultMessage</ns1:exceptionName>" +
" </detail>" +
" </soapenv:Fault>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
public void testDetails() throws Exception
{
Reader reader = new StringReader(xmlString);
InputSource src = new InputSource(reader);
SOAPBodyElement bodyItem = getFirstBody(src);
assertTrue("The SOAPBodyElement I got was not a SOAPFault, it was a " +
bodyItem.getClass().getName(), bodyItem instanceof SOAPFault);
SOAPFault flt = (SOAPFault)bodyItem;
flt.addDetail();
javax.xml.soap.Detail d = flt.getDetail();
Iterator i = d.getDetailEntries();
while (i.hasNext())
{
DetailEntry entry = (DetailEntry) i.next();
String name = entry.getElementName().getLocalName();
if ("tickerSymbol".equals(name)) {
assertEquals("the value of the tickerSymbol element didn't match",
"MACR", entry.getValue());
} else if ("exceptionName".equals(name)) {
assertEquals("the value of the exceptionName element didn't match",
"test.wsdl.faults.InvalidTickerFaultMessage", entry.getValue());
} else {
assertTrue("Expecting details element name of 'tickerSymbol' or 'expceptionName' - I found :" + name, false);
}
}
assertTrue(d != null);
}
private SOAPBodyElement getFirstBody(InputSource msgSource)
throws Exception
{
DeserializationContext dser = new DeserializationContext(
msgSource, _msgContext, Message.RESPONSE);
dser.parse();
SOAPEnvelope env = dser.getEnvelope();
return env.getFirstBody();
}
}
| 7,271 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestAttachment.java | package test.saaj;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
public class TestAttachment extends junit.framework.TestCase {
public void testStringAttachment() throws Exception {
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
AttachmentPart attachment = message.createAttachmentPart();
String stringContent = "Update address for Sunny Skies " +
"Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439";
attachment.setContent(stringContent, "text/plain");
attachment.setContentId("update_address");
message.addAttachmentPart(attachment);
assertTrue(message.countAttachments()==1);
java.util.Iterator it = message.getAttachments();
while (it.hasNext()) {
attachment = (AttachmentPart) it.next();
Object content = attachment.getContent();
String id = attachment.getContentId();
System.out.println("Attachment " + id + " contains: " + content);
assertEquals(content,stringContent);
}
System.out.println("Here is what the XML message looks like:");
message.writeTo(System.out);
message.removeAllAttachments();
assertTrue(message.countAttachments()==0);
}
public void testMultipleAttachments() throws Exception {
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage msg = factory.createMessage();
java.net.URL url1 = TestAttachment.class.getResource("slashdot.xml");
java.net.URL url2 = TestAttachment.class.getResource("LICENSE.txt");
AttachmentPart a1 = msg.createAttachmentPart(new javax.activation.DataHandler(url1));
a1.setContentType("text/xml");
msg.addAttachmentPart(a1);
AttachmentPart a2 = msg.createAttachmentPart(new javax.activation.DataHandler(url1));
a2.setContentType("text/xml");
msg.addAttachmentPart(a2);
AttachmentPart a3 = msg.createAttachmentPart(new javax.activation.DataHandler(url2));
a3.setContentType("text/plain");
msg.addAttachmentPart(a3);
assertTrue(msg.countAttachments()==3);
javax.xml.soap.MimeHeaders mimeHeaders = new javax.xml.soap.MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
int nAttachments = 0;
java.util.Iterator iterator = msg.getAttachments(mimeHeaders);
while (iterator.hasNext()) {
nAttachments++;
AttachmentPart ap = (AttachmentPart)iterator.next();
assertTrue(ap.equals(a1) || ap.equals(a2));
}
assertTrue(nAttachments==2);
}
public void testBadAttSize() throws Exception {
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
ByteArrayInputStream ins=new ByteArrayInputStream(new byte[5]);
DataHandler dh=new DataHandler(new Src(ins,"text/plain"));
AttachmentPart part = message.createAttachmentPart(dh);
assertEquals("Size should match",5,part.getSize());
}
class Src implements DataSource{
InputStream m_src;
String m_type;
public Src(InputStream data, String type){
m_src=data;
m_type=type;
}
public String getContentType(){
return m_type;
}
public InputStream getInputStream() throws IOException{
m_src.reset();
return m_src;
}
public String getName(){
return "Some-Data";
}
public OutputStream getOutputStream(){
throw new UnsupportedOperationException("I don't give output streams");
}
}
}
| 7,272 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestEnvelope.java | package test.saaj;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.Text;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import junit.framework.AssertionFailedError;
public class TestEnvelope extends junit.framework.TestCase {
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <soapenv:Header>\n" +
" <shw:Hello xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n" +
" <shw:Myname>Tony</shw:Myname>\n" +
" </shw:Hello>\n" +
" </soapenv:Header>\n" +
" <soapenv:Body>\n" +
" <shw:Address xmlns:shw=\"http://www.jcommerce.net/soap/ns/SOAPHelloWorld\">\n" +
" <shw:City>GENT</shw:City>\n" +
" </shw:Address>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
// Test JAXM methods...
public void testEnvelope() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage smsg =
mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
SOAPPart sp = smsg.getSOAPPart();
SOAPEnvelope se = (SOAPEnvelope)sp.getEnvelope();
//smsg.writeTo(System.out);
assertTrue(se != null);
}
// Test JAXM methods...
public void testEnvelope2() throws Exception {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage smsg =
mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
SOAPPart sp = smsg.getSOAPPart();
SOAPEnvelope se = (SOAPEnvelope)sp.getEnvelope();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
smsg.writeTo(baos);
SOAPBody body = smsg.getSOAPPart().getEnvelope().getBody();
assertTrue(body != null);
}
public void testEnvelopeWithLeadingComment() throws Exception {
String soapMessageWithLeadingComment =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<!-- Comment -->" +
"<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<env:Body><echo><arg0>Hello</arg0></echo></env:Body>" +
"</env:Envelope>";
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message =
factory.createMessage(new MimeHeaders(),
new ByteArrayInputStream(soapMessageWithLeadingComment.getBytes()));
SOAPPart part = message.getSOAPPart();
SOAPEnvelope envelope = (SOAPEnvelope) part.getEnvelope();
//message.writeTo(System.out);
assertTrue(envelope != null);
}
private SOAPEnvelope getSOAPEnvelope() throws Exception {
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
return envelope;
}
public void testAttributes() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPBody body = envelope.getBody();
Name name1 = envelope.createName("MyAttr1");
String value1 = "MyValue1";
Name name2 = envelope.createName("MyAttr2");
String value2 = "MyValue2";
Name name3 = envelope.createName("MyAttr3");
String value3 = "MyValue3";
body.addAttribute(name1, value1);
body.addAttribute(name2, value2);
body.addAttribute(name3, value3);
java.util.Iterator iterator = body.getAllAttributes();
assertTrue(getIteratorCount(iterator) == 3);
iterator = body.getAllAttributes();
boolean foundName1 = false;
boolean foundName2 = false;
boolean foundName3 = false;
while (iterator.hasNext()) {
Name name = (Name) iterator.next();
if (name.equals(name1))
foundName1 = true;
else if (name.equals(name2))
foundName2 = true;
else if (name.equals(name3))
foundName3 = true;
}
assertTrue(foundName1 && foundName2 && foundName3);
}
public void testFaults() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPBody body = envelope.getBody();
SOAPFault sf = body.addFault();
sf.setFaultCode("myFault");
String fc = sf.getFaultCode();
assertTrue(fc.equals("myFault"));
}
public void testFaults2() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPBody body = envelope.getBody();
SOAPFault sf = body.addFault();
assertTrue(body.getFault() != null);
Detail d1 = sf.addDetail();
Name name = envelope.createName("GetLastTradePrice", "WOMBAT",
"http://www.wombat.org/trader");
d1.addDetailEntry(name);
Detail d2 = sf.getDetail();
assertTrue(d2 != null);
Iterator i = d2.getDetailEntries();
assertTrue(getIteratorCount(i) == 1);
i = d2.getDetailEntries();
while(i.hasNext()) {
DetailEntry de = (DetailEntry)i.next();
assertEquals(de.getElementName(),name);
}
}
public void testHeaderElements() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPBody body = envelope.getBody();
SOAPHeader hdr = envelope.getHeader();
SOAPHeaderElement she1 = hdr.addHeaderElement(envelope.createName("foo1", "f1", "foo1-URI"));
she1.setActor("actor-URI");
java.util.Iterator iterator = hdr.extractHeaderElements("actor-URI");
int cnt = 0;
while (iterator.hasNext()) {
cnt++;
SOAPHeaderElement she = (SOAPHeaderElement) iterator.next();
assertTrue(she.equals(she1));
}
assertTrue(cnt == 1);
iterator = hdr.extractHeaderElements("actor-URI");
assertTrue(!iterator.hasNext());
}
public void testText1() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
Iterator iStart = envelope.getChildElements();
int countStart = getIteratorCount(iStart);
SOAPElement se = envelope.addTextNode("<txt>This is text</txt>");
assertTrue(se != null);
assertTrue(envelope.getValue().equals("<txt>This is text</txt>"));
Iterator i = envelope.getChildElements();
int count = getIteratorCount(i);
assertTrue(count == countStart + 1);
}
public void testText2() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPElement se = envelope.addTextNode("This is text");
Iterator iterator = se.getChildElements();
Node n = null;
while (iterator.hasNext()) {
n = (Node)iterator.next();
if (n instanceof Text)
break;
}
assertTrue(n instanceof Text);
Text t = (Text)n;
assertTrue(!t.isComment());
}
public void testText3() throws Exception {
SOAPEnvelope envelope = getSOAPEnvelope();
SOAPElement se = envelope.addTextNode("<!-- This is a comment -->");
Iterator iterator = se.getChildElements();
Node n = null;
while (iterator.hasNext()) {
n = (Node)iterator.next();
if (n instanceof Text)
break;
}
assertTrue(n instanceof Text);
Text t = (Text)n;
assertTrue(t.isComment());
}
public void testText4() throws SOAPException, IOException {
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage smsg =
mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
// Make some change to the message
SOAPPart sp = smsg.getSOAPPart();
SOAPEnvelope envelope = sp.getEnvelope();
envelope.addTextNode("<!-- This is a comment -->");
boolean passbody = false;
for (Iterator i = envelope.getChildElements(); i.hasNext(); ) {
Node n = (Node) i.next();
if (n instanceof SOAPElement) {
SOAPElement se = (SOAPElement) n;
System.out.println("soap element = " + se.getNodeName());
if (se.getNamespaceURI().equals(SOAPConstants.URI_NS_SOAP_ENVELOPE)
&& se.getLocalName().equals("Body")) {
passbody = true;
}
}
if (n instanceof Text) {
Text t = (Text)n;
System.out.println("text = " + t.getValue());
if (t.getValue().equals("<!-- This is a comment -->")) {
assertEquals(true, passbody);
return;
}
}
}
throw new AssertionFailedError("Text is not added to expected position.");
}
private int getIteratorCount(java.util.Iterator i) {
int count = 0;
while (i.hasNext()) {
count++;
i.next();
}
return count;
}
}
| 7,273 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestMessageProperty2.java | package test.saaj;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.stream.StreamSource;
public class TestMessageProperty2 extends junit.framework.TestCase {
private static String GoodSoapMessage = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:tns=\"http://helloservice.org/wsdl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><tns:hello><String_1 xsi:type=\"xsd:string\"><Bozo></String_1></tns:hello></soap:Body></soap:Envelope>";
private SOAPMessage createTestMessage(String encoding, boolean xmlDecl) throws Exception {
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart sp = message.getSOAPPart();
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
ByteArrayInputStream bais =
new ByteArrayInputStream(GoodSoapMessage.getBytes(encoding));
StreamSource ssrc = new StreamSource(bais);
sp.setContent(ssrc);
message.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encoding);
message.setProperty(SOAPMessage.WRITE_XML_DECLARATION, xmlDecl ? "true" : "false");
return message;
}
private SOAPMessage createMessageFromInputStream(InputStream is) throws Exception {
MessageFactory mf = MessageFactory.newInstance();
return mf.createMessage(new MimeHeaders(), is);
}
public void testUTF8withXMLDecl() throws Exception {
SOAPMessage msg = createTestMessage("UTF-8", true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
String xml = new String(baos.toByteArray(),"UTF-8");
assertTrue(xml.indexOf("UTF-8") != -1);
assertTrue(xml.indexOf("<Bozo>") != -1);
}
public void testUTF16withXMLDecl() throws Exception {
SOAPMessage msg = createTestMessage("UTF-16", true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
String xml = new String(baos.toByteArray(),"UTF-16");
assertTrue(xml.indexOf("UTF-16") != -1);
assertTrue(xml.indexOf("<Bozo>") != -1);
}
}
| 7,274 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/saaj/TestText.java | package test.saaj;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Attr;
import org.w3c.dom.Text;
import org.w3c.dom.NodeList;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPPart;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.ByteArrayInputStream;
public class TestText extends junit.framework.TestCase {
// Test SAAJ addTextNode performance
public void testAddTextNode() throws Exception {
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
// Create the base element
Name bodyName = soapFactory.createName("VBGenReceiver", "xsi",
"http://www.w3.org/2001/XMLSchema-instance");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
// Create the MetaData Tag
Name name = soapFactory.createName("MetaData");
SOAPElement metaData = bodyElement.addChildElement(name);
//Create the SKey Tag
name = soapFactory.createName("SKey");
SOAPElement sKey = metaData.addChildElement(name);
sKey.addTextNode("SKEY001");
//Create Object Tag
name = soapFactory.createName("Object");
SOAPElement object = bodyElement.addChildElement(name);
//Create Book ID Tag
name = soapFactory.createName("BookID");
SOAPElement bookID = object.addChildElement(name);
bookID.addTextNode("BookID002");
//Create OrderID tag
name = soapFactory.createName("OrderID");
SOAPElement orderID = object.addChildElement(name);
orderID.addTextNode("OrderID003");
//create PurchaseID tage
name = soapFactory.createName("PurchaseID");
SOAPElement purchaseID = object.addChildElement(name);
purchaseID.addTextNode("PurchaseID005");
//create LanguageID Tag
name = soapFactory.createName("LanguageID");
SOAPElement languageID = object.addChildElement(name);
languageID.addTextNode("LanguageID004");
//create LanguageID Tag
name = soapFactory.createName("LanguageName");
SOAPElement languageName = object.addChildElement(name);
languageName.addTextNode("LanguageName006");
//create LanguageID Tag
name = soapFactory.createName("Title");
SOAPElement title = object.addChildElement(name);
title.addTextNode("Title007");
//create LanguageID Tag
name = soapFactory.createName("Author");
SOAPElement author = object.addChildElement(name);
author.addTextNode("Author008");
//create LanguageID Tag
name = soapFactory.createName("Format");
SOAPElement format = bodyElement.addChildElement(name);
//create LanguageID Tag
name = soapFactory.createName("Type");
SOAPElement formatType = format.addChildElement(name);
formatType.addTextNode("Type009");
//create LanguageID Tag
name = soapFactory.createName("Delivery");
SOAPElement delivery = bodyElement.addChildElement(name);
//create LanguageID Tag
name = soapFactory.createName("Name");
SOAPElement delName = delivery.addChildElement(name);
delName.addTextNode("Name010");
//create LanguageID Tag
name = soapFactory.createName("Address1");
SOAPElement address1 = delivery.addChildElement(name);
address1.addTextNode("Address1011");
//create LanguageID Tag
name = soapFactory.createName("Address2");
SOAPElement address2 = delivery.addChildElement(name);
address2.addTextNode("Address2012");
//create LanguageID Tag
name = soapFactory.createName("City");
SOAPElement city = delivery.addChildElement(name);
city.addTextNode("City013");
//create LanguageID Tag
name = soapFactory.createName("State");
SOAPElement state = delivery.addChildElement(name);
state.addTextNode("State014");
//create LanguageID Tag
name = soapFactory.createName("PostalCode");
SOAPElement postalCode = delivery.addChildElement(name);
postalCode.addTextNode("PostalCode015");
System.out.println("The message is lll:\n");
message.writeTo(System.out);
}
public void testTraverseDOM() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<book year=\"1992\">\n" +
" <title>Advanced Programming in the Unix environment</title>\n" +
" <author><last>Stevens</last><first>W.</first></author>\n" +
" <publisher>Addison-Wesley</publisher>\n" +
" <price>65.95</price>\n" +
"</book>\n" +
"";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document payload = builder.parse(new ByteArrayInputStream(xml.getBytes()));
MessageFactory soapMsgFactory = MessageFactory.newInstance();
SOAPMessage soapMsg = soapMsgFactory.createMessage();
SOAPPart soapPart = soapMsg.getSOAPPart();
SOAPEnvelope soapEnv = soapPart.getEnvelope();
SOAPBody soapBody = soapEnv.getBody();
soapBody.addDocument(payload);
System.out.println("***************");
soapMsg.writeTo(System.out);
processNode(soapPart);
}
private void processNode(Node currentNode) {
switch (currentNode.getNodeType()) {
// process a Document node
case Node.DOCUMENT_NODE:
Document doc = (Document) currentNode;
System.out.println("Document node: " + doc.getNodeName() +
"\nRoot element: " +
doc.getDocumentElement().getNodeName());
processChildNodes(doc.getChildNodes());
break;
// process an Element node
case Node.ELEMENT_NODE:
System.out.println("\nElement node: " +
currentNode.getNodeName());
NamedNodeMap attributeNodes =
currentNode.getAttributes();
for (int i = 0; i < attributeNodes.getLength(); i++) {
Attr attribute = (Attr) attributeNodes.item(i);
System.out.println("\tAttribute: " +
attribute.getNodeName() + " ; Value = " +
attribute.getNodeValue());
}
processChildNodes(currentNode.getChildNodes());
break;
// process a text node and a CDATA section
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
Text text = (Text) currentNode;
if (!text.getNodeValue().trim().equals(""))
System.out.println("\tText: " +
text.getNodeValue());
break;
}
}
private void processChildNodes(NodeList children) {
if (children.getLength() != 0)
for (int i = 0; i < children.getLength(); i++)
processNode(children.item(i));
}
}
| 7,275 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap/TestHeaderAttrs.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 test.soap;
import junit.framework.TestCase;
import org.apache.axis.AxisFault;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.transport.local.LocalResponder;
import org.apache.axis.transport.local.LocalTransport;
import java.util.Random;
/**
* A fairly comprehensive test of MustUnderstand/Actor combinations.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestHeaderAttrs extends TestCase {
static final String PROP_DOUBLEIT = "double_result";
static final String GOOD_HEADER_NS = "http://testMU/";
static final String GOOD_HEADER_NAME = "doubleIt";
static final String BAD_HEADER_NS = "http://incorrect-ns/";
static final String BAD_HEADER_NAME = "startThermonuclearWar";
static final String ACTOR = "http://some.actor/";
static SOAPHeaderElement goodHeader =
new SOAPHeaderElement(GOOD_HEADER_NS,
GOOD_HEADER_NAME);
static SOAPHeaderElement badHeader =
new SOAPHeaderElement(BAD_HEADER_NS,
BAD_HEADER_NAME);
private SimpleProvider provider = new SimpleProvider();
private AxisServer engine = new AxisServer(provider);
private LocalTransport localTransport = new LocalTransport(engine);
static final String localURL = "local:///testService";
// Which SOAP version are we using? Default to SOAP 1.1
protected SOAPConstants soapVersion = SOAPConstants.SOAP11_CONSTANTS;
/**
* Prep work. Make a server, tie a LocalTransport to it, and deploy
* our little test service therein.
*/
public void setUp() throws Exception {
engine.init();
localTransport.setUrl(localURL);
SOAPService service = new SOAPService(new TestHandler(),
new RPCProvider(),
null);
service.setOption("className", TestService.class.getName());
service.setOption("allowedMethods", "*");
provider.deployService("testService", service);
SimpleTargetedChain serverTransport =
new SimpleTargetedChain(null, null, new LocalResponder());
provider.deployTransport("local", serverTransport);
}
/**
* Test an unrecognized header with MustUnderstand="true"
*/
public void testMUBadHeader() throws Exception
{
// 1. MU header to unrecognized actor -> should work fine
badHeader.setActor(ACTOR);
badHeader.setMustUnderstand(true);
assertTrue("Bad result from test", runTest(badHeader, false));
// 2. MU header to NEXT -> should fail
badHeader.setActor(soapVersion.getNextRoleURI());
badHeader.setMustUnderstand(true);
// Test (should produce MU failure)
try {
runTest(badHeader, false);
} catch (Exception e) {
assertTrue("Non AxisFault Exception : " + e,
e instanceof AxisFault);
AxisFault fault = (AxisFault)e;
assertEquals("Bad fault code!", soapVersion.getMustunderstandFaultQName(),
fault.getFaultCode());
return;
}
fail("Should have gotten mustUnderstand fault!");
}
/**
* Test an unrecognized header with MustUnderstand="false"
*/
public void testNonMUBadHeader() throws Exception
{
badHeader.setActor(soapVersion.getNextRoleURI());
badHeader.setMustUnderstand(false);
assertTrue("Non-MU bad header to next actor returned bad result!",
runTest(badHeader, false));
badHeader.setActor(ACTOR);
assertTrue("Non-MU bad header to unrecognized actor returned bad result!",
runTest(badHeader, false));
}
/**
* Test a recognized header (make sure it has the desired result)
*/
public void testGoodHeader() throws Exception
{
goodHeader.setActor(soapVersion.getNextRoleURI());
assertTrue("Good header with next actor returned bad result!",
runTest(goodHeader, true));
}
/**
* Test a recognized header with a particular actor attribute
*/
public void testGoodHeaderWithActors() throws Exception
{
// 1. Good header to unrecognized actor -> should be ignored, and
// we should get a non-doubled result
goodHeader.setActor(ACTOR);
assertTrue("Good header with unrecognized actor returned bad result!",
runTest(goodHeader, false));
// Now tell the engine to recognize the ACTOR value
engine.addActorURI(ACTOR);
// 2. Good header should now be processed and return doubled result
assertTrue("Good header with recognized actor returned bad result!",
runTest(goodHeader, true));
engine.removeActorURI(ACTOR);
}
/**
* Call the service with a random string. Returns true if the result
* is the length of the string (doubled if the doubled arg is true).
*/
public boolean runTest(SOAPHeaderElement header,
boolean doubled) throws Exception
{
Call call = new Call(new Service());
call.setSOAPVersion(soapVersion);
call.setTransport(localTransport);
call.addHeader(header);
String str = "a";
int maxChars = new Random().nextInt(50);
for (int i = 0; i < maxChars; i++) {
str += "a";
}
Integer i = (Integer)call.invoke("countChars", new Object [] { str });
int desiredResult = str.length();
if (doubled) desiredResult = desiredResult * 2;
return (i.intValue() == desiredResult);
}
}
| 7,276 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap/TestHandler.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 test.soap;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
/**
* This is a test Handler which interacts with the TestService below in
* order to test header processing. If a particular header appears in
* the message, we mark the MessageContext so the TestService knows to
* double its results (which is a detectable way of confirming header
* processing on the client side).
*/
public class TestHandler extends BasicHandler {
public void invoke(MessageContext msgContext) throws AxisFault {
SOAPEnvelope env = msgContext.getRequestMessage().getSOAPEnvelope();
if (env.getHeaderByName(TestHeaderAttrs.GOOD_HEADER_NS,
TestHeaderAttrs.GOOD_HEADER_NAME) != null) {
// Just the header's presence is enough - mark the property
// so it can be picked up by the service (see below)
msgContext.setProperty(TestHeaderAttrs.PROP_DOUBLEIT, Boolean.TRUE);
}
if (env.getHeaderByName(TestOnFaultHeaders.TRIGGER_NS,
TestOnFaultHeaders.TRIGGER_NAME) != null) {
// Fault trigger header is there, so throw an Exception
throw new AxisFault("triggered exception");
}
}
public void onFault(MessageContext msgContext) {
try {
SOAPEnvelope env = msgContext.getResponseMessage().getSOAPEnvelope();
SOAPHeaderElement header = new SOAPHeaderElement("ns", "local", "val");
env.addHeader(header);
} catch (Exception e) {
throw new RuntimeException("Exception during onFault processing");
}
}
}
| 7,277 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap/TestOnFaultHeaders.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 test.soap;
import junit.framework.TestCase;
import org.apache.axis.SimpleChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import java.util.Vector;
/**
* Confirm OnFault() header processing + additions work right.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestOnFaultHeaders extends TestCase {
public static String TRIGGER_NS = "http://trigger-fault";
public static String TRIGGER_NAME = "faultPlease";
public static String RESP_NAME = "okHeresYourFault";
private SimpleProvider provider = new SimpleProvider();
private AxisServer engine = new AxisServer(provider);
private LocalTransport localTransport = new LocalTransport(engine);
static final String localURL = "local:///testService";
public void setUp() throws Exception {
engine.init();
localTransport.setUrl(localURL);
SimpleChain chain = new SimpleChain();
chain.addHandler(new TestFaultHandler());
chain.addHandler(new TestHandler());
SOAPService service = new SOAPService(chain,
new RPCProvider(),
null);
service.setOption("className", TestService.class.getName());
service.setOption("allowedMethods", "*");
provider.deployService("testService", service);
}
/**
* Add a header which will trigger a fault in the TestHandler, and
* therefore trigger the onFault() in the TestFaultHandler. That should
* put a header in the outgoing message, which we check for when we get
* the fault.
*
* @throws Exception
*/
public void testOnFaultHeaders() throws Exception {
Call call = new Call(new Service());
call.setTransport(localTransport);
SOAPHeaderElement header = new SOAPHeaderElement(TRIGGER_NS,
TRIGGER_NAME,
"do it");
call.addHeader(header);
try {
call.invoke("countChars", new Object [] { "foo" });
} catch (Exception e) {
SOAPEnvelope env = call.getResponseMessage().getSOAPEnvelope();
Vector headers = env.getHeaders();
assertEquals("Wrong # of headers in fault!", 1, headers.size());
SOAPHeaderElement respHeader = (SOAPHeaderElement)headers.get(0);
assertEquals("Wrong namespace for header", TRIGGER_NS,
respHeader.getNamespaceURI());
assertEquals("Wrong localName for response header", RESP_NAME,
respHeader.getName());
return;
}
fail("We should have gotten a fault!");
}
}
| 7,278 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap/TestFaultHandler.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 test.soap;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
/**
* This is a test Handler which interacts with the TestService below in
* order to test header processing. This one runs before the TestHandler,
* so when the TestHandler throws an Exception (triggered by a particular
* header being sent from TestOnFaultHeaders), the onFault() method gets
* called. In there, we get the response message and add a header to it.
* This header gets picked up by the client, who checks that it looks right
* and has successfully propagated from here to the top of the call stack.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestFaultHandler extends BasicHandler {
public void invoke(MessageContext msgContext) throws AxisFault {
}
public void onFault(MessageContext msgContext) {
try {
SOAPEnvelope env = msgContext.getResponseMessage().getSOAPEnvelope();
SOAPHeaderElement header = new SOAPHeaderElement(
TestOnFaultHeaders.TRIGGER_NS,
TestOnFaultHeaders.RESP_NAME,
"here's the value"
);
env.addHeader(header);
} catch (Exception e) {
throw new RuntimeException("Exception during onFault processing");
}
}
}
| 7,279 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/soap/TestService.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 test.soap;
import org.apache.axis.MessageContext;
/**
* Trivial test service.
*/
public class TestService {
/**
* Calculate and return the length of the passed String. If a
* MessageContext property indicates that we've received a particular
* header, then double the result before returning it.
*/
public int countChars(String str)
{
int ret = str.length();
MessageContext mc = MessageContext.getCurrentContext();
if (mc.isPropertyTrue(TestHeaderAttrs.PROP_DOUBLEIT)) {
ret = ret * 2;
}
return ret;
}
}
| 7,280 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/concurrency/TestApplicationScope.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 test.concurrency;
import junit.framework.TestCase;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.BasicServerConfig;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import org.apache.commons.logging.Log;
/**
* Test the "application" scope option - lots of threads call the same service
* multiple times, and we confirm that only a single instance of the service
* object was created.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestApplicationScope extends TestCase {
protected static Log log =
LogFactory.getLog(TestApplicationScope.class.getName());
private BasicServerConfig config;
private AxisServer server;
private String SERVICE_NAME = "TestService";
protected void setUp() throws Exception {
config = new BasicServerConfig();
server = new AxisServer(config);
// Deploy a service which contains an option that we expect to be
// available by asking the MessageContext in the service method (see
// PropertyHandler.java).
RPCProvider provider = new RPCProvider();
SOAPService service = new SOAPService(provider);
service.setName(SERVICE_NAME);
service.setOption("className", TestService.class.getName());
service.setOption("scope", "application");
service.setOption("allowedMethods", "*");
config.deployService(SERVICE_NAME, service);
}
public class TestRunnable implements Runnable {
private int reps;
public TestRunnable(int reps) {
this.reps = reps;
}
public void run() {
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService(SERVICE_NAME);
Call call = new Call(new Service());
call.setTransport(transport);
for (int i = 0; i < reps; i++) {
try {
String ret = (String)call.invoke("hello", null);
if (ret == null) {
MessageContext msgContext = call.getMessageContext();
String respStr = msgContext.getResponseMessage().getSOAPPartAsString();
String reqStr = msgContext.getRequestMessage().getSOAPPartAsString();
String nullStr = "Got null response! Request message:\r\n" + reqStr + "\r\n\r\n" +
"Response message:\r\n" + respStr;
log.fatal(nullStr);
setError(new Exception(nullStr));
} else if (!ret.equals(TestService.MESSAGE)) {
setError(new Exception("Messages didn't match (got '" +
ret +
"' wanted '" +
TestService.MESSAGE +
"'!"));
return;
}
} catch (AxisFault axisFault) {
setError(axisFault);
return;
}
}
}
}
private Exception error = null;
synchronized void setError(Exception e) {
if (error == null) {
error = e;
}
}
public void testApplicationScope() throws Exception {
int threads = 50;
int reps = 10;
ThreadGroup group = new ThreadGroup("TestThreads");
for (int i = 0; i < threads; i++) {
TestRunnable tr = new TestRunnable(reps);
Thread thread = new Thread(group, tr, "TestThread #" + i);
thread.start();
}
while (group.activeCount() > 0 && error == null) {
Thread.sleep(100);
}
if (error != null) {
throw error;
}
}
}
| 7,281 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/concurrency/TestService.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 test.concurrency;
/**
* An Axis service to test application scope. There should be exactly one
* instance of this class, if we end up with more then application scope
* isn't working correctly.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestService {
private static Object lock = new Object();
private static TestService singleton = null;
public static final String MESSAGE = "Hi there, come here often?";
public TestService() throws Exception {
synchronized (lock) {
if (singleton != null) {
// We're not the first/only one, so throw an Exception!
throw new Exception("Multiple instances of TestService created!");
}
singleton = this;
}
}
public String hello() {
return MESSAGE;
}
}
| 7,282 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/components/TestUUID.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.
*/
/**
*
* UUIDGen adopted from the juddi project
* (http://sourceforge.net/projects/juddi/)
*
*/
package test.components;
import junit.framework.TestCase;
import org.apache.axis.components.uuid.FastUUIDGen;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
public class TestUUID extends TestCase {
public void testUUID() {
long startTime = 0;
long endTime = 0;
UUIDGen uuidgen = null;
uuidgen = UUIDGenFactory.getUUIDGen();
startTime = System.currentTimeMillis();
for (int i = 1; i <= 10; ++i) {
String u = uuidgen.nextUUID();
System.out.println(i + ": " + u);
}
endTime = System.currentTimeMillis();
System.out.println("UUIDGen took " + (endTime - startTime) + " milliseconds");
}
public void testSequence() {
String current = null;
String prev = null;
FastUUIDGen g = new FastUUIDGen();
for (int i=0;i<1000;i++) {
current = g.nextUUID();
if (current.equals(prev)) {
fail("same uuid generated: " + current + " " + prev);
}
prev = current;
}
}
}
| 7,283 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/inheritance/Child.java | package test.inheritance;
public class Child extends Parent {
public static final String HELLO_MSG = "Hello from the Child class";
public static final String OVERLOAD_MSG = "The Child got ";
public String normal()
{
return HELLO_MSG;
}
public String overloaded(int i)
{
return OVERLOAD_MSG + i;
}
}
| 7,284 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/inheritance/Parent.java | package test.inheritance;
public class Parent {
public static final String HELLO_MSG = "Hello from the Parent class!";
public static final String OVERLOAD_MSG = "The Parent got ";
public String inherited()
{
return HELLO_MSG;
}
public String overloaded(String param)
{
return OVERLOAD_MSG + param;
}
}
| 7,285 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/inheritance/TestInheritance.java | package test.inheritance;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
public class TestInheritance extends TestCase {
private AxisServer server;
private LocalTransport transport;
protected void setUp() throws Exception {
SimpleProvider config = new SimpleProvider();
SOAPService service = new SOAPService(new RPCProvider());
service.setOption("className", "test.inheritance.Child");
service.setOption("allowedMethods", "*");
config.deployService("inheritanceTest", service);
server = new AxisServer(config);
transport = new LocalTransport(server);
transport.setRemoteService("inheritanceTest");
}
public void testInheritance() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
String ret = (String)call.invoke("inherited", null);
assertEquals("Inherited method returned bad result",
Parent.HELLO_MSG, ret);
ret = (String)call.invoke("normal", null);
assertEquals("Child method returned bad result",
Child.HELLO_MSG, ret);
ret = (String)call.invoke("overloaded", new Object [] { "test" });
assertTrue("Overloaded (String) method returned bad result",
ret.startsWith(Parent.OVERLOAD_MSG));
ret = (String)call.invoke("overloaded",
new Object [] { new Integer(5) });
assertTrue("Overloaded (int) method returned bad result",
ret.startsWith(Child.OVERLOAD_MSG));
}
}
| 7,286 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/properties/TestScopedProperties.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 test.properties;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.BasicClientConfig;
import org.apache.axis.configuration.BasicServerConfig;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.providers.java.RPCProvider;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
/**
* Test scoped properties. This test confirms that MessageContext.getProperty
* will correctly defer to a higher-level property scope (the Call on the
* client side, the SOAPService on the server side) to obtain values for
* properties that are not explicitly set in the MessageContext itself.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestScopedProperties extends TestCase {
public static final String PROP_NAME = "test.property";
public static final String CLIENT_VALUE = "client-side property value!";
public static final String SERVER_VALUE = "this is the server side value";
public static final String OVERRIDE_NAME = "override.property";
public static final String OVERRIDE_VALUE = "The REAL value!";
private SOAPService service;
private PropertyHandler serverHandler = new PropertyHandler();
private SimpleProvider config;
private AxisServer server;
/**
* Sets up the server side for this test. We deploy a service with
* a PropertyHandler as a request handler, and PropertyHandler as the
* backend class as well. We set an option on the service to a well-
* known value (PROP_NAME -> PROP_VALUE), and also set an option on
* the service (OVERRIDE_NAME) which we expect to be overriden by
* an explicit setting in the MessageContext.
*/
protected void setUp() throws Exception {
config = new BasicServerConfig();
server = new AxisServer(config);
// Deploy a service which contains an option that we expect to be
// available by asking the MessageContext in the service method (see
// PropertyHandler.java).
RPCProvider provider = new RPCProvider();
service = new SOAPService(serverHandler, provider, null);
service.setOption("className", PropertyHandler.class.getName());
service.setOption("allowedMethods", "*");
// Here's the interesting property.
service.setOption(PROP_NAME, SERVER_VALUE);
// Also set a property which we expect to be overriden by an explicit
// value in the MessageContext (see PropertyHandler.invoke()). We
// should never see this value.
service.setOption(OVERRIDE_NAME, SERVER_VALUE);
config.deployService("service", service);
}
/**
* Basic scoped properties test. Set up a client side service with a
* PropertyHandler as the request handler, then set a property on the
* Call which we expect to be available when the request handler queries
* the MessageContext. Call the backend service, and make sure the
* client handler, the server handler, and the result all agree on what
* the values should be.
*/
public void testScopedProperties() throws Exception {
BasicClientConfig config = new BasicClientConfig();
PropertyHandler clientHandler = new PropertyHandler();
SOAPService clientService = new SOAPService(clientHandler, null, null);
config.deployService("service", clientService);
Service s = new Service(config);
Call call = new Call(s);
// Set a property on the Call which we expect to be available via
// the MessageContext in the client-side handler.
call.setProperty(PROP_NAME, CLIENT_VALUE);
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService("service");
call.setTransport(transport);
// Make the call.
String result = (String)call.invoke("service",
"testScopedProperty",
new Object [] { });
assertEquals("Returned scoped property wasn't correct",
SERVER_VALUE,
result);
// Confirm that both the client and server side properties were
// correctly read.
assertEquals("Client-side scoped property wasn't correct",
CLIENT_VALUE,
clientHandler.getPropVal());
assertEquals("Server-side scoped property wasn't correct",
SERVER_VALUE,
serverHandler.getPropVal());
}
/**
* Test overriding a property that's set in the service with an explicit
* setting in the MessageContext. The server-side handler will set the
* OVERRIDDE_NAME property, and the "testOverrideProperty" method will
* return the value it sees, which should match.
*/
public void testMessageContextOverride() throws Exception {
// Only the server side matters on this one, so don't bother with
// special client config.
Call call = new Call(new Service());
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService("service");
call.setTransport(transport);
// Make the call.
String result = (String)call.invoke("service",
"testOverrideProperty",
new Object [] { });
assertEquals("Overriden property value didn't match",
OVERRIDE_VALUE,
result);
}
/**
* Test of three-level client scopes (MC -> service -> Call).
*
* Set a property on the Call, then try the invocation. The client-side
* handler should see the Call value. Then set the same property to a
* different value in the client-side service object, and confirm that
* when we invoke again we see the new value.
*/
public void testFullClientScopes() throws Exception {
Call call = new Call(new Service());
PropertyHandler clientHandler = new PropertyHandler();
SOAPService clientService = new SOAPService(clientHandler, null, null);
call.setSOAPService(clientService);
// Set a property on the Call which we expect to be available via
// the MessageContext in the client-side handler.
call.setProperty(PROP_NAME, CLIENT_VALUE);
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService("service");
call.setTransport(transport);
// First call should get the value from the Call object.
call.invoke("testOverrideProperty", new Object [] { });
assertEquals("Client-side scoped property from Call wasn't correct",
CLIENT_VALUE,
clientHandler.getPropVal());
// Now set the same option on the client service, which should
// take precedence over the value in the Call.
clientService.setOption(PROP_NAME, OVERRIDE_VALUE);
// Second call should now get the value from the client service.
call.invoke("testOverrideProperty", new Object [] { });
assertEquals("Client-side scoped property from service wasn't correct",
OVERRIDE_VALUE,
clientHandler.getPropVal());
}
}
| 7,287 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/properties/PropertyHandler.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 test.properties;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
/**
* Combination of two functions for this test.
*
* 1) When invoked as a Handler, save the value of the PROP_NAME property
* into a field so the test can look at it later. (used to test client-
* side)
*
* 2) When used as a back-end service, return the value of the PROP_NAME
* property (used to test server-side)
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class PropertyHandler extends BasicHandler {
private String propVal;
public void invoke(MessageContext msgContext) throws AxisFault {
// Get the "normal" property value, and save it away.
propVal = msgContext.getStrProp(TestScopedProperties.PROP_NAME);
// Set the "override" property directly in the MC.
msgContext.setProperty(TestScopedProperties.OVERRIDE_NAME,
TestScopedProperties.OVERRIDE_VALUE);
}
public String getPropVal() {
return propVal;
}
public void setPropVal(String propVal) {
this.propVal = propVal;
}
public String testScopedProperty() throws Exception {
MessageContext context = MessageContext.getCurrentContext();
String propVal = context.getStrProp(TestScopedProperties.PROP_NAME);
return propVal;
}
public String testOverrideProperty() throws Exception {
MessageContext context = MessageContext.getCurrentContext();
String propVal = context.getStrProp(TestScopedProperties.OVERRIDE_NAME);
return propVal;
}
}
| 7,288 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestUndeployment.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.Handler;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.deployment.wsdd.WSDDDeployment;
import org.apache.axis.deployment.wsdd.WSDDDocument;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.XMLUtils;
import java.io.InputStream;
import java.io.StringBufferInputStream;
/**
* Test WSDD undeployment.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestUndeployment extends TestCase
{
static final String HANDLER_NAME = "logger";
static final String PARAM_NAME = "testParam";
static final String PARAM_VAL = "testValue";
static final String deployDoc =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <handler type=\"java:org.apache.axis.handlers.LogHandler\" " +
"name=\"" + HANDLER_NAME + "\">\n" +
" <parameter name=\"" + PARAM_NAME +
"\" value=\"" + PARAM_VAL + "\"/>\n" +
" </handler>\n" +
" <handler type=\"logger\" name=\"other\"/>\n" +
"</deployment>";
static final String undeployDoc =
"<undeployment xmlns=\"http://xml.apache.org/axis/wsdd/\">\n" +
" <handler name=\"other\"/>\n" +
"</undeployment>";
/**
* Load up a server with a couple of handlers as spec'ed above,
* then undeploy one of them. Confirm that all looks reasonable
* throughout.
*/
public void testUndeployHandler() throws Exception
{
XMLStringProvider provider = new XMLStringProvider(deployDoc);
AxisServer server = new AxisServer(provider);
Handler handler = server.getHandler("other");
assertNotNull("Couldn't get handler", handler);
InputStream is = new StringBufferInputStream(undeployDoc);
WSDDDocument doc = new WSDDDocument(XMLUtils.newDocument(is));
WSDDDeployment dep = provider.getDeployment();
doc.deploy(dep);
server.refreshGlobalOptions();
handler = server.getHandler("other");
assertNull("Undeployed handler is still available", handler);
handler = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get handler (2nd time)", handler);
}
}
| 7,289 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestScopeOption.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.Handler;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
public class TestScopeOption extends TestCase
{
static final String HANDLER_NAME = "logger";
// Two-part WSDD, with a space for scope option in the middle
static final String doc1 =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <handler type=\"java:org.apache.axis.handlers.LogHandler\" " +
"name=\"" + HANDLER_NAME + "\" " +
"scope=\"";
static final String doc2 = "\"/>\n" +
"</deployment>";
/**
* Initialize an engine with a single handler with per-access scope.
* Then get the handler from the engine twice, and confirm that we get
* two different objects.
*
*/
public void testPerAccessScope() throws Exception
{
String doc = doc1 + "per-access" + doc2;
XMLStringProvider provider = new XMLStringProvider(doc);
AxisServer server = new AxisServer(provider);
Handler h1 = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get first logger handler from engine!", h1);
Handler h2 = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get second logger handler from engine!", h2);
assertTrue("Per-access Handlers were identical!", (h1 != h2));
}
/**
* Initialize an engine with a single handler of singleton scope.
* Then get the handler from the engine twice, and confirm that we
* get the same object both times.
*/
public void testSingletonScope() throws Exception
{
String doc = doc1 + "singleton" + doc2;
XMLStringProvider provider = new XMLStringProvider(doc);
AxisServer server = new AxisServer(provider);
Handler h1 = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get first logger handler from engine!", h1);
Handler h2 = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get second logger handler from engine!", h2);
assertTrue("Singleton Handlers were different!", (h1 == h2));
}
}
| 7,290 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestJAXRPCHandlerInfoChain.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 test.wsdd;
import javax.xml.namespace.QName;
import javax.xml.rpc.handler.Handler;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
/**
* Tests
* - if roles declared in handlerInfoChains are passed to the service method via
* the MessageContext
* - if parameters are passed to the handler
* - if the callback methods of an JAXRPC handler are called
*
* @author Thomas Bayer (bayer@oio.de)
*/
public class TestJAXRPCHandlerInfoChain extends TestCase implements Handler {
static final String SERVICE_NAME = "JAXRPCHandlerService";
static final String tns = "http://axis.apache.org/test";
static final String ROLE_ONE = "http://test.role.one";
static final String ROLE_TWO = "http://test.role.two";
AxisServer server;
LocalTransport transport;
static boolean roleOneFound = false;
static boolean roleTwoFound = false;
static boolean initCalled = false;
static boolean handleRequestCalled = false;
static boolean handleResponseCalled = false;
static boolean methodCalled = false;
static final String wsdd =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" "
+ "xmlns:java=\""
+ WSDDConstants.URI_WSDD_JAVA
+ "\">\n"
+ " <service name=\""
+ SERVICE_NAME
+ "\" "
+ "provider=\"java:RPC\">\n"
+ " <parameter name=\"className\" value=\"test.wsdd.TestJAXRPCHandlerInfoChain\"/>"
+ " <handlerInfoChain>"
+ " <handlerInfo classname=\"test.wsdd.TestJAXRPCHandlerInfoChain\">"
+ " <parameter name=\"param1\" value=\"hossa\"/>"
+ " </handlerInfo>"
+ " <role soapActorName=\"" + ROLE_ONE + "\"/>"
+ " <role soapActorName=\"" + ROLE_TWO + "\"/>"
+ " </handlerInfoChain>"
+ " </service>\n"
+ "</deployment>";
protected void setUp() throws Exception {
transport = new LocalTransport(new AxisServer(new XMLStringProvider(wsdd)));
transport.setRemoteService(SERVICE_NAME);
}
public void init(HandlerInfo handlerInfo) {
assertEquals("hossa", (String) handlerInfo.getHandlerConfig().get("param1"));
initCalled = true;
}
public void destroy() {
}
public boolean handleRequest(javax.xml.rpc.handler.MessageContext mc) {
String[] roles = ((SOAPMessageContext) mc).getRoles();
for (int i = 0; i < roles.length; i++) {
if (ROLE_ONE.equals(roles[i]))
roleOneFound = true;
if (ROLE_TWO.equals(roles[i]))
roleTwoFound = true;
}
handleRequestCalled = true;
return true;
}
public QName[] getHeaders() {
return null;
}
public boolean handleResponse(javax.xml.rpc.handler.MessageContext mc) {
handleResponseCalled = true;
return true;
}
public boolean handleFault(javax.xml.rpc.handler.MessageContext mc) {
return true;
}
public void doSomething() {
methodCalled = true;
}
public void testJAXRPCHandlerRoles() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
call.invoke("doSomething", null);
assertTrue( roleOneFound);
assertTrue( roleTwoFound);
assertTrue( initCalled);
assertTrue( handleRequestCalled);
assertTrue( handleResponseCalled);
assertTrue( methodCalled);
}
}
| 7,291 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/DummyHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package test.wsdd;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
public class DummyHandler extends BasicHandler {
public void invoke(MessageContext msgContext) throws AxisFault {
}
}
| 7,292 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestRoles.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
import java.util.List;
public class TestRoles extends TestCase
{
static final String GLOBAL_ROLE = "http://apache.org/globalRole";
static final String SERVICE_ROLE = "http://apache.org/serviceRole";
static final String SERVICE_NAME = "roleService";
static final String doc =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <globalConfiguration>\n" +
" <role>" + GLOBAL_ROLE + "</role>\n" +
" </globalConfiguration>\n" +
" <service name=\"" + SERVICE_NAME + "\">\n" +
" <parameter name=\"className\" value=\"test.wsdd.TestRoles\"/>\n" +
" <role>" + SERVICE_ROLE + "</role>" +
" </service>\n"+
"</deployment>";
/**
* Initialize an engine with a single handler with a parameter set, and
* another reference to that same handler with a different name.
*
* Make sure the param is set for both the original and the reference
* handler.
*
*/
public void testOptions() throws Exception
{
XMLStringProvider provider = new XMLStringProvider(doc);
AxisServer server = new AxisServer(provider);
SOAPService service = server.getService(SERVICE_NAME);
assertNotNull("Couldn't get service from engine!", service);
List roles = service.getRoles();
assertTrue("Service role not accessible",
roles.contains(SERVICE_ROLE));
assertTrue("Global role not accessible",
roles.contains(GLOBAL_ROLE));
roles = service.getServiceActors();
assertTrue("Service role not accessible from specific list",
roles.contains(SERVICE_ROLE));
assertFalse("Global role is accessible from specific list",
roles.contains(GLOBAL_ROLE));
}
}
| 7,293 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestAllowedMethods.java | /*
* Created by IntelliJ IDEA.
* User: gdaniels
* Date: Apr 2, 2002
* Time: 10:14:06 AM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
public class TestAllowedMethods extends TestCase {
static final String SERVICE_NAME = "AllowedMethodService";
private static final String MESSAGE = "Allowed method";
AxisServer server;
LocalTransport transport;
// Two-part WSDD, with a space for scope option in the middle
static final String doc1 =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <service name=\"" + SERVICE_NAME + "\" " +
"provider=\"java:RPC\">\n" +
" <parameter name=\"allowedMethods\" value=\"allowed\"/>" +
" <parameter name=\"className\" value=\"test.wsdd.TestAllowedMethods\"/>" +
" </service>\n" +
"</deployment>";
protected void setUp() throws Exception {
XMLStringProvider config = new XMLStringProvider(doc1);
server = new AxisServer(config);
transport = new LocalTransport(server);
transport.setRemoteService(SERVICE_NAME);
}
public void testAllowedMethods() throws Exception {
Call call = new Call(new Service());
call.setTransport(transport);
String ret = (String)call.invoke("allowed", null);
assertEquals("Return didn't match", MESSAGE, ret);
try {
ret = (String)call.invoke("disallowed", null);
} catch (Exception e) {
// Success, we shouldn't have been allowed to call that.
return;
}
fail("Successfully called disallowed method!");
}
public String disallowed() throws Exception {
return "You shouldn't have called me!";
}
public String allowed() {
return MESSAGE;
}
}
| 7,294 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestOptions.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.Handler;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
public class TestOptions extends TestCase
{
static final String HANDLER_NAME = "logger";
static final String PARAM_NAME = "testParam";
static final String PARAM_VAL = "testValue";
// Two-part WSDD, with a space for scope option in the middle
static final String doc =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <handler type=\"java:org.apache.axis.handlers.LogHandler\" " +
"name=\"" + HANDLER_NAME + "\">\n" +
" <parameter name=\"" + PARAM_NAME +
"\" value=\"" + PARAM_VAL + "\"/>\n" +
" </handler>\n" +
" <handler type=\"logger\" name=\"other\"/>\n" +
"</deployment>";
/**
* Initialize an engine with a single handler with a parameter set, and
* another reference to that same handler with a different name.
*
* Make sure the param is set for both the original and the reference
* handler.
*
*/
public void testOptions() throws Exception
{
XMLStringProvider provider = new XMLStringProvider(doc);
AxisServer server = new AxisServer(provider);
Handler h1 = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get logger handler from engine!", h1);
Object optVal = h1.getOption(PARAM_NAME);
assertNotNull("Option value was null!", optVal);
assertEquals("Option was not expected value", optVal, PARAM_VAL);
optVal = server.getOption("someOptionWhichIsntSet");
assertNull("Got value for bad option!", optVal);
Handler h2 = server.getHandler("other");
assertNotNull("Couldn't get second handler", h2);
optVal = h1.getOption(PARAM_NAME);
assertNotNull("Option value was null for 2nd handler!", optVal);
assertEquals("Option was not expected value for 2nd handler",
optVal, PARAM_VAL);
optVal = server.getOption("someOptionWhichIsntSet");
assertNull("Got value for bad option on 2nd handler!", optVal);
}
}
| 7,295 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestStructure.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.Chain;
import org.apache.axis.Handler;
import org.apache.axis.TargetedChain;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.server.AxisServer;
import java.io.InputStream;
/**
* Positive test of basic structure of a WSDD document
*/
public class TestStructure extends TestCase
{
static final String INPUT_FILE = "testStructure1.wsdd";
AxisServer server;
protected void setUp()
{
InputStream is = getClass().getResourceAsStream(INPUT_FILE);
FileProvider provider = new FileProvider(is);
server = new AxisServer(provider);
}
public void testChainAnonymousHandler() throws Exception
{
Chain chainOne = (Chain) server.getHandler("chain.one");
assertNotNull("chain.one should be non-null!", chainOne);
Handler chainOne_handlers[] = chainOne.getHandlers();
assertNotNull("chain.one/handlers should be non-null!",
chainOne_handlers);
assertTrue("chain.one should have exactly 1 handler!",
(1 == chainOne_handlers.length));
Handler chainOne_handler = chainOne_handlers[0];
assertNotNull("chain.one's handler should be non-null!",
chainOne_handler);
assertTrue("chain.one's handler should be a DummyHandler!",
(chainOne_handler instanceof DummyHandler));
}
public void testServiceBackReference() throws Exception
{
SOAPService serviceOne = (SOAPService)server.getService("service.one");
assertNotNull("service.one should be non-null!", serviceOne);
Chain serviceOne_responseFlow = (Chain)serviceOne.getResponseHandler();
assertNotNull("service.two/responseFlow should be non-null!",
serviceOne_responseFlow);
Handler serviceOne_responseFlow_handlers[] =
serviceOne_responseFlow.getHandlers();
assertNotNull("service.one/responseFlow/handlers should be non-null!",
serviceOne_responseFlow_handlers);
assertTrue("service.one should have exactly 1 handler!",
(1 == serviceOne_responseFlow_handlers.length));
Handler serviceOne_responseFlow_handler =
serviceOne_responseFlow_handlers[0];
assertNotNull("service.one's handler should be non-null!",
serviceOne_responseFlow_handler);
assertTrue("service.one's handler should be a RPCProvider!",
(serviceOne_responseFlow_handler instanceof
org.apache.axis.providers.java.RPCProvider));
Handler serviceOne_handler_byName = server.getHandler("BackReference");
assertTrue("service.one's 'BackReference' should be same as directly accessed 'BR'!",
(serviceOne_responseFlow_handler ==
serviceOne_handler_byName));
/*******************************************************
<service name="service.two" provider="java:MSG">
<requestFlow>
<handler type="BackReference"/>
</requestFlow>
</service>
******************************************************/
SOAPService serviceTwo = null;
serviceTwo = (SOAPService) server.getService("service.two");
assertTrue("service.two should be non-null!",
(null != serviceTwo));
Chain serviceTwo_requestFlow = (Chain) serviceTwo.getRequestHandler();
assertTrue("service.two/requestFlow should be non-null!",
(null != serviceTwo_requestFlow));
Handler serviceTwo_requestFlow_handlers[] =
serviceTwo_requestFlow.getHandlers();
assertTrue("service.two/requestFlow/handlers should be non-null!",
(null != serviceTwo_requestFlow_handlers));
assertTrue("service.two should have exactly 1 handler!",
(1 == serviceTwo_requestFlow_handlers.length));
Handler serviceTwo_requestFlow_handler =
serviceTwo_requestFlow_handlers[0];
assertTrue("service.two's handler should be non-null!",
(null != serviceTwo_requestFlow_handler));
assertTrue("service.two's handler should be a RPCProvider!",
(serviceTwo_requestFlow_handler instanceof
org.apache.axis.providers.java.RPCProvider));
assertTrue("service.two's 'BackReference' should be same as service.one's!",
(serviceTwo_requestFlow_handler ==
serviceOne_responseFlow_handler));
}
public void testTransportForwardReference()
throws Exception
{
TargetedChain transportOne =
(TargetedChain)server.getTransport("transport.one");
assertNotNull("transport.one should be non-null!", transportOne);
Chain transportOne_responseFlow =
(Chain)transportOne.getResponseHandler();
assertNotNull("transport.two/responseFlow should be non-null!",
transportOne_responseFlow);
Handler transportOne_responseFlow_handlers[] =
transportOne_responseFlow.getHandlers();
assertNotNull("transport.one/responseFlow/handlers should be non-null!",
transportOne_responseFlow_handlers);
assertTrue("transport.one should have exactly 1 handler!",
(1 == transportOne_responseFlow_handlers.length));
Handler transportOne_responseFlow_handler =
transportOne_responseFlow_handlers[0];
assertNotNull("transport.one's handler should be non-null!",
transportOne_responseFlow_handler);
assertTrue("transport.one's handler should be a URLMapper!",
(transportOne_responseFlow_handler instanceof
org.apache.axis.handlers.http.URLMapper));
Handler transportOne_handler_byName =
server.getHandler("ForwardReference");
assertTrue("transport.one's 'ForwardReference' should be same as directly accessed 'BR'!",
(transportOne_responseFlow_handler ==
transportOne_handler_byName));
TargetedChain transportTwo =
(TargetedChain)server.getTransport("transport.two");
assertNotNull("transport.two should be non-null!", transportTwo);
Chain transportTwo_requestFlow = (Chain) transportTwo.getRequestHandler();
assertNotNull("transport.two/requestFlow should be non-null!",
transportTwo_requestFlow);
Handler transportTwo_requestFlow_handlers[] =
transportTwo_requestFlow.getHandlers();
assertNotNull("transport.two/requestFlow/handlers should be non-null!",
transportTwo_requestFlow_handlers);
assertTrue("transport.two should have exactly 1 handler!",
(1 == transportTwo_requestFlow_handlers.length));
Handler transportTwo_requestFlow_handler = transportTwo_requestFlow_handlers[0];
assertNotNull("transport.two's handler should be non-null!",
transportTwo_requestFlow_handler);
assertTrue("transport.two's handler should be a URLMapper!",
(transportTwo_requestFlow_handler instanceof
org.apache.axis.handlers.http.URLMapper));
assertTrue("transport.two's 'ForwardReference' should be same as transport.one's!",
(transportTwo_requestFlow_handler == transportOne_responseFlow_handler));
}
}
| 7,296 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestGlobalConfiguration.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.server.AxisServer;
import java.util.List;
public class TestGlobalConfiguration extends TestCase
{
static final String PARAM_NAME = "testParam";
static final String PARAM_VAL = "testValue";
static final String ROLE = "http://test-role1";
static final String ROLE2 = "http://test-role2";
String doc =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\">\n" +
" <globalConfiguration>\n" +
" <parameter name=\"" + PARAM_NAME +
"\" value=\"" + PARAM_VAL + "\"/>\n" +
" <role>" + ROLE + "</role>\n" +
" <role>" + ROLE2 + "</role>\n" +
" </globalConfiguration>\n" +
"</deployment>";
public void testEngineProperties() throws Exception
{
XMLStringProvider provider = new XMLStringProvider(doc);
AxisServer server = new AxisServer(provider);
Object optVal = server.getOption(PARAM_NAME);
assertNotNull("Option value was null!", optVal);
assertEquals("Option was not expected value", optVal, PARAM_VAL);
optVal = server.getOption("someOptionWhichIsntSet");
assertNull("Got value for bad option!", optVal);
List roles = server.getActorURIs();
assertTrue("Engine roles did not contain " + ROLE,
roles.contains(ROLE));
assertTrue("Engine roles did not contain " + ROLE2,
roles.contains(ROLE2));
}
}
| 7,297 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestAdminService.java | package test.wsdd;
import junit.framework.TestCase;
import org.apache.axis.Handler;
import org.apache.axis.client.AdminClient;
import org.apache.axis.client.Call;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.local.LocalTransport;
import java.io.ByteArrayInputStream;
/**
* Test WSDD functions via the AdminService.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class TestAdminService extends TestCase
{
static final String HANDLER_NAME = "logger";
static final String PARAM_NAME = "testParam";
static final String PARAM_VAL = "testValue";
static final String deployDoc =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <handler type=\"java:org.apache.axis.handlers.LogHandler\" " +
"name=\"" + HANDLER_NAME + "\">\n" +
" <parameter name=\"" + PARAM_NAME +
"\" value=\"" + PARAM_VAL + "\"/>\n" +
" </handler>\n" +
" <handler type=\"logger\" name=\"other\"/>\n" +
" <service name=\"AdminService\" provider=\"java:MSG\">\n" +
" <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>" +
" <parameter name=\"methodName\" value=\"AdminService\"/>\n" +
" </service>\n" +
"</deployment>";
static final String undeployDoc =
"<undeployment xmlns=\"http://xml.apache.org/axis/wsdd/\">\n" +
" <handler name=\"other\"/>\n" +
"</undeployment>";
/**
* Load up a server with a couple of handlers as spec'ed above,
* then undeploy one of them. Confirm that all looks reasonable
* throughout.
*/
public void testUndeployHandlerViaAdmin() throws Exception
{
XMLStringProvider provider = new XMLStringProvider(deployDoc);
AxisServer server = new AxisServer(provider);
Handler handler = server.getHandler("other");
assertNotNull("Couldn't get handler", handler);
AdminClient client = new AdminClient(true);
Call call = client.getCall();
LocalTransport transport = new LocalTransport(server);
transport.setRemoteService("AdminService");
call.setTransport(transport);
client.process(new ByteArrayInputStream(undeployDoc.getBytes()));
server.refreshGlobalOptions();
handler = server.getHandler("other");
assertNull("Undeployed handler is still available", handler);
handler = server.getHandler(HANDLER_NAME);
assertNotNull("Couldn't get handler (2nd time)", handler);
}
}
| 7,298 |
0 | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test | Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestXSD.java | package test.wsdd;
import junit.framework.TestCase;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
/**
* Make sure that WSDD.xsd is up-to-date
*/
public class TestXSD extends TestCase {
static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
protected void setUp() throws Exception {
String schemaSource = "wsdd/WSDD.xsd";
// Set namespaceAware to true to get a DOM Level 2 tree with nodes
// containing namesapce information. This is necessary because the
// default value from JAXP 1.0 was defined to be false.
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
// Specify other factory configuration settings
File f = new File(schemaSource);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, f.toURL().toExternalForm());
}
public void testWSDD() throws Exception {
File f = new File(".");
recurse(f);
}
private void recurse(File f) throws Exception {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
recurse(files[i]);
}
} else if (f.getName().endsWith(".wsdd")) {
checkValidity(f);
}
}
private void checkValidity(File f) throws Exception {
System.out.println("========== Checking " + f.getAbsolutePath() + "=================");
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
assertTrue(doc != null);
}
}
| 7,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.