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/samples/echo-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples/echo/InteropTestSoapBindingImpl.java | /**
* InteropTestSoapBindingImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis Wsdl2java emitter.
*
* And then it was hand modified to echo
* the arguments back to the caller.
*/
package samples.echo;
import org.apache.axis.MessageContext;
public class InteropTestSoapBindingImpl implements samples.echo.InteropTestPortType {
public java.lang.String echoString(java.lang.String inputString) throws java.rmi.RemoteException {
MessageContext.getCurrentContext().setProperty(echoHeaderStringHandler.ECHOHEADER_STRING_ID, "header text");
return inputString;
}
public java.lang.String[] echoStringArray(java.lang.String[] inputStringArray) throws java.rmi.RemoteException {
return inputStringArray;
}
public int echoInteger(int inputInteger) throws java.rmi.RemoteException {
return inputInteger;
}
public int[] echoIntegerArray(int[] inputIntegerArray) throws java.rmi.RemoteException {
return inputIntegerArray;
}
public float echoFloat(float inputFloat) throws java.rmi.RemoteException {
return inputFloat;
}
public float[] echoFloatArray(float[] inputFloatArray) throws java.rmi.RemoteException {
return inputFloatArray;
}
public samples.echo.SOAPStruct echoStruct(samples.echo.SOAPStruct inputStruct) throws java.rmi.RemoteException {
return inputStruct;
}
public samples.echo.SOAPStruct[] echoStructArray(samples.echo.SOAPStruct[] inputStructArray) throws java.rmi.RemoteException {
return inputStructArray;
}
public void echoVoid() throws java.rmi.RemoteException {
}
public byte[] echoBase64(byte[] inputBase64) throws java.rmi.RemoteException {
return inputBase64;
}
public java.util.Calendar echoDate(java.util.Calendar inputDate) throws java.rmi.RemoteException {
return inputDate;
}
public byte[] echoHexBinary(byte[] inputHexBinary) throws java.rmi.RemoteException {
return inputHexBinary;
}
public java.math.BigDecimal echoDecimal(java.math.BigDecimal inputDecimal) throws java.rmi.RemoteException {
return inputDecimal;
}
public boolean echoBoolean(boolean inputBoolean) throws java.rmi.RemoteException {
return inputBoolean;
}
public void echoStructAsSimpleTypes(samples.echo.SOAPStruct inputStruct, javax.xml.rpc.holders.StringHolder outputString, javax.xml.rpc.holders.IntHolder outputInteger, javax.xml.rpc.holders.FloatHolder outputFloat) throws java.rmi.RemoteException {
outputString.value = inputStruct.getVarString() ;
outputInteger.value = inputStruct.getVarInt() ;
outputFloat.value = inputStruct.getVarFloat() ;
}
public samples.echo.SOAPStruct echoSimpleTypesAsStruct(java.lang.String inputString, int inputInteger, float inputFloat) throws java.rmi.RemoteException {
samples.echo.SOAPStruct s = new samples.echo.SOAPStruct();
s.setVarInt(inputInteger);
s.setVarString(inputString);
s.setVarFloat(inputFloat);
return s;
}
public java.lang.String[][] echo2DStringArray(java.lang.String[][] input2DStringArray) throws java.rmi.RemoteException {
return input2DStringArray;
}
public samples.echo.SOAPStructStruct echoNestedStruct(samples.echo.SOAPStructStruct inputStruct) throws java.rmi.RemoteException {
return inputStruct;
}
public samples.echo.SOAPArrayStruct echoNestedArray(samples.echo.SOAPArrayStruct inputStruct) throws java.rmi.RemoteException {
return inputStruct;
}
/**
* This method accepts a Map and echoes it back to the client.
*/
public java.util.HashMap echoMap(java.util.HashMap input) {
return input;
}
/**
* This method accepts an array of Maps and echoes it back to the client.
*/
public java.util.HashMap [] echoMapArray(java.util.HashMap[] input) {
return input;
}
/**
* This method accepts a Token (xsd:token) and echoes it back to the client.
*/
public org.apache.axis.types.Token echoToken(org.apache.axis.types.Token input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a NormalizedString (xsd:normalizedString) and echoes
* it back to the client.
*/
public org.apache.axis.types.NormalizedString echoNormalizedString(org.apache.axis.types.NormalizedString input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a UnsignedLong (xsd:unsignedLong) and echoes
* it back to the client.
*/
public org.apache.axis.types.UnsignedLong echoUnsignedLong(org.apache.axis.types.UnsignedLong input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a UnsignedInt (xsd:unsignedInt) and echoes
* it back to the client.
*/
public org.apache.axis.types.UnsignedInt echoUnsignedInt(org.apache.axis.types.UnsignedInt input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a UnsignedShort (xsd:unsignedShort) and echoes
* it back to the client.
*/
public org.apache.axis.types.UnsignedShort echoUnsignedShort(org.apache.axis.types.UnsignedShort input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a UnsignedByte (xsd:unsignedByte) and echoes
* it back to the client.
*/
public org.apache.axis.types.UnsignedByte echoUnsignedByte(org.apache.axis.types.UnsignedByte input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a NonNegativeInteger (xsd:nonNegativeInteger) and echoes
* it back to the client.
*/
public org.apache.axis.types.NonNegativeInteger echoNonNegativeInteger(org.apache.axis.types.NonNegativeInteger input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a PositiveInteger (xsd:positiveInteger) and echoes
* it back to the client.
*/
public org.apache.axis.types.PositiveInteger echoPositiveInteger(org.apache.axis.types.PositiveInteger input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a NonPositiveInteger (xsd:nonPositiveInteger) and echoes
* it back to the client.
*/
public org.apache.axis.types.NonPositiveInteger echoNonPositiveInteger(org.apache.axis.types.NonPositiveInteger input) throws java.rmi.RemoteException {
return input;
}
/**
* This method accepts a NegativeInteger (xsd:negativeInteger) and echoes
* it back to the client.
*/
public org.apache.axis.types.NegativeInteger echoNegativeInteger(org.apache.axis.types.NegativeInteger input) throws java.rmi.RemoteException {
return input;
}
}
| 7,000 |
0 | Create_ds/axis-axis1-java/samples/proxy-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/proxy-sample/src/test/java/test/functional/TestProxySample.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.functional;
import junit.framework.TestCase;
import samples.misc.TestClient;
/** Test the proxy sample code.
*/
public class TestProxySample extends TestCase {
public void test() throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"), "-d" };
TestClient.mainWithService(args, "ProxyService");
}
}
| 7,001 |
0 | Create_ds/axis-axis1-java/samples/proxy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/proxy-sample/src/main/java/samples/proxy/ProxyService.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 samples.proxy;
import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPEnvelope;
import org.w3c.dom.Document;
import samples.transport.tcp.TCPSender;
import samples.transport.tcp.TCPTransport;
/**
* Proxy sample. Relays message on to hardcoded URL.
* Soon, URL becomes configurable (via deployment?!);
* later, URL becomes specifiable in custom header.
*
* @author Rob Jellinghaus <robj@unrealities.com>
*/
public class ProxyService {
/**
* Process the given message, treating it as raw XML.
*/
public void proxyService(SOAPEnvelope env1, SOAPEnvelope env2)
throws AxisFault
{
try {
// Get the current Message Context
MessageContext msgContext = MessageContext.getCurrentContext();
// Look in the message context for our service
Handler self = msgContext.getService();
// what is our target URL?
String dest = (String)self.getOption("URL");
// use the server's client engine in case anything has
// been deployed to it
Service service = new Service();
service.setEngine( msgContext.getAxisEngine().getClientEngine() );
Call call = (Call) service.createCall();
SimpleTargetedChain c = new SimpleTargetedChain(new TCPSender());
// !!! FIXME
//service.getEngine().deployTransport("tcp", c);
// add TCP for proxy testing
call.addTransportPackage("samples.transport");
call.setTransportForProtocol("tcp", TCPTransport.class);
// NOW set the client's URL (since now the tcp handler exists)
call.setTargetEndpointAddress(new java.net.URL(dest));
call.setRequestMessage(msgContext.getRequestMessage());
call.invoke();
Message msg = call.getResponseMessage();
msgContext.setResponseMessage(msg);
}
catch( Exception exp ) {
throw AxisFault.makeFault( exp );
}
}
}
| 7,002 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/stock-sample/src/test/java/test/functional/TestStockSample.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.functional;
import junit.framework.TestCase;
import org.apache.axis.AxisFault;
import samples.stock.GetQuote;
import samples.stock.GetQuote2;
/** Test the stock sample code.
*/
public class TestStockSample extends TestCase {
public void testStockJWS () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser1", "-wpass1", "XXX", "-saxis/StockQuoteService.jws" };
float val = new GetQuote().getQuote(args);
assertEquals("TestStockSample.doTestStockJWS(): stock price should be 66.25", val, 66.25, 0.01);
}
public void testStockJWSInvalidURL() throws Exception {
// This should FAIL
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser1", "-wpass1", "XXX", "-sjws/StockQuoteService.jws" };
try {
new GetQuote().getQuote(args);
} catch (AxisFault e) {
// Don't print stack trace unless there is an error
// e.printStackTrace();
return;
}
assertNull("-sjws/AltStockQuoteService.jws did not fail as expected.");
}
public void testStockJava() throws Exception {
String[] args = { "XXX" };
float val = new GetQuote2().getQuote(args);
assertEquals("Stock price is not the expected 55.25 +/- 0.01", val, 55.25, 0.01);
}
public void testStock () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser1", "-wpass1", "XXX" };
float val = new GetQuote().getQuote(args);
assertEquals("Stock price is not the expected 55.25 +/- 0.01", val, 55.25, 0.01);
}
public void testStockNoAction () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser1", "-wpass1", "XXX_noaction" };
float val = new GetQuote().getQuote(args);
assertEquals("Stock price is not the expected 55.25 +/- 0.01", val, 55.25, 0.01);
}
}
| 7,003 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/GetInfo.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 samples.stock ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
/**
*
* @author Doug Davis (dug@us.ibm.com.com)
*/
public class GetInfo {
public static void main(String args[]) {
try {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null || args.length % 2 != 0 ) {
System.err.println( "Usage: GetInfo <symbol> <datatype>" );
System.exit(1);
}
String symbol = args[0] ;
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(opts.getURL()) );
call.setOperationName( new QName("urn:cominfo", "getInfo") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.addParameter( "info", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_STRING );
call.setUsername( opts.getUser() );
call.setPassword( opts.getPassword() );
String res = (String) call.invoke( new Object[] { args[0], args[1] } );
System.out.println( symbol + ": " + res );
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
| 7,004 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/GetQuote1.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 samples.stock ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
/**
* This version of the ever so popular GetQuote shows how to use the
* Axis client APIs with and without WSDL. The first flavor (getQuote1)
* will use WSDL to prefill all of the data about the remote service.
* The second one (getQuote2) will do it all manually. Either way the
* service is invoked it should produce the exact same request XML and
* of course same results.
*
* This sample supports the use of the standard options too (-p ...)
*
* @author Doug Davis (dug@us.ibm.com.com)
*/
public class GetQuote1 {
public String symbol ;
/**
* This will use the WSDL to prefill all of the info needed to make
* the call. All that's left is filling in the args to invoke().
*/
public float getQuote1(String args[]) throws Exception {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
/* Define the service QName and port QName */
/*******************************************/
QName servQN = new QName("urn:xmltoday-delayed-quotes","GetQuoteService");
QName portQN = new QName("urn:xmltoday-delayed-quotes","GetQuote");
/* Now use those QNames as pointers into the WSDL doc */
/******************************************************/
Service service = new Service( new URL("file:GetQuote.wsdl"), servQN );
Call call = (Call) service.createCall( portQN, "getQuote" );
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL( call.getTargetEndpointAddress() );
call.setTargetEndpointAddress( new URL(opts.getURL()) );
/* Define some service specific properties */
/*******************************************/
call.setUsername( opts.getUser() );
call.setPassword( opts.getPassword() );
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke( new Object[] { symbol = args[0] } );
return( ((Float) result).floatValue() );
}
/**
* This will do everything manually (ie. no WSDL).
*/
public float getQuote2(String args[]) throws Exception {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
/* Create default/empty Service and Call object */
/************************************************/
Service service = new Service();
Call call = (Call) service.createCall();
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL( "http://localhost:8080/axis/servlet/AxisServlet" );
/* Set all of the stuff that would normally come from WSDL */
/***********************************************************/
call.setTargetEndpointAddress( new URL(opts.getURL()) );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "getQuote" );
call.setEncodingStyle( "http://schemas.xmlsoap.org/soap/encoding/" );
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
/* Define some service specific properties */
/*******************************************/
call.setUsername( opts.getUser() );
call.setPassword( opts.getPassword() );
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke( new Object[] { symbol = args[0] } );
return( ((Float) result).floatValue() );
}
/**
* This will use the WSDL to prefill all of the info needed to make
* the call. All that's left is filling in the args to invoke().
*/
public float getQuote3(String args[]) throws Exception {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
/* Define the service QName and port QName */
/*******************************************/
QName servQN = new QName("urn:xmltoday-delayed-quotes","GetQuoteService");
QName portQN = new QName("urn:xmltoday-delayed-quotes","GetQuote");
/* Now use those QNames as pointers into the WSDL doc */
/******************************************************/
Service service = new Service( new URL("file:GetQuote.wsdl"), servQN );
Call call = (Call) service.createCall( portQN, "getQuote" );
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL( call.getTargetEndpointAddress() );
call.setTargetEndpointAddress( new URL(opts.getURL()) );
/* Define some service specific properties */
/*******************************************/
call.setUsername( opts.getUser() );
call.setPassword( opts.getPassword() );
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke( new Object[] { symbol = args[0] } );
result = call.invoke( new Object[] { symbol = args[0] } );
/* Reuse the call object to call the test method */
/*************************************************/
call.setOperation( portQN, "test" );
call.setReturnType( XMLType.XSD_STRING );
System.out.println( call.invoke(new Object[]{}) );
return( ((Float) result).floatValue() );
}
public static void main(String args[]) {
try {
String save_args[] = new String[args.length];
float val ;
GetQuote1 gq = new GetQuote1();
/* Call the getQuote() that uses the WDSL */
/******************************************/
System.out.println("Using WSDL");
System.arraycopy( args, 0, save_args, 0, args.length );
val = gq.getQuote1( args );
System.out.println( gq.symbol + ": " + val );
/* Call the getQuote() that does it all manually */
/*************************************************/
System.out.println("Manually");
System.arraycopy( save_args, 0, args, 0, args.length );
val = gq.getQuote2( args );
System.out.println( gq.symbol + ": " + val );
/* Call the getQuote() that uses Axis's generated WSDL */
/*******************************************************/
System.out.println("WSDL + Reuse Call");
System.arraycopy( save_args, 0, args, 0, args.length );
val = gq.getQuote3( args );
System.out.println( gq.symbol + ": " + val );
}
catch( Exception e ) {
e.printStackTrace();
}
}
};
| 7,005 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/GetQuote.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 samples.stock ;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
/**
*
* @author Doug Davis (dug@us.ibm.com.com)
*/
public class GetQuote {
public String symbol ;
// helper function; does all the real work
public float getQuote (String args[]) throws Exception {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
symbol = args[0] ;
// useful option for profiling - perhaps we should remove before
// shipping?
String countOption = opts.isValueSet('c');
int count=1;
if ( countOption != null) {
count=Integer.valueOf(countOption).intValue();
System.out.println("Iterating " + count + " times");
}
URL url = new URL(opts.getURL());
String user = opts.getUser();
String passwd = opts.getPassword();
Service service = new Service();
Float res = new Float(0.0F);
for (int i=0; i<count; i++) {
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( url );
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
// TESTING HACK BY ROBJ
if (symbol.equals("XXX_noaction")) {
symbol = "XXX";
}
call.setUsername( user );
call.setPassword( passwd );
Object ret = call.invoke( new Object[] {symbol} );
if (ret instanceof String) {
System.out.println("Received problem response from server: "+ret);
throw new AxisFault("", (String)ret, null, null);
}
res = (Float) ret;
}
return res.floatValue();
}
public static void main(String args[]) {
try {
GetQuote gq = new GetQuote();
float val = gq.getQuote(args);
// args array gets side-effected
System.out.println(gq.symbol + ": " + val);
}
catch( Exception e ) {
e.printStackTrace();
}
}
public GetQuote () {
};
};
| 7,006 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/ComInfoService.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 samples.stock ;
/**
*
* @author Doug Davis (dug@us.ibm.com)
*/
public class ComInfoService {
public String getInfo(String symbol, String dataType) throws Exception {
int i, j ;
String[] types = { "symbol", "name", "address" };
String[][] data = { {"IBM",
"International Business Machines",
"Armonk, NY" },
{"MACR",
"Macromedia",
"Newton, MA" },
{"CSCO",
"Cisco Systems",
"San Jose, CA" } };
for ( i = 0 ; i < types.length ; i++ )
if ( types[i].equals( dataType ) ) break ;
if ( i == types.length )
return( "Unknown dataType: " + dataType );
for ( j = 0 ; j < data.length ; j++ )
if ( data[j][0].equals( symbol ) ) break ;
if ( j == data.length )
return( "Unknown symbol: " + symbol );
return( data[j][i] );
}
}
| 7,007 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/StockQuoteService.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 samples.stock ;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.net.URL;
/**
* See \samples\stock\readme for info.
*
* @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
* @author Doug Davis (dug@us.ibm.com)
*/
public class StockQuoteService {
public String test() {
return( "Just a test" );
}
public float getQuote (String symbol) throws Exception {
// get a real (delayed by 20min) stockquote from
// http://services.xmethods.net/axis/. The IP addr
// below came from the host that the above form posts to ..
if ( symbol.equals("XXX") ) return( (float) 55.25 );
URL url = new URL( "http://services.xmethods.net/axis/getQuote?s="
+ symbol );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( url.toExternalForm() );
Element elem = doc.getDocumentElement();
NodeList list = elem.getElementsByTagName( "stock_quote" );
if ( list != null && list.getLength() != 0 ) {
elem = (Element) list.item(0);
list = elem.getElementsByTagName( "price" );
elem = (Element) list.item(0);
String quoteStr = elem.getAttribute("value");
try {
return Float.valueOf(quoteStr).floatValue();
} catch (NumberFormatException e1) {
// maybe its an int?
try {
return Integer.valueOf(quoteStr).intValue() * 1.0F;
} catch (NumberFormatException e2) {
return -1.0F;
}
}
}
return( 0 );
}
}
| 7,008 |
0 | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/stock-sample/src/main/java/samples/stock/GetQuote2.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 samples.stock ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import java.net.URL;
public class GetQuote2 {
public String symbol ;
/**
* This will use the WSDL to prefill all of the info needed to make
* the call. All that's left is filling in the args to invoke().
*/
public float getQuote(String args[]) throws Exception {
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
/* Define the service QName and port QName */
/*******************************************/
QName servQN = new QName("urn:xmltoday-delayed-quotes","GetQuoteService");
QName portQN = new QName("urn:xmltoday-delayed-quotes","GetQuoteJava");
/* Now use those QNames as pointers into the WSDL doc */
/******************************************************/
Service service = new Service( GetQuote2.class.getResource("GetQuote.wsdl"), servQN );
Call call = (Call) service.createCall( portQN, "getQuote" );
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL( call.getTargetEndpointAddress() );
call.setTargetEndpointAddress( new URL(opts.getURL()) );
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke( new Object[] { symbol = args[0] } );
return( ((Float) result).floatValue() );
}
public static void main(String args[]) {
try {
String save_args[] = new String[args.length];
float val ;
GetQuote2 gq = new GetQuote2();
/* Call the getQuote() that uses the WDSL */
/******************************************/
System.out.println("Using Java binding in WSDL");
System.arraycopy( args, 0, save_args, 0, args.length );
val = gq.getQuote( args );
System.out.println( gq.symbol + ": " + val );
}
catch( Exception e ) {
e.printStackTrace();
}
}
};
| 7,009 |
0 | Create_ds/axis-axis1-java/samples/jms-sample/src/test/java/samples | Create_ds/axis-axis1-java/samples/jms-sample/src/test/java/samples/jms/ActiveMQDaemon.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 samples.jms;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
public class ActiveMQDaemon implements Daemon {
private BrokerService broker;
public void init(DaemonContext context) throws DaemonInitException, Exception {
broker = BrokerFactory.createBroker("broker:(tcp://localhost:" + context.getArguments()[0] + ")?useJmx=false&persistent=false");
}
public void start() throws Exception {
broker.start();
}
public void stop() throws Exception {
broker.stop();
}
public void destroy() {
broker = null;
}
}
| 7,010 |
0 | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples/jms/JMSTest.java | /*
* Copyright 2001, 2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.jms;
import org.apache.axis.AxisFault;
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.encoding.XMLType;
import org.apache.axis.transport.jms.JMSConstants;
import org.apache.axis.transport.jms.JMSTransport;
import org.apache.axis.transport.jms.SimpleJMSListener;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.util.HashMap;
/** Tests the JMS transport. To run:
* java org.apache.axis.utils.Admin client client_deploy.xml
* java org.apache.axis.utils.Admin server deploy.xml
* java samples.transport.FileTest IBM
* java samples.transport.FileTest XXX
*
* JMSTest is a simple test driver for the JMS transport. It sets up a
* JMS listener, then calls a delayed quote service for each of the symbols
* specified on the command line.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class JMSTest {
static final String wsdd =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <transport name=\"JMSTransport\" pivot=\"java:org.apache.axis.transport.jms.JMSSender\"/>\n" +
" <service name=\"" + WSDDConstants.URI_WSDD + "\" provider=\"java:MSG\">\n" +
" <parameter name=\"allowedMethods\" value=\"AdminService\"/>\n" +
" <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>\n" +
" </service>\n" +
"</deployment>";
public static void main(String args[]) throws Exception {
Options opts = new Options( args );
// first check if we should print usage
if ((opts.isFlagSet('?') > 0) || (opts.isFlagSet('h') > 0))
printUsage();
HashMap connectorMap = SimpleJMSListener.createConnectorMap(opts);
HashMap cfMap = SimpleJMSListener.createCFMap(opts);
String destination = opts.isValueSet('d');
String username = opts.getUser();
String password = opts.getPassword();
// create the jms listener
SimpleJMSListener listener = new SimpleJMSListener(connectorMap,
cfMap,
destination,
username,
password,
false);
listener.start();
args = opts.getRemainingArgs();
if ( args == null || args.length == 0)
printUsage();
Service service = new Service(new XMLStringProvider(wsdd));
// create the transport
JMSTransport transport = new JMSTransport(connectorMap, cfMap);
// create a new Call object
Call call = (Call) service.createCall();
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
call.setTransport(transport);
// set additional params on the call if desired
//call.setUsername(username );
//call.setPassword(password );
//call.setProperty(JMSConstants.WAIT_FOR_RESPONSE, Boolean.FALSE);
//call.setProperty(JMSConstants.PRIORITY, new Integer(5));
//call.setProperty(JMSConstants.DELIVERY_MODE,
// new Integer(javax.jms.DeliveryMode.PERSISTENT));
//call.setProperty(JMSConstants.TIME_TO_LIVE, new Long(20000));
call.setProperty(JMSConstants.DESTINATION, destination);
call.setTimeout(new Integer(10000));
Float res = new Float(0.0F);
// invoke a call for each of the symbols and print out
for (int i = 0; i < args.length; i++)
{
try
{
res = (Float) call.invoke(new Object[] {args[i]});
System.out.println(args[i] + ": " + res);
}
catch(AxisFault af)
{
System.out.println(af.dumpToString());
System.exit(1);
}
}
// shutdown
listener.shutdown();
transport.shutdown();
}
public static void printUsage()
{
System.out.println("JMSTest: Tests JMS transport by obtaining stock quote");
System.out.println(" Usage: JMSTest <symbol 1> <symbol 2> <symbol 3> ...");
System.out.println(" Opts: -? this message");
System.out.println();
System.out.println(" -c connection factory properties filename");
System.out.println(" -d destination");
System.out.println(" -t topic [absence of -t indicates queue]");
System.out.println();
System.out.println(" -u username");
System.out.println(" -w password");
System.out.println();
System.out.println(" -s single-threaded listener");
System.out.println(" [absence of option => multithreaded]");
System.exit(1);
}
}
| 7,011 |
0 | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples/jms | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples/jms/dii/JMSURLTest.java | package samples.jms.dii;
import org.apache.axis.AxisFault;
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.encoding.XMLType;
import org.apache.axis.transport.jms.JMSTransport;
import org.apache.axis.transport.jms.SimpleJMSListener;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.util.HashMap;
/**
* Demonstrates use of a JMS URL endpoint address to drive the JMS transport.
*
* The JMS listener is an intermediary that receives the JMS service request and
* invokes the actual stock quote service over HTTP.
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSURLTest {
static final String wsdd =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <transport name=\"JMSTransport\" pivot=\"java:org.apache.axis.transport.jms.JMSSender\"/>\n" +
" <service name=\"" + WSDDConstants.URI_WSDD + "\" provider=\"java:MSG\">\n" +
" <parameter name=\"allowedMethods\" value=\"AdminService\"/>\n" +
" <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>\n" +
" </service>\n" +
"</deployment>";
// the JMS URL target endpoint address
static String sampleJmsUrl;
public static void main(String args[]) throws Exception {
Options opts = new Options( args );
// first check if we should print usage
if ((opts.isFlagSet('?') > 0) || (opts.isFlagSet('h') > 0))
printUsage();
String username = opts.getUser();
String password = opts.getPassword();
HashMap connectorMap = SimpleJMSListener.createConnectorMap(opts);
HashMap cfMap = SimpleJMSListener.createCFMap(opts);
String destination = opts.isValueSet('d');
sampleJmsUrl = opts.isValueSet('e');
if (sampleJmsUrl == null) {
printUsage();
}
// create the jms listener
SimpleJMSListener listener = new SimpleJMSListener(connectorMap,
cfMap,
destination,
username,
password,
false);
listener.start();
args = opts.getRemainingArgs();
if ( args == null || args.length == 0)
printUsage();
for (int i = 0; i < args.length; i++)
{
try
{
Float res = getQuote(args[i], username, password);
System.out.println(args[i] + ": " + res);
}
catch(AxisFault af)
{
System.out.println(af.dumpToString());
System.exit(1);
}
}
// shutdown
listener.shutdown();
// close all JMSConnectors whose configuration matches that of the JMS URL
// note: this is optional, as all connectors will be closed upon exit
JMSTransport.closeMatchingJMSConnectors(sampleJmsUrl, username, password);
System.exit(0);
}
public static Float getQuote(String ticker, String username, String password)
throws javax.xml.rpc.ServiceException, AxisFault
{
Float res = new Float(-1.0);
Service service = new Service(new XMLStringProvider(wsdd));
// create a new Call object
Call call = (Call) service.createCall();
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
try
{
java.net.URL jmsurl = new java.net.URL(sampleJmsUrl);
call.setTargetEndpointAddress(jmsurl);
// set additional params on the call if desired
call.setUsername(username);
call.setPassword(password);
call.setTimeout(new Integer(30000));
res = (Float) call.invoke(new Object[] {ticker});
}
catch (java.net.MalformedURLException e)
{
throw new AxisFault("Invalid JMS URL", e);
}
catch (java.rmi.RemoteException e)
{
throw new AxisFault("Failed in getQuote()", e);
}
return res;
}
public static void printUsage()
{
System.out.println("JMSURLTest: Tests JMS transport by obtaining stock quote");
System.out.println(" Usage: JMSURLTest <symbol 1> <symbol 2> <symbol 3> ...");
System.out.println(" Opts: -? this message");
System.out.println();
System.out.println(" -c connection factory properties filename");
System.out.println(" -d destination");
System.out.println(" -t topic [absence of -t indicates queue]");
System.out.println(" -e the JMS endpoint URL to use for the client");
System.out.println();
System.out.println(" -u username");
System.out.println(" -w password");
System.out.println();
System.out.println(" -s single-threaded listener");
System.out.println(" [absence of option => multithreaded]");
System.exit(1);
}
}
| 7,012 |
0 | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples/jms | Create_ds/axis-axis1-java/samples/jms-sample/src/main/java/samples/jms/stub/JMSURLStubTest.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 samples.jms.stub;
import samples.jms.stub.xmltoday_delayed_quotes.*;
import org.apache.axis.AxisFault;
import org.apache.axis.utils.Options;
import org.apache.axis.transport.jms.JMSTransport;
import org.apache.axis.transport.jms.SimpleJMSListener;
import java.util.HashMap;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;
/**
* Demonstrates use of wsdl2java-generated static stubs to invoke JMS endpoints.
*
* The JMS listener is an intermediary that receives the JMS service request and
* invokes the actual stock quote service over HTTP.
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSURLStubTest extends TestCase {
public JMSURLStubTest(String name) {
super(name);
}
public static Float getQuote(String endptAddr, String ticker) throws AxisFault {
float quote = -1.0F;
GetQuoteServiceLocator locator = new GetQuoteServiceLocator();
GetQuote getQuote;
if (endptAddr == null) {
endptAddr = locator.getGetQuoteAddress();
}
try {
getQuote = locator.getGetQuote(new URL(endptAddr));
}
catch (ServiceException e) {
throw new AxisFault("JAX-RPC ServiceException caught: ", e);
} catch (MalformedURLException e) {
throw new AxisFault("MalformedURLException caught: ", e);
}
assertTrue("getQuote is null", getQuote != null);
try {
quote = getQuote.getQuote(ticker);
System.out.println("quote: " + quote);
// close matching connectors
// note: this is optional, as all connectors will be closed upon exit
JMSTransport.closeMatchingJMSConnectors(endptAddr, null, null);
}
catch (RemoteException e) {
throw new AxisFault("Remote Exception caught: ", e);
}
return new Float(quote);
}
public static void printUsage()
{
System.out.println("JMSURLStubTest: Tests JMS transport by obtaining stock quote using wsdl2java-generated stub classes");
System.out.println(" Usage: JMSURLStubTest <symbol 1> <symbol 2> <symbol 3> ...");
System.out.println(" Opts: -? this message");
System.out.println();
System.out.println(" -c connection factory properties filename");
System.out.println(" -d destination");
System.out.println(" -t topic [absence of -t indicates queue]");
System.out.println(" -e the JMS endpoint URL to use for the client");
System.out.println();
System.out.println(" -u username");
System.out.println(" -w password");
System.out.println();
System.out.println(" -s single-threaded listener");
System.out.println(" [absence of option => multithreaded]");
System.exit(1);
}
/**
* Conn args are still required to set up the JMS listener
*/
public static void main(String[] args) throws Exception
{
Options opts = new Options( args );
// first check if we should print usage
if ((opts.isFlagSet('?') > 0) || (opts.isFlagSet('h') > 0))
printUsage();
String username = opts.getUser();
String password = opts.getPassword();
HashMap connectorMap = SimpleJMSListener.createConnectorMap(opts);
HashMap cfMap = SimpleJMSListener.createCFMap(opts);
String destination = opts.isValueSet('d');
String endptAddr = opts.isValueSet('e');
args = opts.getRemainingArgs();
if ( args == null || args.length == 0)
printUsage();
// create the jms listener
SimpleJMSListener listener = new SimpleJMSListener(connectorMap,
cfMap,
destination,
username,
password,
false);
listener.start();
JMSURLStubTest stubTest = new JMSURLStubTest("JMS URL static stub test");
for (int i = 0; i < args.length; i++)
{
try
{
Float quote = stubTest.getQuote(endptAddr, args[i]);
System.out.println(args[i] + ": " + quote);
}
catch(AxisFault af)
{
System.out.println(af.dumpToString());
System.exit(1);
}
}
listener.shutdown();
System.exit(0);
}
}
| 7,013 |
0 | Create_ds/axis-axis1-java/samples/misc-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/misc-sample/src/test/java/test/functional/TestMiscSample.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.functional;
import junit.framework.TestCase;
import samples.misc.TestClient;
/** Test the stock sample code.
*/
public class TestMiscSample extends TestCase {
public void test() throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"), "-d" };
TestClient.main(args);
}
}
| 7,014 |
0 | Create_ds/axis-axis1-java/samples/misc-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/misc-sample/src/main/java/samples/misc/TestClient.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 samples.misc ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.utils.Options;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
/**
*
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@allaire.com)
*/
public class TestClient {
public static String msg = "<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>IBM</symbol>\n" +
"</echo:Echo>\n" +
"</SOAP-ENV:Body></SOAP-ENV:Envelope>\n";
/**
* Send a hardcoded message to the server, and print the response.
*
* @param args the command line arguments (mainly for specifying URL)
* @param op an optional service argument, which will be used for
* specifying the transport-level service
*/
public static String doTest (String args[], String op) throws Exception {
Options opts = new Options( args );
String url = opts.getURL();
String action = "EchoService" ;
if (op != null) action = op;
args = opts.getRemainingArgs();
if ( args != null ) action = args[0];
InputStream input = new ByteArrayInputStream(msg.getBytes());
Service service = new Service();
Call call = (Call) service.createCall();
SOAPEnvelope env = new SOAPEnvelope(input);
call.setTargetEndpointAddress( new URL(url) );
if (action != null) {
call.setUseSOAPAction( true );
call.setSOAPActionURI( action );
}
System.out.println( "Request:\n" + msg );
env = call.invoke( env );
System.out.println( "Response:\n" + env.toString() );
return( env.toString() );
}
public static void main(String args[]) throws Exception{
doTest(args, null);
}
public static void mainWithService(String args[], String service) throws Exception{
doTest(args, service);
}
}
| 7,015 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/test/functional/TestTCPTransportSample.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.functional;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.EngineConfigurationFactoryFinder;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.logging.Log;
import samples.transport.tcp.AdminClient;
import samples.transport.tcp.GetQuote;
import samples.transport.tcp.TCPSender;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
/** Test the stock sample code.
*/
public class TestTCPTransportSample extends TestCase {
static Log log =
LogFactory.getLog(TestTCPTransportSample.class.getName());
private static String uri = "tcp://localhost:" + System.getProperty("test.functional.TCPListenerPort", "8088");
public TestTCPTransportSample(String name) {
super(name);
}
public void doTestDeploy () throws Exception {
String[] args = { "-l" + uri, "src/main/wsdd/deploy.wsdd" };
AdminClient.main(args);
}
public void doTestUndeploy () throws Exception {
String[] args = { "-l" + uri, "samples/stock/undeploy.wsdd" };
AdminClient.main(args);
}
public void doTestStock() throws Exception {
try {
log.info("Testing TCP stock service...");
GetQuote tester = new GetQuote();
tester.getQuote(new String [] { "-l" + uri, "XXX" });
String symbol = "XXX"; // args[0] ;
EngineConfiguration defaultConfig =
EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig();
SimpleProvider config = new SimpleProvider(defaultConfig);
SimpleTargetedChain c = new SimpleTargetedChain(new TCPSender());
config.deployTransport("tcp", c);
Service service = new Service(config);
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(uri) );
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
Object ret = call.invoke(
"urn:xmltoday-delayed-quotes", "getQuote",
new Object[] {symbol} );
if (ret instanceof Float) {
Float res = (Float) ret;
assertEquals("TestTCPTransportSample: stock price should be 55.25 +/- 0.000001", res.floatValue(), 55.25, 0.000001);
} else {
throw new AssertionFailedError("Bad return value from TCP stock test: "+ret);
}
}
// }
catch( Exception e ) {
e.printStackTrace();
throw new AssertionFailedError("Fault returned from TCP stock test: "+e);
}
}
public void testTCPTransportSample () throws Exception {
try {
log.info("Testing TCP transport.");
log.info("Testing deployment...");
doTestDeploy();
log.info("OK!");
log.info("Testing service...");
doTestStock();
log.info("OK!");
// Commented out for now, because namespaced-based dispatch for the
// TCPListener doesn't work yet. Possible solutions:
// 1. Deploy the AdminService at the WSDD namespace's name
// 2. Build another dispatch mechanism into the TCP transport
//
// log.info("Testing undeployment...");
// doTestUndeploy();
// log.info("OK!");
log.info("Test complete.");
}
catch( Exception e ) {
e.printStackTrace();
throw new AssertionFailedError("Fault returned from test: "+e);
}
}
public static void main(String [] args)
{
TestTCPTransportSample tester = new TestTCPTransportSample("TCP test");
try {
tester.testTCPTransportSample();
} catch (Exception e) {
}
}
}
| 7,016 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/test/functional/TestTransportSample.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.functional;
import junit.framework.TestCase;
import org.apache.axis.AxisFault;
import org.apache.axis.client.AdminClient;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import samples.transport.FileTest;
/** Test the stock sample code.
*/
public class TestTransportSample extends TestCase {
static Log log =
LogFactory.getLog(TestTransportSample.class.getName());
public TestTransportSample(String name) {
super(name);
}
public void doTestDeploy () throws Exception {
String[] args = { "-llocal:", "src/main/wsdd/deploy.wsdd" };
AdminClient.main(args);
}
/* NOT RECOMMENDED -- this calls out to xmltoday.com which is flaky.
Verify that it either succeeds, or that it produces a specific
failure. */
public void doTestIBM () throws Exception {
String[] args = { "IBM" };
try {
FileTest.main(args);
} catch (AxisFault e) {
String fault = e.getFaultString();
if (fault == null) throw e;
if (fault.indexOf("java.net.UnknownHost")<0) {
int start = fault.indexOf(": ");
log.info(fault.substring(start+2));
} else if (fault.equals("timeout")) {
log.info("timeout");
} else {
throw e;
}
}
}
public void doTestXXX () throws Exception {
String[] args = { "XXX" };
FileTest.main(args);
}
public void testService () throws Exception {
try {
log.info("Testing transport sample.");
log.info("Testing deployment...");
doTestDeploy();
// TODO: this test no longer works because it depends on a 3rd party service that is no longer available
// log.info("Testing service with symbol IBM...");
// doTestIBM();
log.info("Testing service with symbol XXX...");
doTestXXX();
log.info("Test complete.");
}
catch( Exception e ) {
e.printStackTrace();
throw new Exception("Fault returned from test: "+e);
}
}
/**
* bogus 'main'
*/
public static void main (String[] args) throws Exception {
new TestTransportSample("foo").testService();
}
}
| 7,017 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/test/java/samples/transport/tcp/TCPListenerDaemon.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 samples.transport.tcp;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
public class TCPListenerDaemon implements Daemon {
private TCPListener listener;
public void init(DaemonContext context) throws DaemonInitException, Exception {
listener = new TCPListener(context.getArguments());
}
public void start() throws Exception {
new Thread(listener).start();
}
public void stop() throws Exception {
listener.stop();
}
public void destroy() {
listener = null;
}
}
| 7,018 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/FileTransport.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 samples.transport;
import org.apache.axis.client.Transport;
/**
* A File Transport class.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@allaire.com)
*/
public class FileTransport extends Transport
{
public FileTransport()
{
transportName = "FileTransport";
}
}
| 7,019 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/FileReader.java | package samples.transport ;
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* Waits for the XML to appear in a file called xml#.req and writes
* the response in a file called xml#.res
*
* @author Doug Davis (dug@us.ibm.com)
*/
public class FileReader extends Thread {
static int nextNum = 1 ;
boolean pleaseStop = false ;
boolean halted = false ;
public void run() {
AxisServer server = new AxisServer();
server.init();
while( !pleaseStop ) {
try {
Thread.sleep( 100 );
File file = new File( "xml" + nextNum + ".req" );
if ( !file.exists() ) continue ;
// avoid race condition where file comes to exist but we were halted -- RobJ
if (pleaseStop) continue;
Thread.sleep( 100 ); // let the other side finish writing
FileInputStream fis = new FileInputStream( file );
int thisNum = nextNum++; // increment early to avoid infinite loops
Message msg = new Message( fis );
msg.getSOAPPartAsBytes();
fis.close();
file.delete();
MessageContext msgContext = new MessageContext(server);
msgContext.setRequestMessage( msg );
try {
server.invoke( msgContext );
msg = msgContext.getResponseMessage();
} catch (AxisFault af) {
msg = new Message(af);
msg.setMessageContext(msgContext);
} catch (Exception e) {
msg = new Message(new AxisFault(e.toString()));
msg.setMessageContext(msgContext);
}
byte[] buf = msg.getSOAPPartAsBytes();
FileOutputStream fos = new FileOutputStream( "xml" + thisNum + ".res" );
fos.write( buf );
fos.close();
}
catch( Exception e ) {
if ( !(e instanceof FileNotFoundException) )
e.printStackTrace();
}
}
halted = true;
System.out.println("FileReader halted.");
}
public void halt() {
pleaseStop = true ;
while (!halted) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
break;
}
}
}
}
| 7,020 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/FileSender.java | package samples.transport ;
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
/**
* Just write the XML to a file called xml#.req and wait for
* the result in a file called xml#.res
*
* Not thread-safe - just a dummy sample to show that we can indeed use
* something other than HTTP as the transport.
*
* @author Doug Davis (dug@us.ibm.com)
*/
public class FileSender extends BasicHandler {
static int nextNum = 1 ;
public void invoke(MessageContext msgContext) throws AxisFault {
Message msg = msgContext.getRequestMessage();
byte[] buf = (byte[]) msg.getSOAPPartAsBytes();
boolean timedOut = false;
try {
FileOutputStream fos = new FileOutputStream( "xml" + nextNum + ".req" );
fos.write( buf );
fos.close();
}
catch( Exception e ) {
e.printStackTrace();
}
long timeout = Long.MAX_VALUE;
if (msgContext.getTimeout()!=0)
timeout=(new Date()).getTime()+msgContext.getTimeout();
for (; timedOut == false;) {
try {
Thread.sleep( 100 );
File file = new File( "xml" + nextNum + ".res" );
if ((new Date().getTime())>=timeout)
timedOut = true;
if ( !file.exists() ) continue ;
Thread.sleep( 100 ); // let the other side finish writing
FileInputStream fis = new FileInputStream( "xml" + nextNum + ".res" );
msg = new Message( fis );
msg.getSOAPPartAsBytes(); // just flush the buffer
fis.close();
Thread.sleep( 100 );
(new File("xml" + nextNum + ".res")).delete();
msgContext.setResponseMessage( msg );
break ;
}
catch( Exception e ) {
// File not there - just loop
}
}
nextNum++ ;
if (timedOut)
throw new AxisFault("timeout");
}
}
| 7,021 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/FileTest.java | package samples.transport ;
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.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
/** Tests the simple File transport. To run:
* java org.apache.axis.utils.Admin client client_deploy.xml
* java org.apache.axis.utils.Admin server deploy.xml
* java samples.transport.FileTest IBM
* java samples.transport.FileTest XXX
*/
public class FileTest {
static final String wsdd =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <transport name=\"FileTransport\" pivot=\"java:samples.transport.FileSender\"/>\n" +
" <service name=\"" + WSDDConstants.URI_WSDD + "\" provider=\"java:MSG\">\n" +
" <parameter name=\"allowedMethods\" value=\"AdminService\"/>\n" +
" <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>\n" +
" </service>\n" +
"</deployment>";
public static void main(String args[]) throws Exception {
FileReader reader = new FileReader();
reader.setDaemon(true);
reader.start();
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
String symbol = args[0] ;
Service service = new Service(new XMLStringProvider(wsdd));
Call call = (Call) service.createCall();
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
call.setTransport( new FileTransport() );
call.setUsername(opts.getUser() );
call.setPassword(opts.getPassword() );
call.setTimeout(new Integer(10000));
Float res = new Float(0.0F);
res = (Float) call.invoke( new Object[] {symbol} );
System.out.println( symbol + ": " + res );
reader.halt();
}
}
| 7,022 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/TCPTransport.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 samples.transport.tcp;
import org.apache.axis.AxisEngine;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Transport;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import java.net.URL;
/**
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@allaire.com)
*/
public class TCPTransport extends Transport
{
static Log log =
LogFactory.getLog(TCPTransport.class.getName());
private String host;
private String port;
public TCPTransport () {
transportName = "tcp";
}
public TCPTransport (String host, String port) {
transportName = "tcp";
this.host = host;
this.port = port;
}
/**
* TCP properties
*/
static public String HOST = "tcp.host";
static public String PORT = "tcp.port";
/**
* Set up any transport-specific derived properties in the message context.
* @param context the context to set up
* @param message the client service instance
* @param engine the engine containing the registries
*/
public void setupMessageContextImpl(MessageContext mc,
Call call,
AxisEngine engine)
{
try {
String urlString = mc.getStrProp(MessageContext.TRANS_URL);
if (urlString != null) {
URL url = new URL(urlString);
host = url.getHost();
port = new Integer(url.getPort()).toString();
}
} catch (java.net.MalformedURLException e) {
// Do nothing here?
}
if (host != null) mc.setProperty(HOST, host);
if (port != null) mc.setProperty(PORT, port);
log.debug( "Port = " + mc.getStrProp(PORT));
log.debug( "Host = " + mc.getStrProp(HOST));
// kind of ugly... fake up a "http://host:port/" url to send down the chain
// ROBJ TODO: clean this up so we use TCP transport properties all the way down
// use serviceclient properties if any, otherwise use ours
/*
String url = "http://"+serv.get(HOST)+":"+serv.get(PORT);
log.debug( "TCPTransport set URL to '" + url + "'");
mc.setProperty(MessageContext.TRANS_URL, url);
*/
}
}
| 7,023 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/Handler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.transport.tcp;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* A stub URLStreamHandler, so the system will recognize our
* custom URLs as valid.
*
* @author Glen Daniels (gdaniels@apache.org)
*/
public class Handler extends URLStreamHandler
{
protected URLConnection openConnection(URL u)
{
return null;
}
}
| 7,024 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/GetQuote.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 samples.transport.tcp ;
import org.apache.axis.AxisFault;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.EngineConfigurationFactoryFinder;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
/**
*
* @author Doug Davis (dug@us.ibm.com.com)
*/
public class GetQuote {
public String symbol ;
// helper function; does all the real work
public float getQuote (String args[]) throws Exception {
Call.addTransportPackage("samples.transport");
Call.setTransportForProtocol("tcp", TCPTransport.class);
Options opts = new Options( args );
args = opts.getRemainingArgs();
if ( args == null ) {
System.err.println( "Usage: GetQuote <symbol>" );
System.exit(1);
}
String namespace = "urn:xmltoday-delayed-quotes";
symbol = args[0] ;
EngineConfiguration defaultConfig =
EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig();
SimpleProvider config = new SimpleProvider(defaultConfig);
SimpleTargetedChain c = new SimpleTargetedChain(new TCPSender());
config.deployTransport("tcp", c);
Service service = new Service(config);
Call call = (Call)service.createCall();
call.setTransport(new TCPTransport());
call.setTargetEndpointAddress( new URL(opts.getURL()) );
call.setOperationName( new QName("urn:xmltoday-delayed-quotes", "getQuote") );
call.addParameter( "symbol", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_FLOAT );
// TESTING HACK BY ROBJ
if (symbol.equals("XXX_noaction")) {
symbol = "XXX";
}
call.setUsername( opts.getUser() );
call.setPassword( opts.getPassword() );
// useful option for profiling - perhaps we should remove before
// shipping?
String countOption = opts.isValueSet('c');
int count=1;
if ( countOption != null) {
count=Integer.valueOf(countOption).intValue();
System.out.println("Iterating " + count + " times");
}
Float res = new Float(0.0F);
for (int i=0; i<count; i++) {
Object ret = call.invoke(new Object[] {symbol} );
if (ret instanceof String) {
System.out.println("Received problem response from server: "+ret);
throw new AxisFault("", (String)ret, null, null);
}
res = (Float) ret;
}
return res.floatValue();
}
public static void main(String args[]) {
try {
GetQuote gq = new GetQuote();
float val = gq.getQuote(args);
// args array gets side-effected
System.out.println(gq.symbol + ": " + val);
}
catch( Exception e ) {
e.printStackTrace();
}
}
public GetQuote () {
};
};
| 7,025 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/TCPListener.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 samples.transport.tcp;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Options;
import org.apache.commons.logging.Log;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
/**
* Listen for incoming socket connections on the specified socket. Take
* incoming messages and dispatch them.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
*/
public class TCPListener implements Runnable {
static Log log =
LogFactory.getLog(TCPSender.class.getName());
// These have default values.
private String transportName = "TCPTransport";
private static final String AXIS_ENGINE = "AxisEngine" ;
private int port;
private ServerSocket srvSocket;
private AxisEngine engine = null ;
// becomes true when we want to quit
private volatile boolean done = false;
static final String wsdd =
"<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
"xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
" <transport name=\"tcp\" pivot=\"java:samples.transport.tcp.TCPSender\"/>\n" +
" <service name=\"" + WSDDConstants.URI_WSDD + "\" provider=\"java:MSG\">\n" +
" <parameter name=\"allowedMethods\" value=\"AdminService\"/>\n" +
" <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>\n" +
" </service>\n" +
"</deployment>";
public static void main (String args[]) {
new TCPListener(args).run();
}
public TCPListener (String[] args) {
// look for -p, -d arguments
try {
Options options = new Options(args);
port = new URL(options.getURL()).getPort();
} catch (MalformedURLException ex) {
log.error("Hosed URL: "+ex);
System.exit(1);
}
try {
srvSocket = new ServerSocket(port);
} catch (IOException ex) {
log.error("Can't create server socket on port "+port);
System.exit(1);
}
log.info("TCPListener is listening on port "+port+".");
}
public void run () {
if (srvSocket == null) {
return;
}
Socket sock;
while (!done) {
try {
sock = srvSocket.accept();
log.info("TCPListener received new connection: "+sock);
new Thread(new SocketHandler(sock)).start();
} catch (IOException ex) {
/** stop complaining about this! it seems to happen on quit,
and is not worth mentioning. unless I am confused. -- RobJ
*/
log.debug("Got IOException on srvSocket.accept: "+ex);
}
}
}
public void stop() throws IOException {
done = true;
srvSocket.close();
}
public class SocketHandler implements Runnable {
private Socket socket;
public SocketHandler (Socket socket) {
this.socket = socket;
}
public void run () {
// get the input stream
if ( engine == null ) {
XMLStringProvider provider = new XMLStringProvider(wsdd);
engine = new AxisServer(provider);
engine.init();
}
/* Place the Request message in the MessagContext object - notice */
/* that we just leave it as a 'ServletRequest' object and let the */
/* Message processing routine convert it - we don't do it since we */
/* don't know how it's going to be used - perhaps it might not */
/* even need to be parsed. */
/*******************************************************************/
MessageContext msgContext = new MessageContext(engine);
InputStream inp;
try {
inp = socket.getInputStream();
} catch (IOException ex) {
log.error("Couldn't get input stream from "+socket);
return;
}
// ROBJ 911
// the plain ol' inputstream seems to hang in the SAX parse..... WHY?????
// because there is no content length!
//Message msg = new Message( nbbinp, "InputStream" );
Message msg = null;
try {
StringBuffer line = new StringBuffer();
int b = 0;
while ((b = inp.read()) != '\r') {
line.append((char)b);
}
// got to '\r', skip it and '\n'
if (inp.read() != '\n') {
log.error("Length line "+line+" was not terminated with \r\n");
return;
}
// TEST SUPPORT ONLY
// If the line says "ping", then respond "\n".
// If the line says "quit", then respond "\n" and exit.
if (line.toString().equals("ping")) {
socket.getOutputStream().write(new String("\n").getBytes());
return;
} else if (line.toString().equals("quit")) {
// peacefully die
socket.getOutputStream().write(new String("\n").getBytes());
socket.close();
// The following appears to deadlock. It will get cleaned
// up on exit anyway...
// srvSocket.close();
log.error("AxisListener quitting.");
System.exit(0);
}
// OK, assume it is content length
int len = Integer.parseInt(line.toString());
// read that many bytes into ByteArrayInputStream...
// experiment, doesn't work:
// NonBlockingBufferedInputStream nbbinp = new NonBlockingBufferedInputStream();
// nbbinp.setContentLength(len);
// nbbinp.setInputStream(inp);
// msg = new Message(nbbinp, "InputStream");
byte[] mBytes = new byte[len];
inp.read(mBytes);
msg = new Message(new ByteArrayInputStream(mBytes));
} catch (IOException ex) {
log.error("Couldn't read from socket input stream: "+ex);
return;
}
/* Set the request(incoming) message field in the context */
/**********************************************************/
msgContext.setRequestMessage( msg );
/* Set the Transport Specific Request/Response chains IDs */
/******************************************************/
msgContext.setTransportName(transportName);
try {
/* Invoke the Axis engine... */
/*****************************/
engine.invoke( msgContext );
}
catch( Exception e ) {
AxisFault fault = AxisFault.makeFault(e);
msgContext.setResponseMessage( new Message(fault) );
}
/* Send it back along the wire... */
/***********************************/
msg = msgContext.getResponseMessage();
String response = null;
if (msg == null) {
response="No data";
} else {
try {
response = (String) msg.getSOAPPartAsString();
} catch (AxisFault fault) {
msg = new Message(fault);
try {
response = (String)msg.getSOAPPartAsString();
} catch (AxisFault fault2) {
response = fault2.dumpToString();
}
}
}
try {
OutputStream buf = new BufferedOutputStream(socket.getOutputStream());
// this should probably specify UTF-8, but for now, for Java interop,
// use default encoding
buf.write(response.getBytes());
buf.close();
} catch (IOException ex) {
log.error("Can't write response to socket "+port+", response is: "+response);
}
}
}
}
| 7,026 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/AdminClient.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.transport.tcp ;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.configuration.EngineConfigurationFactoryFinder;
import org.apache.axis.configuration.SimpleProvider;
/**
* An admin client object, which will work with the TCP transport.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
* @author Glen Daniels (gdaniels@apache.org)
*/
public class AdminClient extends org.apache.axis.client.AdminClient {
public static void main(String args[]) {
Call.addTransportPackage("samples.transport");
Call.setTransportForProtocol("tcp", TCPTransport.class);
// Deploy the transport on top of the default client configuration.
EngineConfiguration defaultConfig =
EngineConfigurationFactoryFinder.newFactory().getClientEngineConfig();
SimpleProvider config = new SimpleProvider(defaultConfig);
SimpleTargetedChain c = new SimpleTargetedChain(new TCPSender());
config.deployTransport("tcp", c);
AdminClient.setDefaultConfiguration(config);
try {
org.apache.axis.client.AdminClient client =
new org.apache.axis.client.AdminClient(true);
System.out.println(client.process(args));
}
catch( Exception e ) {
System.err.println( e );
e.printStackTrace( System.err );
}
}
}
| 7,027 |
0 | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport | Create_ds/axis-axis1-java/samples/transport-sample/src/main/java/samples/transport/tcp/TCPSender.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 samples.transport.tcp;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.commons.logging.Log;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* This is meant to be used on a SOAP Client to call a SOAP server.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Doug Davis (dug@us.ibm.com)
*/
public class TCPSender extends BasicHandler {
static Log log =
LogFactory.getLog(TCPSender.class.getName());
public void invoke(MessageContext msgContext) throws AxisFault {
log.info( "Enter: TCPSender::invoke" );
/* Find the service we're invoking so we can grab it's options */
/***************************************************************/
String targetURL = null ;
Message outMsg = null ;
String reqEnv = null ;
targetURL = msgContext.getStrProp( MessageContext.TRANS_URL);
try {
String host = msgContext.getStrProp(TCPTransport.HOST);
int port = Integer.parseInt(msgContext.getStrProp(TCPTransport.PORT));
byte[] buf = new byte[4097];
int rc = 0 ;
Socket sock = null ;
sock = new Socket( host, port );
log.info( "Created an insecure HTTP connection");
reqEnv = (String) msgContext.getRequestMessage().getSOAPPartAsString();
//System.out.println("Msg: " + reqEnv);
BufferedInputStream inp = new BufferedInputStream(sock.getInputStream());
OutputStream out = sock.getOutputStream();
byte[] bytes = reqEnv.getBytes();
String length = "" + bytes.length + "\r\n";
out.write(length.getBytes());
out.write( bytes );
out.flush();
log.debug( "XML sent:" );
log.debug( "---------------------------------------------------");
log.debug( reqEnv );
if ( false ) {
// Special case - if the debug level is this high then something
// really bad must be going on - so just dump the input stream
// to stdout.
byte b;
while ( (b = (byte) inp.read()) != -1 )
System.err.print((char)b);
System.err.println("");
}
outMsg = new Message( inp );
if (log.isDebugEnabled()) {
log.debug( "\nNo Content-Length" );
log.debug( "\nXML received:" );
log.debug( "-----------------------------------------------");
log.debug( (String) outMsg.getSOAPPartAsString() );
}
msgContext.setResponseMessage( outMsg );
}
catch( Exception e ) {
log.error( e );
e.printStackTrace();
throw AxisFault.makeFault(e);
}
log.info( "Exit: TCPSender::invoke" );
}
};
| 7,028 |
0 | Create_ds/axis-axis1-java/tcpmon/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/tcpmon/src/main/java/org/apache/axis/utils/tcpmon.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.utils ;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicButtonListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* TCP monitor to log http messages and responses, both SOAP and plain HTTP.
* If you want to choose a different Swing look and feel, set the property
* tcpmon.laf to the classname of the new look and feel
* @author Doug Davis (dug@us.ibm.com)
* @author Steve Loughran
*/
public class tcpmon extends JFrame {
private JTabbedPane notebook = null ;
private static final int STATE_COLUMN = 0 ;
private static final int TIME_COLUMN = 1 ;
private static final int INHOST_COLUMN = 2 ;
private static final int OUTHOST_COLUMN = 3 ;
private static final int REQ_COLUMN = 4 ;
private static final String DEFAULT_HOST="127.0.0.1";
private static final int DEFAULT_PORT=8080;
/**
* this is the admin page
*/
class AdminPage extends JPanel {
public JRadioButton listenerButton, proxyButton ;
public JLabel hostLabel, tportLabel;
public NumberField port;
public HostnameField host;
public NumberField tport ;
public JTabbedPane noteb ;
public JCheckBox HTTPProxyBox ;
public HostnameField HTTPProxyHost;
public NumberField HTTPProxyPort ;
public JLabel HTTPProxyHostLabel, HTTPProxyPortLabel ;
public JLabel delayTimeLabel, delayBytesLabel;
public NumberField delayTime, delayBytes;
public JCheckBox delayBox;
public AdminPage( JTabbedPane notebook, String name ) {
JPanel mainPane = null ;
JButton addButton = null ;
this.setLayout( new BorderLayout() );
noteb = notebook ;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
mainPane = new JPanel(layout);
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER;
mainPane.add( new JLabel(getMessage("newTCP00", "Create a new TCP/IP Monitor...") + " "), c );
// Add some blank space
mainPane.add( Box.createRigidArea(new Dimension(1, 5)), c );
// The listener info
///////////////////////////////////////////////////////////////////
JPanel tmpPanel = new JPanel(new GridBagLayout());
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
tmpPanel.add( new JLabel(getMessage("listenPort00", "Listen Port #") + " "), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
tmpPanel.add( port = new NumberField(4), c );
mainPane.add( tmpPanel, c );
mainPane.add( Box.createRigidArea(new Dimension(1, 5)), c );
// Group for the radio buttons
ButtonGroup btns = new ButtonGroup();
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
mainPane.add( new JLabel(getMessage("actAs00", "Act as a...") ), c );
// Target Host/Port section
///////////////////////////////////////////////////////////////////
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
final String listener = getMessage("listener00", "Listener");
mainPane.add( listenerButton = new JRadioButton( listener ), c );
btns.add( listenerButton );
listenerButton.setSelected( true );
listenerButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (listener.equals(event.getActionCommand())) {
boolean state = listenerButton.isSelected();
tport.setEnabled( state );
host.setEnabled( state );
hostLabel.setForeground(state ? Color.black : Color.gray);
tportLabel.setForeground(state ? Color.black : Color.gray);
}
}
}
);
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
mainPane.add( Box.createRigidArea(new Dimension(25, 0)) );
mainPane.add( hostLabel = new JLabel(getMessage("targetHostname00", "Target Hostname") + " "), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
host = new HostnameField(30);
mainPane.add( host, c );
host.setText(DEFAULT_HOST);
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
mainPane.add( Box.createRigidArea(new Dimension(25, 0)) );
mainPane.add( tportLabel = new JLabel(getMessage("targetPort00", "Target Port #") + " "), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
tport = new NumberField(4);
mainPane.add( tport, c );
tport.setValue(DEFAULT_PORT);
// Act as proxy section
///////////////////////////////////////////////////////////////////
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
final String proxy = getMessage("proxy00", "Proxy");
mainPane.add( proxyButton = new JRadioButton( proxy ), c);
btns.add( proxyButton );
proxyButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (proxy.equals(event.getActionCommand())) {
boolean state = proxyButton.isSelected();
tport.setEnabled( !state );
host.setEnabled( !state );
hostLabel.setForeground(state ? Color.gray : Color.black);
tportLabel.setForeground(state ? Color.gray : Color.black);
}
}
}
);
// Spacer
/////////////////////////////////////////////////////////////////
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
mainPane.add( Box.createRigidArea(new Dimension(1, 10)), c );
// Options section
///////////////////////////////////////////////////////////////////
JPanel opts = new JPanel(new GridBagLayout());
opts.setBorder( new TitledBorder(getMessage("options00", "Options")) );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
mainPane.add( opts, c );
// HTTP Proxy Support section
///////////////////////////////////////////////////////////////////
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
final String proxySupport = getMessage("proxySupport00", "HTTP Proxy Support");
opts.add(HTTPProxyBox = new JCheckBox(proxySupport), c);
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
opts.add( HTTPProxyHostLabel = new JLabel(getMessage("hostname00", "Hostname") + " "), c );
HTTPProxyHostLabel.setForeground( Color.gray );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
opts.add( HTTPProxyHost = new HostnameField(30), c );
HTTPProxyHost.setEnabled( false );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
opts.add( HTTPProxyPortLabel = new JLabel(getMessage("port00", "Port #") + " "), c );
HTTPProxyPortLabel.setForeground( Color.gray );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
opts.add( HTTPProxyPort = new NumberField(4), c );
HTTPProxyPort.setEnabled( false );
HTTPProxyBox.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (proxySupport.equals(event.getActionCommand())) {
boolean b = HTTPProxyBox.isSelected();
Color color = b ? Color.black : Color.gray ;
HTTPProxyHost.setEnabled( b );
HTTPProxyPort.setEnabled( b );
HTTPProxyHostLabel.setForeground( color );
HTTPProxyPortLabel.setForeground( color );
}
}
}
);
// Set default proxy values...
String tmp = System.getProperty( "http.proxyHost" );
if ( tmp != null && tmp.equals("") ) {
tmp = null ;
}
HTTPProxyBox.setSelected( tmp != null );
HTTPProxyHost.setEnabled( tmp != null );
HTTPProxyPort.setEnabled( tmp != null );
HTTPProxyHostLabel.setForeground( tmp != null ? Color.black : Color.gray);
HTTPProxyPortLabel.setForeground( tmp != null ? Color.black : Color.gray);
if ( tmp != null ) {
HTTPProxyBox.setSelected( true );
HTTPProxyHost.setText( tmp );
tmp = System.getProperty( "http.proxyPort" );
if ( tmp != null && tmp.equals("") ) {
tmp = null ;
}
if ( tmp == null ) {
tmp = "80" ;
}
HTTPProxyPort.setText( tmp );
}
//add byte delay fields
opts.add(Box.createRigidArea(new Dimension(1, 10)), c);
c.anchor = GridBagConstraints.WEST;
c.gridwidth = GridBagConstraints.REMAINDER;
final String delaySupport = getMessage("delay00", "Simulate Slow Connection");
opts.add(delayBox = new JCheckBox(delaySupport), c);
//bytes per pause
c.anchor = GridBagConstraints.WEST;
c.gridwidth = 1;
delayBytesLabel=new JLabel(getMessage("delay01", "Bytes per Pause"));
opts.add(delayBytesLabel, c);
delayBytesLabel.setForeground(Color.gray);
c.anchor = GridBagConstraints.WEST;
c.gridwidth = GridBagConstraints.REMAINDER;
opts.add(delayBytes = new NumberField(6), c);
delayBytes.setEnabled(false);
//delay interval
c.anchor = GridBagConstraints.WEST;
c.gridwidth = 1;
delayTimeLabel = new JLabel(getMessage("delay02", "Delay in Milliseconds"));
opts.add(delayTimeLabel, c);
delayTimeLabel.setForeground(Color.gray);
c.anchor = GridBagConstraints.WEST;
c.gridwidth = GridBagConstraints.REMAINDER;
opts.add(delayTime = new NumberField(6), c);
delayTime.setEnabled(false);
//enabler callback
delayBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (delaySupport.equals(event.getActionCommand())) {
boolean b = delayBox.isSelected();
Color color = b ? Color.black : Color.gray;
delayBytes.setEnabled(b);
delayTime.setEnabled(b);
delayBytesLabel.setForeground(color);
delayTimeLabel.setForeground(color);
}
}
}
);
// Spacer
//////////////////////////////////////////////////////////////////
mainPane.add( Box.createRigidArea(new Dimension(1, 10)), c );
// ADD Button
///////////////////////////////////////////////////////////////////
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
final String add = getMessage("add00", "Add");
mainPane.add( addButton = new JButton( add ), c );
this.add( new JScrollPane( mainPane ), BorderLayout.CENTER );
// addButton.setEnabled( false );
addButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( add.equals(event.getActionCommand()) ) {
String text ;
Listener l = null ;
int lPort;
lPort=port.getValue(0);
if(lPort==0) {
//no port, button does nothing
return;
}
String tHost = host.getText();
int tPort = 0 ;
tPort=tport.getValue(0);
SlowLinkSimulator slowLink=null;
if(delayBox.isSelected()) {
int bytes= delayBytes.getValue(0);
int time = delayTime.getValue(0);
slowLink=new SlowLinkSimulator(bytes,time);
}
try {
l = new Listener( noteb, null, lPort, tHost, tPort,
proxyButton.isSelected(), slowLink);
} catch (Exception e){
e.printStackTrace();
}
// Pick-up the HTTP Proxy settings
///////////////////////////////////////////////////
text = HTTPProxyHost.getText();
if ( "".equals(text) ) {
text = null ;
}
l.HTTPProxyHost = text ;
text = HTTPProxyPort.getText();
int proxyPort=HTTPProxyPort.getValue(-1);
if(proxyPort!=-1) {
l.HTTPProxyPort = Integer.parseInt(text);
}
//reset the port
port.setText(null);
/* but not, any more, the target port and host
values
host.setText(null);
tport.setText(null);
*/
}
}
}
);
notebook.addTab( name, this );
notebook.repaint();
notebook.setSelectedIndex( notebook.getTabCount() - 1 );
}
}
/**
* wait for incoming connections, spawn a connection thread when
* stuff comes in.
*/
class SocketWaiter extends Thread {
ServerSocket sSocket = null ;
Listener listener ;
int port ;
boolean pleaseStop = false ;
public SocketWaiter(Listener l, int p) {
listener = l ;
port = p ;
start();
}
public void run() {
try {
listener.setLeft( new JLabel(getMessage("wait00", " Waiting for Connection...") ) );
listener.repaint();
sSocket = new ServerSocket( port );
for (; ; ) {
Socket inSocket = sSocket.accept();
if ( pleaseStop ) {
break ;
}
new Connection( listener, inSocket );
inSocket = null ;
}
} catch ( Exception exp ) {
if ( !"socket closed".equals(exp.getMessage()) ) {
JLabel tmp = new JLabel( exp.toString() );
tmp.setForeground( Color.red );
listener.setLeft( tmp );
listener.setRight( new JLabel("") );
listener.stop();
}
}
}
/**
* force a halt by connecting to self and then closing the server socket
*/
public void halt() {
try {
pleaseStop = true ;
new Socket( "127.0.0.1", port );
if ( sSocket != null ) {
sSocket.close();
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
/**
* class to simulate slow connections by slowing down the system
*/
static class SlowLinkSimulator {
private int delayBytes;
private int delayTime;
private int currentBytes;
private int totalBytes;
/**
* construct
* @param delayBytes bytes per delay; set to 0 for no delay
* @param delayTime delay time per delay in milliseconds
*/
public SlowLinkSimulator(int delayBytes, int delayTime) {
this.delayBytes = delayBytes;
this.delayTime = delayTime;
}
/**
* construct by copying delay bytes and time, but not current
* count of bytes
* @param that source of data
*/
public SlowLinkSimulator(SlowLinkSimulator that) {
this.delayBytes=that.delayBytes;
this.delayTime=that.delayTime;
}
/**
* how many bytes have gone past?
* @return
*/
public int getTotalBytes() {
return totalBytes;
}
/**
* log #of bytes pumped. Will pause when necessary. This method is not
* synchronized
* @param bytes
*/
public void pump(int bytes) {
totalBytes+=bytes;
if(delayBytes==0) {
//when not delaying, we are just a byte counter
return;
}
currentBytes += bytes;
if(currentBytes>delayBytes) {
//we have overshot. lets find out how far
int delaysize=currentBytes/delayBytes;
long delay=delaysize*(long)delayTime;
//move byte counter down to the remainder of bytes
currentBytes=currentBytes%delayBytes;
//now wait
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
; //ignore the exception
}
}
}
/**
* get the current byte count
* @return
*/
public int getCurrentBytes() {
return currentBytes;
}
/**
* set the current byte count
* @param currentBytes
*/
public void setCurrentBytes(int currentBytes) {
this.currentBytes = currentBytes;
}
}
/**
* this class handles the pumping of data from the incoming socket to the
* outgoing socket
*/
class SocketRR extends Thread {
Socket inSocket = null ;
Socket outSocket = null ;
JTextArea textArea ;
InputStream in = null ;
OutputStream out = null ;
boolean xmlFormat ;
boolean numericEnc ;
volatile boolean done = false ;
TableModel tmodel = null ;
int tableIndex = 0 ;
String type = null;
Connection myConnection = null;
SlowLinkSimulator slowLink;
public SocketRR(Connection c, Socket inputSocket, InputStream inputStream,
Socket outputSocket, OutputStream outputStream,
JTextArea _textArea, boolean format, boolean numeric,
TableModel tModel, int index, final String type, SlowLinkSimulator slowLink) {
inSocket = inputSocket ;
in = inputStream ;
outSocket = outputSocket ;
out = outputStream ;
textArea = _textArea ;
xmlFormat = format ;
numericEnc= numeric ;
tmodel = tModel ;
tableIndex = index ;
this.type = type;
myConnection = c;
this.slowLink= slowLink;
start();
}
public boolean isDone() {
return ( done );
}
public void run() {
try {
byte[] buffer = new byte[4096];
byte[] tmpbuffer = new byte[8192];
String message = null;
int saved = 0 ;
int len ;
int i1, i2 ;
int i ;
int reqSaved = 0 ;
int tabWidth = 3 ;
boolean atMargin = true ;
int thisIndent = -1,
nextIndent = -1,
previousIndent = -1;
//if ( inSocket != null ) inSocket.setSoTimeout( 10 );
//if ( outSocket != null ) outSocket.setSoTimeout( 10 );
if ( tmodel != null ) {
String tmpStr = (String) tmodel.getValueAt(tableIndex,
REQ_COLUMN);
if ( !"".equals(tmpStr) ) {
reqSaved = tmpStr.length();
}
}
a:
for ( ; ; ) {
if ( done ) {
break;
}
//try{
//len = in.available();
//}catch(Exception e){len=0;}
len = buffer.length ;
// Used to be 1, but if we block it doesn't matter
// however 1 will break with some servers, including apache
if ( len == 0 ) {
len = buffer.length;
}
if ( saved + len > buffer.length) {
len = buffer.length - saved ;
}
int len1 = 0;
while ( len1 == 0 ) {
try {
len1 = in.read(buffer, saved, len);
}
catch ( Exception ex ) {
if ( done && saved == 0 ) {
break a;
}
len1 = -1;
break;
}
}
len = len1;
if ( len == -1 && saved == 0 ) {
break ;
}
if ( len == -1) {
done = true;
}
// No matter how we may (or may not) format it, send it
// on unformatted - we don't want to mess with how its
// sent to the other side, just how its displayed
if ( out != null && len > 0 ) {
slowLink.pump(len);
out.write( buffer, saved, len );
}
if ( tmodel != null && reqSaved < 50 ) {
String old = (String) tmodel.getValueAt( tableIndex,
REQ_COLUMN);
old = old + new String(buffer, saved, len);
if ( old.length() > 50 ) {
old = old.substring(0, 50);
}
reqSaved = old.length();
if ( (i = old.indexOf('\n')) > 0 ) {
old = old.substring(0, i - 1);
reqSaved = 50 ;
}
tmodel.setValueAt( old, tableIndex, REQ_COLUMN );
}
if ( xmlFormat ) {
// Do XML Formatting
boolean inXML = false ;
int bufferLen = saved ;
if ( len != -1 ) {
bufferLen += len ;
}
i1 = 0 ;
i2 = 0 ;
saved = 0 ;
for ( ; i1 < bufferLen ; i1++ ) {
// Except when we're at EOF, saved last char
if ( len != -1 && i1 + 1 == bufferLen ) {
saved = 1;
break;
}
thisIndent = -1;
if ( buffer[i1] == '<' && buffer[i1 + 1] != '/' ) {
previousIndent = nextIndent++;
thisIndent = nextIndent;
inXML = true ;
}
if ( buffer[i1] == '<' && buffer[i1 + 1] == '/' ) {
if (previousIndent > nextIndent) {
thisIndent = nextIndent;
}
previousIndent = nextIndent--;
inXML = true ;
}
if ( buffer[i1] == '/' && buffer[i1 + 1] == '>' ) {
previousIndent = nextIndent--;
inXML = true ;
}
if ( thisIndent != -1 ) {
if ( thisIndent > 0 ) {
tmpbuffer[i2++] = (byte) '\n';
}
for ( i = tabWidth * thisIndent; i > 0; i-- ) {
tmpbuffer[i2++] = (byte) ' ';
}
}
atMargin = ( buffer[i1] == '\n' || buffer[i1] == '\r');
if ( !inXML || !atMargin ) {
tmpbuffer[i2++] = buffer[i1];
}
}
message = new String( tmpbuffer, 0, i2, getEncoding() );
if (numericEnc) {
textArea.append( StringUtils.escapeNumericChar(message) );
} else {
textArea.append( StringUtils.unescapeNumericChar(message) );
}
// Shift saved bytes to the beginning
for ( i = 0 ; i < saved ; i++ ) {
buffer[i] = buffer[bufferLen - saved + i];
}
}
else {
message = new String( buffer, 0, len, getEncoding() );
if (numericEnc) {
textArea.append( StringUtils.escapeNumericChar(message) );
} else {
textArea.append( StringUtils.unescapeNumericChar(message) );
}
}
// this.sleep(3); // Let other threads have a chance to run
}
// this.sleep(3); // Let other threads have a chance to run
// halt();
// Only set the 'done' flag if we were reading from a
// Socket - if we were reading from an input stream then
// we'll let the other side control when we're done
// if ( inSocket != null ) done = true ;
}
catch ( Throwable t ) {
t.printStackTrace();
}
finally {
done = true ;
try {
if (out != null) {
out.flush();
if (null != outSocket) {
outSocket.shutdownOutput();
} else {
out.close();
}
out = null;
}
}
catch (Exception e) {
;
}
try {
if (in != null) {
if (inSocket != null) {
inSocket.shutdownInput();
} else {
in.close();
}
in = null;
}
}
catch (Exception e) {
;
}
myConnection.wakeUp();
}
}
private String getEncoding() {
try {
return XMLUtils.getEncoding();
} catch (Throwable t){
return "UTF-8";
}
}
public void halt() {
try {
if ( inSocket != null ) {
inSocket.close();
}
if ( outSocket != null ) {
outSocket.close();
}
inSocket = null ;
outSocket = null ;
if ( in != null ) {
in.close();
}
if ( out != null ) {
out.close();
}
in = null ;
out = null ;
done = true;
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
/**
* a connection listens to a single current connection
*/
class Connection extends Thread {
Listener listener ;
boolean active ;
String fromHost ;
String time ;
JTextArea inputText = null ;
JScrollPane inputScroll = null ;
JTextArea outputText = null ;
JScrollPane outputScroll = null ;
Socket inSocket = null ;
Socket outSocket = null ;
Thread clientThread = null ;
Thread serverThread = null ;
SocketRR rr1 = null ;
SocketRR rr2 = null ;
InputStream inputStream = null ;
String HTTPProxyHost = null ;
int HTTPProxyPort = 80 ;
private SlowLinkSimulator slowLink;
public Connection(Listener l) {
listener = l ;
HTTPProxyHost = l.HTTPProxyHost ;
HTTPProxyPort = l.HTTPProxyPort ;
slowLink =l.slowLink;
}
public Connection(Listener l, Socket s ) {
this (l);
inSocket = s ;
start();
}
public Connection(Listener l, InputStream in ) {
this (l);
inputStream = in ;
start();
}
public void run() {
try {
active = true ;
HTTPProxyHost = System.getProperty( "http.proxyHost" );
if ( HTTPProxyHost != null && HTTPProxyHost.equals("") ) {
HTTPProxyHost = null ;
}
if ( HTTPProxyHost != null ) {
String tmp = System.getProperty( "http.proxyPort" );
if ( tmp != null && tmp.equals("") ) {
tmp = null ;
}
if ( tmp == null ) {
HTTPProxyPort = 80 ;
} else {
HTTPProxyPort = Integer.parseInt( tmp );
}
}
if ( inSocket != null ) {
fromHost = (inSocket.getInetAddress()).getHostName();
} else {
fromHost = "resend" ;
}
String dateformat=getMessage("dateformat00", "yyyy-MM-dd HH:mm:ss");
DateFormat df = new SimpleDateFormat(dateformat);
time = df.format( new Date() );
int count = listener.connections.size();
listener.tableModel.insertRow(count + 1, new Object[] {
getMessage("active00", "Active"),
time,
fromHost,
listener.hostField.getText(), ""
}
);
listener.connections.add( this );
inputText = new JTextArea( null, null, 20, 80 );
inputScroll = new JScrollPane( inputText );
outputText = new JTextArea( null, null, 20, 80 );
outputScroll = new JScrollPane( outputText );
ListSelectionModel lsm = listener.connectionTable.getSelectionModel();
if ( count == 0 || lsm.getLeadSelectionIndex() == 0 ) {
listener.outPane.setVisible( false );
int divLoc = listener.outPane.getDividerLocation();
listener.setLeft( inputScroll );
listener.setRight( outputScroll );
listener.removeButton.setEnabled(false);
listener.removeAllButton.setEnabled(true);
listener.saveButton.setEnabled(true);
listener.resendButton.setEnabled(true);
listener.outPane.setDividerLocation(divLoc);
listener.outPane.setVisible( true );
}
String targetHost = listener.hostField.getText();
int targetPort = Integer.parseInt(listener.tPortField.getText());
int listenPort = Integer.parseInt(listener.portField.getText());
InputStream tmpIn1 = inputStream ;
OutputStream tmpOut1 = null ;
InputStream tmpIn2 = null ;
OutputStream tmpOut2 = null ;
if ( tmpIn1 == null ) {
tmpIn1 = inSocket.getInputStream();
}
if ( inSocket != null ) {
tmpOut1 = inSocket.getOutputStream();
}
String bufferedData = null ;
StringBuffer buf = null ;
int index = listener.connections.indexOf( this );
if (listener.isProxyBox.isSelected() || HTTPProxyHost != null) {
// Check if we're a proxy
byte[] b = new byte[1];
buf = new StringBuffer();
String s ;
for ( ; ; ) {
int len ;
len = tmpIn1.read(b, 0, 1);
if ( len == -1 ) {
break ;
}
s = new String( b );
buf.append( s );
if ( b[0] != '\n' ) {
continue ;
}
break ;
}
bufferedData = buf.toString();
inputText.append( bufferedData );
if ( bufferedData.startsWith( "GET " ) ||
bufferedData.startsWith( "POST " ) ||
bufferedData.startsWith( "PUT " ) ||
bufferedData.startsWith( "DELETE " ) ) {
int start, end ;
URL url ;
start = bufferedData.indexOf( ' ' ) + 1;
while ( bufferedData.charAt(start) == ' ' ) {
start++ ;
}
end = bufferedData.indexOf( ' ', start );
String urlString = bufferedData.substring( start, end );
if ( urlString.charAt(0) == '/' ) {
urlString = urlString.substring(1);
}
if ( listener.isProxyBox.isSelected() ) {
url = new URL( urlString );
targetHost = url.getHost();
targetPort = url.getPort();
if ( targetPort == -1 ) {
targetPort = 80 ;
}
listener.tableModel.setValueAt( targetHost, index + 1,
OUTHOST_COLUMN );
bufferedData = bufferedData.substring( 0, start) +
url.getFile() +
bufferedData.substring( end );
}
else {
url = new URL( "http://" + targetHost + ":" +
targetPort + "/" + urlString );
listener.tableModel.setValueAt( targetHost, index + 1,
OUTHOST_COLUMN );
bufferedData = bufferedData.substring( 0, start) +
url.toExternalForm() +
bufferedData.substring( end );
targetHost = HTTPProxyHost ;
targetPort = HTTPProxyPort ;
}
}
}
else {
//
// Change Host: header to point to correct host
//
byte[] b1 = new byte[1];
buf = new StringBuffer();
String s1;
String lastLine = null ;
for ( ; ; ) {
int len ;
len = tmpIn1.read(b1, 0, 1);
if ( len == -1 ) {
break ;
}
s1 = new String( b1 );
buf.append( s1 );
if ( b1[0] != '\n' ) {
continue ;
}
// we have a complete line
String line = buf.toString();
buf.setLength(0);
// check to see if we have found Host: header
if (line.startsWith("Host: ")) {
// we need to update the hostname to target host
String newHost = "Host: " + targetHost + ":" + listenPort + "\r\n";
bufferedData = bufferedData.concat(newHost);
break ;
}
// add it to our headers so far
if (bufferedData == null) {
bufferedData = line;
} else {
bufferedData = bufferedData.concat(line);
}
// failsafe
if (line.equals("\r\n")) {
break;
}
if ("\n".equals(lastLine) && line.equals("\n")) {
break ;
}
lastLine = line ;
}
if ( bufferedData != null ) {
inputText.append( bufferedData );
int idx = bufferedData.length() < 50 ? bufferedData.length() : 50;
s1 = bufferedData.substring( 0, idx );
int i = s1.indexOf('\n');
if ( i > 0 ) {
s1 = s1.substring(0, i - 1);
}
s1 = s1 + " " +
" ";
s1 = s1.substring(0, 51);
listener.tableModel.setValueAt( s1, index + 1,
REQ_COLUMN );
}
}
if ( targetPort == -1 ) {
targetPort = 80 ;
}
outSocket = new Socket(targetHost, targetPort );
tmpIn2 = outSocket.getInputStream();
tmpOut2 = outSocket.getOutputStream();
if ( bufferedData != null ) {
byte[] b = bufferedData.getBytes();
tmpOut2.write( b );
slowLink.pump(b.length);
}
boolean format = listener.xmlFormatBox.isSelected();
boolean numeric = listener.numericBox.isSelected();
//this is the channel to the endpoint
rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket,
tmpOut2, inputText, format, numeric,
listener.tableModel, index + 1, "request:", slowLink);
//create the response slow link from the inbound slow link
SlowLinkSimulator responseLink = new SlowLinkSimulator(slowLink);
//this is the channel from the endpoint
rr2 = new SocketRR( this, outSocket, tmpIn2, inSocket,
tmpOut1, outputText, format, numeric,
null, 0, "response:", responseLink);
while ( rr1 != null || rr2 != null ) {
// Only loop as long as the connection to the target
// machine is available - once that's gone we can stop.
// The old way, loop until both are closed, left us
// looping forever since no one closed the 1st one.
// while( !rr2.isDone() )
if (null != rr1 && rr1.isDone()) {
if ( index >= 0 && rr2 != null) {
listener.tableModel.setValueAt(getMessage("resp00", "Resp"),
1 + index, STATE_COLUMN );
}
rr1 = null;
}
if (null != rr2 && rr2.isDone()) {
if ( index >= 0 && rr1 != null ) {
listener.tableModel.setValueAt(getMessage("req00", "Req"),
1 + index, STATE_COLUMN );
}
rr2 = null;
}
// Thread.sleep( 10 );
synchronized ( this) {
this.wait(1000); //Safety just incase we're not told to wake up.
}
}
// System.out.println("Done ");
// rr1.halt();
// rr2.halt();
active = false ;
/*
if ( inSocket != null ) {
inSocket.close();
inSocket = null ;
}
outSocket.close();
outSocket = null ;
*/
if ( index >= 0 ) {
listener.tableModel.setValueAt(getMessage("done00", "Done"),
1 + index, STATE_COLUMN );
}
}
catch ( Exception e ) {
StringWriter st = new StringWriter();
PrintWriter wr = new PrintWriter(st);
int index = listener.connections.indexOf( this );
if ( index >= 0 ) {
listener.tableModel.setValueAt( getMessage("error00", "Error"), 1 + index, STATE_COLUMN );
}
e.printStackTrace(wr);
wr.close();
if(outputText!=null) {
outputText.append( st.toString() );
} else {
//something went wrong before we had the output area
System.out.println(st.toString());
}
halt();
}
}
synchronized void wakeUp() {
this.notifyAll();
}
public void halt() {
try {
if ( rr1 != null ) {
rr1.halt();
}
if ( rr2 != null ) {
rr2.halt();
}
if ( inSocket != null ) {
inSocket.close();
}
inSocket = null ;
if ( outSocket != null ) {
outSocket.close();
}
outSocket = null ;
}
catch ( Exception e ) {
e.printStackTrace();
}
}
public void remove() {
int index = -1;
try {
halt();
index = listener.connections.indexOf( this );
listener.tableModel.removeRow( index + 1 );
listener.connections.remove( index );
}
catch ( Exception e ) {
System.err.println("index:=" + index + this );
e.printStackTrace();
}
}
}
/**
* this is one of the tabbed panels that acts as the actual proxy
*/
class Listener extends JPanel {
public Socket inputSocket = null ;
public Socket outputSocket = null ;
public JTextField portField = null ;
public JTextField hostField = null ;
public JTextField tPortField = null ;
public JCheckBox isProxyBox = null ;
public JButton stopButton = null ;
public JButton removeButton = null ;
public JButton removeAllButton = null ;
public JCheckBox xmlFormatBox = null ;
public JCheckBox numericBox = null ;
public JButton saveButton = null ;
public JButton resendButton = null ;
public JButton switchButton = null ;
public JButton closeButton = null ;
public JTable connectionTable = null ;
public DefaultTableModel tableModel = null ;
public JSplitPane outPane = null ;
public ServerSocket sSocket = null ;
public SocketWaiter sw = null ;
public JPanel leftPanel = null ;
public JPanel rightPanel = null ;
public JTabbedPane notebook = null ;
public String HTTPProxyHost = null ;
public int HTTPProxyPort = 80 ;
public int delayBytes = 0;
public int delayTime = 0;
public SlowLinkSimulator slowLink;
public final Vector connections = new Vector();
/**
* create a listener
* @param _notebook
* @param name
* @param listenPort
* @param host
* @param targetPort
* @param isProxy
* @param slowLink optional reference to a slow connection
*/
public Listener(JTabbedPane _notebook, String name,
int listenPort, String host, int targetPort,
boolean isProxy, SlowLinkSimulator slowLink) {
notebook = _notebook ;
if ( name == null ) {
name = getMessage("port01", "Port") + " " + listenPort ;
}
//set the slow link to the passed down link
if(slowLink!=null) {
this.slowLink=slowLink;
} else {
//or make up a no-op one.
this.slowLink=new SlowLinkSimulator(0,0);
}
this.setLayout( new BorderLayout() );
// 1st component is just a row of labels and 1-line entry fields
/////////////////////////////////////////////////////////////////////
JPanel top = new JPanel();
top.setLayout( new BoxLayout(top, BoxLayout.X_AXIS) );
top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
final String start = getMessage("start00", "Start");
top.add( stopButton = new JButton( start ) );
top.add( Box.createRigidArea(new Dimension(5, 0)) );
top.add( new JLabel( " " + getMessage("listenPort01", "Listen Port:") + " ", SwingConstants.RIGHT ) );
top.add( portField = new JTextField( "" + listenPort, 4 ) );
top.add( new JLabel( " " + getMessage("host00", "Host:"), SwingConstants.RIGHT ) );
top.add( hostField = new JTextField( host, 30 ) );
top.add( new JLabel( " " + getMessage("port02", "Port:") + " ", SwingConstants.RIGHT ) );
top.add( tPortField = new JTextField( "" + targetPort, 4 ) );
top.add( Box.createRigidArea(new Dimension(5, 0)) );
top.add( isProxyBox = new JCheckBox(getMessage("proxy00", "Proxy")) );
isProxyBox.addChangeListener( new BasicButtonListener(isProxyBox) {
public void stateChanged(ChangeEvent event) {
JCheckBox box = (JCheckBox) event.getSource();
boolean state = box.isSelected();
tPortField.setEnabled( !state );
hostField.setEnabled( !state );
}
}
);
isProxyBox.setSelected(isProxy);
portField.setEditable(false);
portField.setMaximumSize(new Dimension(50, Short.MAX_VALUE) );
hostField.setEditable(false);
hostField.setMaximumSize(new Dimension(85, Short.MAX_VALUE) );
tPortField.setEditable(false);
tPortField.setMaximumSize(new Dimension(50, Short.MAX_VALUE) );
stopButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( getMessage("stop00", "Stop").equals(event.getActionCommand()) ) {
stop();
}
if ( start.equals(event.getActionCommand()) ) {
start();
}
}
}
);
this.add( top, BorderLayout.NORTH );
// 2nd component is a split pane with a table on the top
// and the request/response text areas on the bottom
/////////////////////////////////////////////////////////////////////
tableModel = new DefaultTableModel(new String[] {
getMessage("state00", "State"),
getMessage("time00", "Time"),
getMessage("requestHost00", "Request Host"),
getMessage("targetHost", "Target Host"),
getMessage("request00", "Request...")
} , 0 );
tableModel.addRow( new Object[] {
"---", getMessage("mostRecent00", "Most Recent"), "---", "---", "---"
}
);
connectionTable = new JTable(1, 2);
connectionTable.setModel( tableModel );
connectionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Reduce the STATE column and increase the REQ column
TableColumn col ;
col = connectionTable.getColumnModel().getColumn(STATE_COLUMN);
col.setMaxWidth( col.getPreferredWidth() / 2 );
col = connectionTable.getColumnModel().getColumn(REQ_COLUMN);
col.setPreferredWidth( col.getPreferredWidth() * 2 );
ListSelectionModel sel = connectionTable.getSelectionModel();
sel.addListSelectionListener( new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return ;
}
ListSelectionModel m = (ListSelectionModel) event.getSource();
int divLoc = outPane.getDividerLocation();
if (m.isSelectionEmpty()) {
setLeft( new JLabel(" " + getMessage("wait00", "Waiting for Connection...") ) );
setRight( new JLabel("") );
removeButton.setEnabled(false);
removeAllButton.setEnabled(false);
saveButton.setEnabled(false);
resendButton.setEnabled(false);
}
else {
int row = m.getLeadSelectionIndex();
if ( row == 0 ) {
if ( connections.size() == 0 ) {
setLeft(new JLabel(" " + getMessage("wait00", "Waiting for connection...")));
setRight(new JLabel(""));
removeButton.setEnabled(false);
removeAllButton.setEnabled(false);
saveButton.setEnabled(false);
resendButton.setEnabled(false);
}
else {
Connection conn = (Connection) connections.lastElement();
setLeft( conn.inputScroll );
setRight( conn.outputScroll );
removeButton.setEnabled(false);
removeAllButton.setEnabled(true);
saveButton.setEnabled(true);
resendButton.setEnabled(true);
}
}
else {
Connection conn = (Connection) connections.get(row - 1);
setLeft( conn.inputScroll );
setRight( conn.outputScroll );
removeButton.setEnabled(true);
removeAllButton.setEnabled(true);
saveButton.setEnabled(true);
resendButton.setEnabled(true);
}
}
outPane.setDividerLocation(divLoc);
}
}
);
JPanel tablePane = new JPanel();
tablePane.setLayout( new BorderLayout() );
JScrollPane tableScrollPane = new JScrollPane( connectionTable );
tablePane.add( tableScrollPane, BorderLayout.CENTER );
JPanel buttons = new JPanel();
buttons.setLayout( new BoxLayout(buttons, BoxLayout.X_AXIS) );
buttons.setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5) );
final String removeSelected = getMessage("removeSelected00", "Remove Selected");
buttons.add( removeButton = new JButton(removeSelected) );
buttons.add( Box.createRigidArea(new Dimension(5, 0)) );
final String removeAll = getMessage("removeAll00", "Remove All");
buttons.add( removeAllButton = new JButton(removeAll) );
tablePane.add( buttons, BorderLayout.SOUTH );
removeButton.setEnabled( false );
removeButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( removeSelected.equals(event.getActionCommand()) ) {
remove();
}
}
}
);
removeAllButton.setEnabled( false );
removeAllButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( removeAll.equals(event.getActionCommand()) ) {
removeAll();
}
}
}
);
// Add Response Section
/////////////////////////////////////////////////////////////////////
JPanel pane2 = new JPanel();
pane2.setLayout( new BorderLayout() );
leftPanel = new JPanel();
leftPanel.setAlignmentX( Component.LEFT_ALIGNMENT );
leftPanel.setLayout( new BoxLayout(leftPanel, BoxLayout.Y_AXIS) );
leftPanel.add( new JLabel(" " + getMessage("request01", "Request")) );
leftPanel.add( new JLabel(" " + getMessage("wait01", "Waiting for connection") ));
rightPanel = new JPanel();
rightPanel.setLayout( new BoxLayout(rightPanel, BoxLayout.Y_AXIS) );
rightPanel.add( new JLabel(" " + getMessage("response00", "Response")) );
rightPanel.add( new JLabel("") );
outPane = new JSplitPane(0, leftPanel, rightPanel );
outPane.setDividerSize(4);
pane2.add( outPane, BorderLayout.CENTER );
JPanel bottomButtons = new JPanel();
bottomButtons.setLayout( new BoxLayout(bottomButtons, BoxLayout.X_AXIS));
bottomButtons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
bottomButtons.add( xmlFormatBox = new JCheckBox( getMessage("xmlFormat00", "XML Format") ) );
bottomButtons.add( numericBox = new JCheckBox( getMessage("numericEnc00", "Numeric" ) ) );
bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
final String save = getMessage("save00", "Save");
bottomButtons.add( saveButton = new JButton( save ) );
bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
final String resend = getMessage("resend00", "Resend");
bottomButtons.add( resendButton = new JButton( resend ) );
bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
final String switchStr = getMessage("switch00", "Switch Layout");
bottomButtons.add( switchButton = new JButton( switchStr ) );
bottomButtons.add( Box.createHorizontalGlue() );
final String close = getMessage("close00", "Close");
bottomButtons.add( closeButton = new JButton( close ) );
pane2.add( bottomButtons, BorderLayout.SOUTH );
saveButton.setEnabled( false );
saveButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( save.equals(event.getActionCommand()) ) {
save();
}
}
}
);
resendButton.setEnabled( false );
resendButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( resend.equals(event.getActionCommand()) ) {
resend();
}
}
}
);
switchButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (switchStr.equals(event.getActionCommand()) ) {
int v = outPane.getOrientation();
if ( v == 0 ) {
// top/bottom
outPane.setOrientation(1);
}
else {
// left/right
outPane.setOrientation(0);
}
outPane.setDividerLocation(0.5);
}
}
}
);
closeButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (close.equals(event.getActionCommand()) ) {
close();
}
}
}
);
JSplitPane pane1 = new JSplitPane( 0 );
pane1.setDividerSize(4);
pane1.setTopComponent( tablePane );
pane1.setBottomComponent( pane2 );
pane1.setDividerLocation( 150 );
this.add( pane1, BorderLayout.CENTER );
//
////////////////////////////////////////////////////////////////////
sel.setSelectionInterval(0, 0);
outPane.setDividerLocation( 150 );
notebook.addTab( name, this );
start();
}
public void setLeft(Component left) {
leftPanel.removeAll();
leftPanel.add(left);
}
public void setRight(Component right) {
rightPanel.removeAll();
rightPanel.add(right);
}
public void start() {
int port = Integer.parseInt( portField.getText() );
portField.setText( "" + port );
int i = notebook.indexOfComponent( this );
notebook.setTitleAt( i, getMessage("port01", "Port") + " " + port );
int tmp = Integer.parseInt( tPortField.getText() );
tPortField.setText( "" + tmp );
sw = new SocketWaiter( this, port );
stopButton.setText( getMessage("stop00", "Stop") );
portField.setEditable(false);
hostField.setEditable(false);
tPortField.setEditable(false);
isProxyBox.setEnabled(false);
}
public void close() {
stop();
notebook.remove( this );
}
public void stop() {
try {
for ( int i = 0 ; i < connections.size() ; i++ ) {
Connection conn = (Connection) connections.get( i );
conn.halt();
}
sw.halt();
stopButton.setText( getMessage("start00", "Start") );
portField.setEditable(true);
hostField.setEditable(true);
tPortField.setEditable(true);
isProxyBox.setEnabled(true);
}
catch ( Exception e ) {
e.printStackTrace();
}
}
public void remove() {
ListSelectionModel lsm = connectionTable.getSelectionModel();
int bot = lsm.getMinSelectionIndex();
int top = lsm.getMaxSelectionIndex();
for ( int i = top ; i >= bot ; i-- ) {
((Connection) connections.get(i - 1)).remove();
}
if ( bot > connections.size() ) {
bot = connections.size();
}
lsm.setSelectionInterval(bot, bot);
}
public void removeAll() {
ListSelectionModel lsm = connectionTable.getSelectionModel();
lsm.clearSelection();
while ( connections.size() > 0 ) {
((Connection) connections.get(0)).remove();
}
lsm.setSelectionInterval(0, 0);
}
public void save() {
JFileChooser dialog = new JFileChooser( "." );
int rc = dialog.showSaveDialog( this );
if ( rc == JFileChooser.APPROVE_OPTION ) {
try {
File file = dialog.getSelectedFile();
FileOutputStream out = new FileOutputStream( file );
ListSelectionModel lsm = connectionTable.getSelectionModel();
rc = lsm.getLeadSelectionIndex();
int n = 0;
for (Iterator i = connections.iterator();i.hasNext();n++) {
Connection conn = (Connection)i.next();
if (lsm.isSelectedIndex(n + 1) ||
(!(i.hasNext()) && lsm.getLeadSelectionIndex() == 0)) {
rc = Integer.parseInt( portField.getText() );
out.write("\n==============\n".getBytes());
out.write( ((getMessage("listenPort01", "Listen Port:") + " " + rc + "\n" )).getBytes() );
out.write( (getMessage("targetHost01", "Target Host:") + " " + hostField.getText() +
"\n" ).getBytes() );
rc = Integer.parseInt( tPortField.getText() );
out.write( ((getMessage("targetPort01", "Target Port:") + " " + rc + "\n" )).getBytes() );
out.write( (("==== " + getMessage("request01", "Request") + " ====\n" )).getBytes() );
out.write( conn.inputText.getText().getBytes() );
out.write( (("==== " + getMessage("response00", "Response") + " ====\n" )).getBytes() );
out.write( conn.outputText.getText().getBytes() );
out.write("\n==============\n".getBytes());
}
}
out.close();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
public void resend() {
int rc ;
try {
ListSelectionModel lsm = connectionTable.getSelectionModel();
rc = lsm.getLeadSelectionIndex();
if ( rc == 0 ) {
rc = connections.size();
}
Connection conn = (Connection) connections.get( rc - 1 );
if ( rc > 0 ) {
lsm.clearSelection();
lsm.setSelectionInterval(0, 0);
}
InputStream in = null ;
String text = conn.inputText.getText();
// Fix Content-Length HTTP headers
if ( text.startsWith("POST ") || text.startsWith("GET ") ) {
// System.err.println("IN CL" );
int pos1, pos2, pos3 ;
String body, headers, headers1, header2 ;
pos3 = text.indexOf( "\n\n" );
if ( pos3 == -1 ) {
pos3 = text.indexOf( "\r\n\r\n" );
if ( pos3 != -1 ) {
pos3 = pos3 + 4 ;
}
}
else {
pos3 += 2 ;
}
headers = text.substring( 0, pos3 );
pos1 = headers.indexOf( "Content-Length:" );
// System.err.println("pos1: " + pos1 );
// System.err.println("pos3: " + pos3 );
if ( pos1 != -1 ) {
int newLen = text.length() - pos3 ;
pos2 = headers.indexOf( "\n", pos1 );
System.err.println("CL: " + newLen );
System.err.println("Hdrs: '" + headers + "'" );
System.err.println("subTEXT: '" +
text.substring(pos3, pos3 + newLen) + "'");
text = headers.substring(0, pos1) +
"Content-Length: " + newLen + "\n" +
headers.substring(pos2 + 1) +
text.substring(pos3) ;
System.err.println("\nTEXT: '" + text + "'" );
}
}
in = new ByteArrayInputStream( text.getBytes() );
new Connection( this, in );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
public tcpmon(int listenPort, String targetHost, int targetPort, boolean embedded) {
super ( getMessage("tcpmon00", "TCPMonitor") );
notebook = new JTabbedPane();
this.getContentPane().add( notebook );
new AdminPage( notebook, getMessage("admin00", "Admin") );
if ( listenPort != 0 ) {
Listener l = null ;
if ( targetHost == null ) {
l = new Listener( notebook, null, listenPort,
targetHost, targetPort, true, null);
} else {
l = new Listener( notebook, null, listenPort,
targetHost, targetPort, false, null);
}
notebook.setSelectedIndex( 1 );
l.HTTPProxyHost = System.getProperty( "http.proxyHost" );
if ( l.HTTPProxyHost != null && l.HTTPProxyHost.equals("") ) {
l.HTTPProxyHost = null ;
}
if ( l.HTTPProxyHost != null ) {
String tmp = System.getProperty( "http.proxyPort" );
if ( tmp != null && tmp.equals("") ) {
tmp = null ;
}
if ( tmp == null ) {
l.HTTPProxyPort = 80 ;
} else {
l.HTTPProxyPort = Integer.parseInt( tmp );
}
}
}
if(!embedded) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
this.pack();
this.setSize( 600, 600 );
this.setVisible( true );
}
public tcpmon(int listenPort, String targetHost, int targetPort) {
this(listenPort, targetHost, targetPort, false);
}
/**
* set up the L&F
*/
private static void setupLookAndFeel(boolean nativeLookAndFeel) throws Exception {
String classname= UIManager.getCrossPlatformLookAndFeelClassName();
if(nativeLookAndFeel) {
classname= UIManager.getSystemLookAndFeelClassName();
}
String lafProperty= System.getProperty("tcpmon.laf", "");
if(lafProperty.length()>0) {
classname=lafProperty;
}
try {
UIManager.setLookAndFeel(classname);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
/**
* this is our main method
* @param args
*/
public static void main(String[] args) {
try {
//switch between swing L&F here
setupLookAndFeel(true);
if ( args.length == 3 ) {
int p1 = Integer.parseInt( args[0] );
int p2 = Integer.parseInt( args[2] );
new tcpmon( p1, args[1], p2 );
}
else if ( args.length == 1 ) {
int p1 = Integer.parseInt( args[0] );
new tcpmon( p1, null, 0 );
}
else if ( args.length != 0 ) {
System.err.println( getMessage("usage00", "Usage:")
+ " tcpmon [listenPort targetHost targetPort]\n");
}
else {
new tcpmon(0, null, 0);
}
}
catch ( Throwable exp ) {
exp.printStackTrace();
}
}
// Message resource bundle.
private static ResourceBundle messages = null;
/**
* Get the message with the given key. There are no arguments for this message.
*/
public static String getMessage(String key, String defaultMsg) {
try {
if (messages == null) {
initializeMessages();
}
return messages.getString(key);
} catch (Throwable t) {
// If there is any problem whatsoever getting the internationalized
// message, return the default.
return defaultMsg;
}
} // getMessage
/**
* Load the resource bundle messages from the properties file. This is ONLY done when it is
* needed. If no messages are printed (for example, only Wsdl2java is being run in non-
* verbose mode) then there is no need to read the properties file.
*/
private static void initializeMessages() {
messages = ResourceBundle.getBundle("org.apache.axis.utils.tcpmon");
} // initializeMessages
/**
* a text field with a restricted set of characters
*/
static class RestrictedTextField extends JTextField {
protected String validText;
public RestrictedTextField(String validText) {
setValidText(validText);
}
public RestrictedTextField(int columns, String validText) {
super(columns);
setValidText(validText);
}
public RestrictedTextField(String text, String validText) {
super(text);
setValidText(validText);
}
public RestrictedTextField(String text, int columns, String validText) {
super(text, columns);
setValidText(validText);
}
private void setValidText(String validText) {
this.validText = validText;
}
/**
* fascinatingly, this method is called in the super() constructor,
* meaning before we are fully initialized. C++ doesnt actually permit
* such a situation, but java clearly does...
* @return a new document
*/
public Document createDefaultModel() {
return new RestrictedDocument();
}
/**
* this class strips out invaid chars
*/
class RestrictedDocument extends PlainDocument {
/**
* Constructs a plain text document. A default model using
* <code>GapContent</code> is constructed and set.
*/
public RestrictedDocument() {
}
/**
* add a string; only those chars in the valid text list are allowed
* @param offset
* @param string
* @param attributes
* @throws BadLocationException
*/
public void insertString(int offset, String string, AttributeSet attributes)
throws BadLocationException {
if (string == null) {
return;
}
int len = string.length();
StringBuffer buffer = new StringBuffer(string.length());
for (int i = 0; i < len; i++) {
char ch = string.charAt(i);
if (validText.indexOf(ch) >= 0) {
buffer.append(ch);
}
}
super.insertString(offset, new String(buffer), attributes);
}
} //end class NumericDocument
}
/**
* because we cant use Java1.4's JFormattedTextField, here is
* a class that accepts numbers only
*/
static class NumberField extends RestrictedTextField {
private static final String VALID_TEXT = "0123456789";
/**
* Constructs a new <code>TextField</code>. A default model is created,
* the initial string is <code>null</code>,
* and the number of columns is set to 0.
*/
public NumberField() {
super(VALID_TEXT);
}
/**
* Constructs a new empty <code>TextField</code> with the specified
* number of columns.
* A default model is created and the initial string is set to
* <code>null</code>.
*
* @param columns the number of columns to use to calculate
* the preferred width; if columns is set to zero, the
* preferred width will be whatever naturally results from
* the component implementation
*/
public NumberField(int columns) {
super(columns, VALID_TEXT);
}
/**
* get the int value of a field, any invalid (non int) field returns
* the default
* @param def default value
* @return the field contents
*/
public int getValue(int def) {
int result = def;
String text = getText();
if (text != null && text.length() != 0) {
try {
result = Integer.parseInt(text);
} catch (NumberFormatException e) {
}
}
return result;
}
/**
* set the text to a numeric value
* @param value number to assign
*/
public void setValue(int value) {
setText(Integer.toString(value));
}
} //end class NumericTextField
/**
* hostname fields
*/
static class HostnameField extends RestrictedTextField {
//list of valid chars in a hostname
private static final String VALID_TEXT =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ-.";
public HostnameField(int columns) {
super(columns, VALID_TEXT);
}
public HostnameField() {
super(VALID_TEXT);
}
}
}
| 7,029 |
0 | Create_ds/axis-axis1-java/soapmonitor-applet/src/main | Create_ds/axis-axis1-java/soapmonitor-applet/src/main/java/SOAPMonitorApplet.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.
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
/**
* This is a SOAP Mointor Applet class. This class provides
* the user interface for displaying data from the SOAP
* monitor service.
*
* @author Brian Price (pricebe@us.ibm.com)
*
*/
public class SOAPMonitorApplet extends JApplet {
private static final int SOAP_MONITOR_REQUEST = 0;
private static final int SOAP_MONITOR_RESPONSE = 1;
/**
* Private data
*/
private JPanel main_panel = null;
private JTabbedPane tabbed_pane = null;
private int port = 0;
private Vector pages = null;
/**
* Constructor
*/
public SOAPMonitorApplet() {
}
/**
* Applet initialization
*/
public void init() {
// Get the port to be used
String port_str = getParameter("port");
if (port_str != null) {
port = Integer.parseInt(port_str);
}
// Try to use the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e){
}
// Create main panel to hold notebook
main_panel = new JPanel();
main_panel.setBackground(Color.white);
main_panel.setLayout(new BorderLayout());
setContentPane(main_panel);
// Create the notebook
tabbed_pane = new JTabbedPane(JTabbedPane.TOP);
main_panel.add(tabbed_pane,BorderLayout.CENTER);
// Add notebook page for default host connection
pages = new Vector();
addPage(new SOAPMonitorPage(getCodeBase().getHost()));
}
/**
* Add a page to the notebook
*/
private void addPage(SOAPMonitorPage pg) {
tabbed_pane.addTab(" "+pg.getHost()+" ", pg);
pages.addElement(pg);
}
/**
* Applet is being displayed
*/
public void start() {
// Tell all pages to start talking to the server
Enumeration e = pages.elements();
while (e.hasMoreElements()) {
SOAPMonitorPage pg = (SOAPMonitorPage) e.nextElement();
if (pg != null) {
pg.start();
}
}
}
/*
* Applet is no longer displayed
*/
public void stop() {
// Tell all pages to stop talking to the server
Enumeration e = pages.elements();
while (e.hasMoreElements()) {
SOAPMonitorPage pg = (SOAPMonitorPage) e.nextElement();
if (pg != null) {
pg.stop();
}
}
}
/**
* Applet cleanup
*/
public void destroy() {
tabbed_pane = null;
main_panel = null;
}
/**
* This class provides the contents of a notebook page
* representing a server connection.
*/
class SOAPMonitorPage extends JPanel
implements Runnable,
ListSelectionListener,
ActionListener {
/**
* Status Strings
*/
private final String STATUS_ACTIVE = "The SOAP Monitor is started.";
private final String STATUS_STOPPED = "The SOAP Monitor is stopped.";
private final String STATUS_CLOSED = "The server communication has been terminated.";
private final String STATUS_NOCONNECT = "The SOAP Monitor is unable to communcate with the server.";
/**
* Private data
*/
private String host = null;
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
private SOAPMonitorTableModel model = null;
private JTable table = null;
private JScrollPane scroll = null;
private JPanel list_panel = null;
private JPanel list_buttons = null;
private JButton remove_button = null;
private JButton remove_all_button = null;
private JButton filter_button = null;
private JPanel details_panel = null;
private JPanel details_header = null;
private JSplitPane details_soap = null;
private JPanel details_buttons = null;
private JLabel details_time = null;
private JLabel details_target = null;
private JLabel details_status = null;
private JLabel details_time_value = null;
private JLabel details_target_value = null;
private JLabel details_status_value = null;
private EmptyBorder empty_border = null;
private EtchedBorder etched_border = null;
private JPanel request_panel = null;
private JPanel response_panel = null;
private JLabel request_label = null;
private JLabel response_label = null;
private SOAPMonitorTextArea request_text = null;
private SOAPMonitorTextArea response_text = null;
private JScrollPane request_scroll = null;
private JScrollPane response_scroll = null;
private JButton layout_button = null;
private JSplitPane split = null;
private JPanel status_area = null;
private JPanel status_buttons = null;
private JButton start_button = null;
private JButton stop_button = null;
private JLabel status_text = null;
private JPanel status_text_panel = null;
private SOAPMonitorFilter filter = null;
private GridBagLayout details_header_layout = null;
private GridBagConstraints details_header_constraints = null;
private JCheckBox reflow_xml = null;
/**
* Constructor (create and layout page)
*/
public SOAPMonitorPage(String host_name) {
host = host_name;
// Set up default filter (show all messages)
filter = new SOAPMonitorFilter();
// Use borders to help improve appearance
etched_border = new EtchedBorder();
// Build top portion of split (list panel)
model = new SOAPMonitorTableModel();
table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionInterval(0,0);
table.setPreferredScrollableViewportSize(new Dimension(600, 96));
table.getSelectionModel().addListSelectionListener(this);
scroll = new JScrollPane(table);
remove_button = new JButton("Remove");
remove_button.addActionListener(this);
remove_button.setEnabled(false);
remove_all_button = new JButton("Remove All");
remove_all_button.addActionListener(this);
filter_button = new JButton("Filter ...");
filter_button.addActionListener(this);
list_buttons = new JPanel();
list_buttons.setLayout(new FlowLayout());
list_buttons.add(remove_button);
list_buttons.add(remove_all_button);
list_buttons.add(filter_button);
list_panel = new JPanel();
list_panel.setLayout(new BorderLayout());
list_panel.add(scroll,BorderLayout.CENTER);
list_panel.add(list_buttons, BorderLayout.SOUTH);
list_panel.setBorder(empty_border);
// Build bottom portion of split (message details)
details_time = new JLabel("Time: ", SwingConstants.RIGHT);
details_target = new JLabel("Target Service: ", SwingConstants.RIGHT);
details_status = new JLabel("Status: ", SwingConstants.RIGHT);
details_time_value = new JLabel();
details_target_value = new JLabel();
details_status_value = new JLabel();
Dimension preferred_size = details_time.getPreferredSize();
preferred_size.width = 1;
details_time.setPreferredSize(preferred_size);
details_target.setPreferredSize(preferred_size);
details_status.setPreferredSize(preferred_size);
details_time_value.setPreferredSize(preferred_size);
details_target_value.setPreferredSize(preferred_size);
details_status_value.setPreferredSize(preferred_size);
details_header = new JPanel();
details_header_layout = new GridBagLayout();
details_header.setLayout(details_header_layout);
details_header_constraints = new GridBagConstraints();
details_header_constraints.fill=GridBagConstraints.BOTH;
details_header_constraints.weightx=0.5;
details_header_layout.setConstraints(details_time,details_header_constraints);
details_header.add(details_time);
details_header_layout.setConstraints(details_time_value,details_header_constraints);
details_header.add(details_time_value);
details_header_layout.setConstraints(details_target,details_header_constraints);
details_header.add(details_target);
details_header_constraints.weightx=1.0;
details_header_layout.setConstraints(details_target_value,details_header_constraints);
details_header.add(details_target_value);
details_header_constraints.weightx=.5;
details_header_layout.setConstraints(details_status,details_header_constraints);
details_header.add(details_status);
details_header_layout.setConstraints(details_status_value,details_header_constraints);
details_header.add(details_status_value);
details_header.setBorder(etched_border);
request_label = new JLabel("SOAP Request", SwingConstants.CENTER);
request_text = new SOAPMonitorTextArea();
request_text.setEditable(false);
request_scroll = new JScrollPane(request_text);
request_panel = new JPanel();
request_panel.setLayout(new BorderLayout());
request_panel.add(request_label, BorderLayout.NORTH);
request_panel.add(request_scroll, BorderLayout.CENTER);
response_label = new JLabel("SOAP Response", SwingConstants.CENTER);
response_text = new SOAPMonitorTextArea();
response_text.setEditable(false);
response_scroll = new JScrollPane(response_text);
response_panel = new JPanel();
response_panel.setLayout(new BorderLayout());
response_panel.add(response_label, BorderLayout.NORTH);
response_panel.add(response_scroll, BorderLayout.CENTER);
details_soap = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
details_soap.setTopComponent(request_panel);
details_soap.setRightComponent(response_panel);
details_soap.setResizeWeight(.5);
details_panel = new JPanel();
layout_button = new JButton("Switch Layout");
layout_button.addActionListener(this);
reflow_xml = new JCheckBox("Reflow XML text");
reflow_xml.addActionListener(this);
details_buttons = new JPanel();
details_buttons.setLayout(new FlowLayout());
details_buttons.add(reflow_xml);
details_buttons.add(layout_button);
details_panel.setLayout(new BorderLayout());
details_panel.add(details_header,BorderLayout.NORTH);
details_panel.add(details_soap,BorderLayout.CENTER);
details_panel.add(details_buttons,BorderLayout.SOUTH);
details_panel.setBorder(empty_border);
// Add the two parts to the age split pane
split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
split.setTopComponent(list_panel);
split.setRightComponent(details_panel);
// Build status area
start_button = new JButton("Start");
start_button.addActionListener(this);
stop_button = new JButton("Stop");
stop_button.addActionListener(this);
status_buttons = new JPanel();
status_buttons.setLayout(new FlowLayout());
status_buttons.add(start_button);
status_buttons.add(stop_button);
status_text = new JLabel();
status_text.setBorder(new BevelBorder(BevelBorder.LOWERED));
status_text_panel = new JPanel();
status_text_panel.setLayout(new BorderLayout());
status_text_panel.add(status_text, BorderLayout.CENTER);
status_text_panel.setBorder(empty_border);
status_area = new JPanel();
status_area.setLayout(new BorderLayout());
status_area.add(status_buttons, BorderLayout.WEST);
status_area.add(status_text_panel, BorderLayout.CENTER);
status_area.setBorder(etched_border);
// Add the split and status area to page
setLayout(new BorderLayout());
add(split, BorderLayout.CENTER);
add(status_area, BorderLayout.SOUTH);
}
/**
* Get the name of the host we are displaying
*/
public String getHost() {
return host;
}
/**
* Set the status text
*/
public void setStatus(String txt) {
status_text.setForeground(Color.black);
status_text.setText(" "+txt);
}
/**
* Set the status text to an error
*/
public void setErrorStatus(String txt) {
status_text.setForeground(Color.red);
status_text.setText(" "+txt);
}
/**
* Start talking to the server
*/
public void start() {
String codehost = getCodeBase().getHost();
if (socket == null) {
try {
// Open the socket to the server
socket = new Socket(codehost, port);
// Create output stream
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
// Create input stream and start background
// thread to read data from the server
in = new ObjectInputStream(socket.getInputStream());
new Thread(this).start();
} catch (Exception e) {
// Exceptions here are unexpected, but we can't
// really do anything (so just write it to stdout
// in case someone cares and then ignore it)
System.out.println("Exception! "+e.toString());
e.printStackTrace();
setErrorStatus(STATUS_NOCONNECT);
socket = null;
}
} else {
// Already started
}
if (socket != null) {
// Make sure the right buttons are enabled
start_button.setEnabled(false);
stop_button.setEnabled(true);
setStatus(STATUS_ACTIVE);
}
}
/**
* Stop talking to the server
*/
public void stop() {
if (socket != null) {
// Close all the streams and socket
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
}
out = null;
}
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
}
in = null;
}
if (socket != null) {
try {
socket.close();
} catch (IOException ioe) {
}
socket = null;
}
} else {
// Already stopped
}
// Make sure the right buttons are enabled
start_button.setEnabled(true);
stop_button.setEnabled(false);
setStatus(STATUS_STOPPED);
}
/**
* Background thread used to receive data from
* the server.
*/
public void run() {
Long id;
Integer message_type;
String target;
String soap;
SOAPMonitorData data;
int selected;
int row;
boolean update_needed;
while (socket != null) {
try {
// Get the data from the server
message_type = (Integer) in.readObject();
// Process the data depending on its type
switch (message_type.intValue()) {
case SOAP_MONITOR_REQUEST:
// Get the id, target and soap info
id = (Long) in.readObject();
target = (String) in.readObject();
soap = (String) in.readObject();
// Add new request data to the table
data = new SOAPMonitorData(id,target,soap);
model.addData(data);
// If "most recent" selected then update
// the details area if needed
selected = table.getSelectedRow();
if ((selected == 0) && model.filterMatch(data)) {
valueChanged(null);
}
break;
case SOAP_MONITOR_RESPONSE:
// Get the id and soap info
id = (Long) in.readObject();
soap = (String) in.readObject();
data = model.findData(id);
if (data != null) {
update_needed = false;
// Get the selected row
selected = table.getSelectedRow();
// If "most recent", then always
// update details area
if (selected == 0) {
update_needed = true;
}
// If the data being updated is
// selected then update details
row = model.findRow(data);
if ((row != -1) && (row == selected)) {
update_needed = true;
}
// Set the response and update table
data.setSOAPResponse(soap);
model.updateData(data);
// Refresh details area (if needed)
if (update_needed) {
valueChanged(null);
}
}
break;
}
} catch (Exception e) {
// Exceptions are expected here when the
// server communication has been terminated.
if (stop_button.isEnabled()) {
stop();
setErrorStatus(STATUS_CLOSED);
}
}
}
}
/**
* Listener to handle table selection changes
*/
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
// Check if they selected a specific row
if (row > 0) {
remove_button.setEnabled(true);
} else {
remove_button.setEnabled(false);
}
// Check for "most recent" selection
if (row == 0) {
row = model.getRowCount() - 1;
if (row == 0) {
row = -1;
}
}
if (row == -1) {
// Clear the details panel
details_time_value.setText("");
details_target_value.setText("");
details_status_value.setText("");
request_text.setText("");
response_text.setText("");
} else {
// Show the details for the row
SOAPMonitorData soap = model.getData(row);
details_time_value.setText(soap.getTime());
details_target_value.setText(soap.getTargetService());
details_status_value.setText(soap.getStatus());
if (soap.getSOAPRequest() == null) {
request_text.setText("");
} else {
request_text.setText(soap.getSOAPRequest());
request_text.setCaretPosition(0);
}
if (soap.getSOAPResponse() == null) {
response_text.setText("");
} else {
response_text.setText(soap.getSOAPResponse());
response_text.setCaretPosition(0);
}
}
}
/**
* Listener to handle button actions
*/
public void actionPerformed(ActionEvent e) {
// Check if the user pressed the remove button
if (e.getSource() == remove_button) {
int row = table.getSelectedRow();
model.removeRow(row);
table.clearSelection();
table.repaint();
valueChanged(null);
}
// Check if the user pressed the remove all button
if (e.getSource() == remove_all_button) {
model.clearAll();
table.setRowSelectionInterval(0,0);
table.repaint();
valueChanged(null);
}
// Check if the user pressed the filter button
if (e.getSource() == filter_button) {
filter.showDialog();
if (filter.okPressed()) {
// Update the display with new filter
model.setFilter(filter);
table.repaint();
}
}
// Check if the user pressed the start button
if (e.getSource() == start_button) {
start();
}
// Check if the user pressed the stop button
if (e.getSource() == stop_button) {
stop();
}
// Check if the user wants to switch layout
if (e.getSource() == layout_button) {
details_panel.remove(details_soap);
details_soap.removeAll();
if (details_soap.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) {
details_soap = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
} else {
details_soap = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
}
details_soap.setTopComponent(request_panel);
details_soap.setRightComponent(response_panel);
details_soap.setResizeWeight(.5);
details_panel.add(details_soap, BorderLayout.CENTER);
details_panel.validate();
details_panel.repaint();
}
// Check if the user is changing the reflow option
if (e.getSource() == reflow_xml) {
request_text.setReflowXML(reflow_xml.isSelected());
response_text.setReflowXML(reflow_xml.isSelected());
}
}
}
/**
* This class represend the data for a SOAP request/response pair
*/
class SOAPMonitorData {
/**
* Private data
*/
private Long id;
private String time;
private String target;
private String soap_request;
private String soap_response;
/**
* Constructor
*/
public SOAPMonitorData(Long id, String target, String soap_request) {
this.id = id;
// A null id is used to signal that the "most recent" entry
// is being created.
if (id == null) {
this.time = "Most Recent";
this.target = "---";
this.soap_request = null;
this.soap_response = null;
} else {
this.time = DateFormat.getTimeInstance().format(new Date());
this.target = target;
this.soap_request = soap_request;
this.soap_response = null;
}
}
/**
* Get the id for the SOAP message
*/
public Long getId() {
return id;
}
/**
* Get the time the SOAP request was received by the applet
*/
public String getTime() {
return time;
}
/**
* Get the SOAP request target service name
*/
public String getTargetService() {
return target;
}
/**
* Get the status of the request
*/
public String getStatus() {
String status = "---";
if (id != null) {
status = "Complete";
if (soap_response == null) {
status = "Active";
}
}
return status;
}
/**
* Get the request SOAP contents
*/
public String getSOAPRequest() {
return soap_request;
}
/**
* Set the resposne SOAP contents
*/
public void setSOAPResponse(String response) {
soap_response = response;
}
/**
* Get the response SOAP contents
*/
public String getSOAPResponse() {
return soap_response;
}
}
/**
* This table model is used to manage the table displayed
* at the top of the page to show all the SOAP messages
* we have received and to control which message details are
* to be displayed on the bottom of the page.
*/
class SOAPMonitorTableModel extends AbstractTableModel {
/**
* Column titles
*/
private final String[] column_names = { "Time",
"Target Service",
"Status" };
/**
* Private data
*/
private Vector data;
private Vector filter_include;
private Vector filter_exclude;
private boolean filter_active;
private boolean filter_complete;
private Vector filter_data;
/**
* Constructor
*/
public SOAPMonitorTableModel() {
data = new Vector();
// Add "most recent" entry to top of table
SOAPMonitorData soap = new SOAPMonitorData(null,null,null);
data.addElement(soap);
filter_include = null;
filter_exclude = null;
filter_active = false;
filter_complete = false;
filter_data = null;
// By default, exclude NotificationService and
// EventViewerService messages
filter_exclude = new Vector();
filter_exclude.addElement("NotificationService");
filter_exclude.addElement("EventViewerService");
filter_data = new Vector();
filter_data.addElement(soap);
}
/**
* Get column count (part of table model interface)
*/
public int getColumnCount() {
return column_names.length;
}
/**
* Get row count (part of table model interface)
*/
public int getRowCount() {
int count = data.size();
if (filter_data != null) {
count = filter_data.size();
}
return count;
}
/**
* Get column name (part of table model interface)
*/
public String getColumnName(int col) {
return column_names[col];
}
/**
* Get value at (part of table model interface)
*/
public Object getValueAt(int row, int col) {
SOAPMonitorData soap;
String value = null;
soap = (SOAPMonitorData) data.elementAt(row);
if (filter_data != null) {
soap = (SOAPMonitorData) filter_data.elementAt(row);
}
switch (col) {
case 0:
value = soap.getTime();
break;
case 1:
value = soap.getTargetService();
break;
case 2:
value = soap.getStatus();
break;
}
return value;
}
/**
* Check if soap data matches filter
*/
public boolean filterMatch(SOAPMonitorData soap) {
boolean match = true;
if (filter_include != null) {
// Check for service match
Enumeration e = filter_include.elements();
match = false;
while (e.hasMoreElements() && !match) {
String service = (String) e.nextElement();
if (service.equals(soap.getTargetService())) {
match = true;
}
}
}
if (filter_exclude != null) {
// Check for service match
Enumeration e = filter_exclude.elements();
while (e.hasMoreElements() && match) {
String service = (String) e.nextElement();
if (service.equals(soap.getTargetService())) {
match = false;
}
}
}
if (filter_active) {
// Check for active status match
if (soap.getSOAPResponse() != null) {
match = false;
}
}
if (filter_complete) {
// Check for complete status match
if (soap.getSOAPResponse() == null) {
match = false;
}
}
// The "most recent" is always a match
if (soap.getId() == null) {
match = true;
}
return match;
}
/**
* Add data to the table as a new row
*/
public void addData(SOAPMonitorData soap) {
int row = data.size();
data.addElement(soap);
if (filter_data != null) {
if (filterMatch(soap)) {
row = filter_data.size();
filter_data.addElement(soap);
fireTableRowsInserted(row,row);
}
} else {
fireTableRowsInserted(row,row);
}
}
/**
* Find the data for a given id
*/
public SOAPMonitorData findData(Long id) {
SOAPMonitorData soap = null;
for (int row=data.size(); (row > 0) && (soap == null); row--) {
soap = (SOAPMonitorData) data.elementAt(row-1);
if (soap.getId().longValue() != id.longValue()) {
soap = null;
}
}
return soap;
}
/**
* Find the row in the table for a given message id
*/
public int findRow(SOAPMonitorData soap) {
int row = -1;
if (filter_data != null) {
row = filter_data.indexOf(soap);
} else {
row = data.indexOf(soap);
}
return row;
}
/**
* Remove all messages from the table (but leave "most recent")
*/
public void clearAll() {
int last_row = data.size() - 1;
if (last_row > 0) {
data.removeAllElements();
SOAPMonitorData soap = new SOAPMonitorData(null,null,null);
data.addElement(soap);
if (filter_data != null) {
filter_data.removeAllElements();
filter_data.addElement(soap);
}
fireTableDataChanged();
}
}
/**
* Remove a message from the table
*/
public void removeRow(int row) {
SOAPMonitorData soap = null;
if (filter_data == null) {
soap = (SOAPMonitorData) data.elementAt(row);
data.remove(soap);
} else {
soap = (SOAPMonitorData) filter_data.elementAt(row);
filter_data.remove(soap);
data.remove(soap);
}
fireTableRowsDeleted(row,row);
}
/**
* Set a new filter
*/
public void setFilter(SOAPMonitorFilter filter) {
// Save new filter criteria
filter_include = filter.getFilterIncludeList();
filter_exclude = filter.getFilterExcludeList();
filter_active = filter.getFilterActive();
filter_complete = filter.getFilterComplete();
applyFilter();
}
/**
* Refilter the list of messages
*/
public void applyFilter() {
// Re-filter using new criteria
filter_data = null;
if ((filter_include != null) ||
(filter_exclude != null) ||
filter_active || filter_complete ) {
filter_data = new Vector();
Enumeration e = data.elements();
SOAPMonitorData soap;
while (e.hasMoreElements()) {
soap = (SOAPMonitorData) e.nextElement();
if (filterMatch(soap)) {
filter_data.addElement(soap);
}
}
}
fireTableDataChanged();
}
/**
* Get the data for a row
*/
public SOAPMonitorData getData(int row) {
SOAPMonitorData soap = null;
if (filter_data == null) {
soap = (SOAPMonitorData) data.elementAt(row);
} else {
soap = (SOAPMonitorData) filter_data.elementAt(row);
}
return soap;
}
/**
* Update a message
*/
public void updateData (SOAPMonitorData soap) {
int row;
if (filter_data == null) {
// No filter, so just fire table updated
row = data.indexOf(soap);
if (row != -1) {
fireTableRowsUpdated(row,row);
}
} else {
// Check if the row was being displayed
row = filter_data.indexOf(soap);
if (row == -1) {
// Row was not displayed, so check for if it
// now needs to be displayed
if (filterMatch(soap)) {
int index = -1;
row = data.indexOf(soap) + 1;
while ((row < data.size()) && (index == -1)) {
index = filter_data.indexOf(data.elementAt(row));
if (index != -1) {
// Insert at this location
filter_data.add(index,soap);
}
row++;
}
if (index == -1) {
// Insert at end
index = filter_data.size();
filter_data.addElement(soap);
}
fireTableRowsInserted(index,index);
}
} else {
// Row was displayed, so check if it needs to
// be updated or removed
if (filterMatch(soap)) {
fireTableRowsUpdated(row,row);
} else {
filter_data.remove(soap);
fireTableRowsDeleted(row,row);
}
}
}
}
}
/**
* Panel with checkbox and list
*/
class ServiceFilterPanel extends JPanel
implements ActionListener,
ListSelectionListener,
DocumentListener {
private JCheckBox service_box = null;
private Vector filter_list = null;
private Vector service_data = null;
private JList service_list = null;
private JScrollPane service_scroll = null;
private JButton remove_service_button = null;
private JPanel remove_service_panel = null;
private EmptyBorder indent_border = null;
private EmptyBorder empty_border = null;
private JPanel service_area = null;
private JPanel add_service_area = null;
private JTextField add_service_field = null;
private JButton add_service_button = null;
private JPanel add_service_panel = null;
/**
* Constructor
*/
public ServiceFilterPanel(String text, Vector list) {
empty_border = new EmptyBorder(5,5,0,5);
indent_border = new EmptyBorder(5,25,5,5);
service_box = new JCheckBox(text);
service_box.addActionListener(this);
service_data = new Vector();
if (list != null) {
service_box.setSelected(true);
service_data = (Vector) list.clone();
}
service_list = new JList(service_data);
service_list.setBorder(new EtchedBorder());
service_list.setVisibleRowCount(5);
service_list.addListSelectionListener(this);
service_list.setEnabled(service_box.isSelected());
service_scroll = new JScrollPane(service_list);
service_scroll.setBorder(new EtchedBorder());
remove_service_button = new JButton("Remove");
remove_service_button.addActionListener(this);
remove_service_button.setEnabled(false);
remove_service_panel = new JPanel();
remove_service_panel.setLayout(new FlowLayout());
remove_service_panel.add(remove_service_button);
service_area = new JPanel();
service_area.setLayout(new BorderLayout());
service_area.add(service_scroll, BorderLayout.CENTER);
service_area.add(remove_service_panel, BorderLayout.EAST);
service_area.setBorder(indent_border);
add_service_field = new JTextField();
add_service_field.addActionListener(this);
add_service_field.getDocument().addDocumentListener(this);
add_service_field.setEnabled(service_box.isSelected());
add_service_button = new JButton("Add");
add_service_button.addActionListener(this);
add_service_button.setEnabled(false);
add_service_panel = new JPanel();
add_service_panel.setLayout(new BorderLayout());
JPanel dummy = new JPanel();
dummy.setBorder(empty_border);
add_service_panel.add(dummy, BorderLayout.WEST);
add_service_panel.add(add_service_button, BorderLayout.EAST);
add_service_area = new JPanel();
add_service_area.setLayout(new BorderLayout());
add_service_area.add(add_service_field, BorderLayout.CENTER);
add_service_area.add(add_service_panel, BorderLayout.EAST);
add_service_area.setBorder(indent_border);
setLayout(new BorderLayout());
add(service_box, BorderLayout.NORTH);
add(service_area, BorderLayout.CENTER);
add(add_service_area, BorderLayout.SOUTH);
setBorder(empty_border);
}
/**
* Get the current list of services
*/
public Vector getServiceList() {
Vector list = null;
if (service_box.isSelected()) {
list = service_data;
}
return list;
}
/**
* Listener to handle button actions
*/
public void actionPerformed(ActionEvent e) {
// Check if the user changed the service filter option
if (e.getSource() == service_box) {
service_list.setEnabled(service_box.isSelected());
service_list.clearSelection();
remove_service_button.setEnabled(false);
add_service_field.setEnabled(service_box.isSelected());
add_service_field.setText("");
add_service_button.setEnabled(false);
}
// Check if the user pressed the add service button
if ((e.getSource() == add_service_button) ||
(e.getSource() == add_service_field)) {
String text = add_service_field.getText();
if ((text != null) && (text.length() > 0)) {
service_data.addElement(text);
service_list.setListData(service_data);
}
add_service_field.setText("");
add_service_field.requestFocus();
}
// Check if the user pressed the remove service button
if (e.getSource() == remove_service_button) {
Object[] sels = service_list.getSelectedValues();
for (int i=0; i<sels.length; i++) {
service_data.removeElement(sels[i]);
}
service_list.setListData(service_data);
service_list.clearSelection();
}
}
/**
* Handle changes to the text field
*/
public void changedUpdate(DocumentEvent e) {
String text = add_service_field.getText();
if ((text != null) && (text.length() > 0)) {
add_service_button.setEnabled(true);
} else {
add_service_button.setEnabled(false);
}
}
/**
* Handle changes to the text field
*/
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
/**
* Handle changes to the text field
*/
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
/**
* Listener to handle service list selection changes
*/
public void valueChanged(ListSelectionEvent e) {
if (service_list.getSelectedIndex() == -1) {
remove_service_button.setEnabled(false);
} else {
remove_service_button.setEnabled(true);
}
}
}
/**
* Class for showing the filter dialog
*/
class SOAPMonitorFilter implements ActionListener {
/**
* Private data
*/
private JDialog dialog = null;
private JPanel panel = null;
private JPanel buttons = null;
private JButton ok_button = null;
private JButton cancel_button = null;
private ServiceFilterPanel include_panel = null;
private ServiceFilterPanel exclude_panel = null;
private JPanel status_panel = null;
private JCheckBox status_box = null;
private EmptyBorder empty_border = null;
private EmptyBorder indent_border = null;
private JPanel status_options = null;
private ButtonGroup status_group = null;
private JRadioButton status_active = null;
private JRadioButton status_complete = null;
private Vector filter_include_list = null;
private Vector filter_exclude_list = null;
private boolean filter_active = false;
private boolean filter_complete = false;
private boolean ok_pressed = false;
/**
* Constructor
*/
public SOAPMonitorFilter() {
// By default, exclude NotificationService and
// EventViewerService messages
filter_exclude_list = new Vector();
filter_exclude_list.addElement("NotificationService");
filter_exclude_list.addElement("EventViewerService");
}
/**
* Get list of services to be included
*/
public Vector getFilterIncludeList() {
return filter_include_list;
}
/**
* Get list of services to be excluded
*/
public Vector getFilterExcludeList() {
return filter_exclude_list;
}
/**
* Check if filter active messages
*/
public boolean getFilterActive() {
return filter_active;
}
/**
* Check if filter complete messages
*/
public boolean getFilterComplete() {
return filter_complete;
}
/**
* Show the filter dialog
*/
public void showDialog() {
empty_border = new EmptyBorder(5,5,0,5);
indent_border = new EmptyBorder(5,25,5,5);
include_panel = new ServiceFilterPanel("Include messages based on target service:",
filter_include_list);
exclude_panel = new ServiceFilterPanel("Exclude messages based on target service:",
filter_exclude_list);
status_box = new JCheckBox("Filter messages based on status:");
status_box.addActionListener(this);
status_active = new JRadioButton("Active messages only");
status_active.setSelected(true);
status_active.setEnabled(false);
status_complete = new JRadioButton("Complete messages only");
status_complete.setEnabled(false);
status_group = new ButtonGroup();
status_group.add(status_active);
status_group.add(status_complete);
if (filter_active || filter_complete) {
status_box.setSelected(true);
status_active.setEnabled(true);
status_complete.setEnabled(true);
if (filter_complete) {
status_complete.setSelected(true);
}
}
status_options = new JPanel();
status_options.setLayout(new BoxLayout(status_options, BoxLayout.Y_AXIS));
status_options.add(status_active);
status_options.add(status_complete);
status_options.setBorder(indent_border);
status_panel = new JPanel();
status_panel.setLayout(new BorderLayout());
status_panel.add(status_box, BorderLayout.NORTH);
status_panel.add(status_options, BorderLayout.CENTER);
status_panel.setBorder(empty_border);
ok_button = new JButton("Ok");
ok_button.addActionListener(this);
cancel_button = new JButton("Cancel");
cancel_button.addActionListener(this);
buttons = new JPanel();
buttons.setLayout(new FlowLayout());
buttons.add(ok_button);
buttons.add(cancel_button);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(include_panel);
panel.add(exclude_panel);
panel.add(status_panel);
panel.add(buttons);
dialog = new JDialog();
dialog.setTitle("SOAP Monitor Filter");
dialog.setContentPane(panel);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.pack();
Dimension d = dialog.getToolkit().getScreenSize();
dialog.setLocation((d.width-dialog.getWidth())/2,
(d.height-dialog.getHeight())/2);
ok_pressed = false;
dialog.show();
}
/**
* Listener to handle button actions
*/
public void actionPerformed(ActionEvent e) {
// Check if the user pressed the ok button
if (e.getSource() == ok_button) {
filter_include_list = include_panel.getServiceList();
filter_exclude_list = exclude_panel.getServiceList();
if (status_box.isSelected()) {
filter_active = status_active.isSelected();
filter_complete = status_complete.isSelected();
} else {
filter_active = false;
filter_complete = false;
}
ok_pressed = true;
dialog.dispose();
}
// Check if the user pressed the cancel button
if (e.getSource() == cancel_button) {
dialog.dispose();
}
// Check if the user changed the status filter option
if (e.getSource() == status_box) {
status_active.setEnabled(status_box.isSelected());
status_complete.setEnabled(status_box.isSelected());
}
}
/**
* Check if the user pressed the ok button
*/
public boolean okPressed() {
return ok_pressed;
}
}
/**
* Text panel class that supports XML reflow
*/
class SOAPMonitorTextArea extends JTextArea {
/**
* Private data
*/
private boolean format = false;
private String original = "";
private String formatted = null;
/**
* Constructor
*/
public SOAPMonitorTextArea() {
}
/**
* Override setText to do formatting
*/
public void setText(String text) {
original = text;
formatted = null;
if (format) {
doFormat();
super.setText(formatted);
} else {
super.setText(original);
}
}
/**
* Turn reflow on or off
*/
public void setReflowXML(boolean reflow) {
format = reflow;
if (format) {
if (formatted == null) {
doFormat();
}
super.setText(formatted);
} else {
super.setText(original);
}
}
/**
* Reflow XML
*/
public void doFormat() {
Vector parts = new Vector();
char[] chars = original.toCharArray();
int index = 0;
int first = 0;
String part = null;
while (index < chars.length) {
// Check for start of tag
if (chars[index] == '<') {
// Did we have data before this tag?
if (first < index) {
part = new String(chars,first,index-first);
part = part.trim();
// Save non-whitespace data
if (part.length() > 0) {
parts.addElement(part);
}
}
// Save the start of tag
first = index;
}
// Check for end of tag
if (chars[index] == '>') {
// Save the tag
part = new String(chars,first,index-first+1);
parts.addElement(part);
first = index+1;
}
// Check for end of line
if ((chars[index] == '\n') || (chars[index] == '\r')) {
// Was there data on this line?
if (first < index) {
part = new String(chars,first,index-first);
part = part.trim();
// Save non-whitespace data
if (part.length() > 0) {
parts.addElement(part);
}
}
first = index+1;
}
index++;
}
// Reflow as XML
StringBuffer buf = new StringBuffer();
Object[] list = parts.toArray();
int indent = 0;
int pad = 0;
index = 0;
while (index < list.length) {
part = (String) list[index];
if (buf.length() == 0) {
// Just add first tag (should be XML header)
buf.append(part);
} else {
// All other parts need to start on a new line
buf.append('\n');
// If we're at an end tag then decrease indent
if (part.startsWith("</")) {
indent--;
}
// Add any indent
for (pad = 0; pad < indent; pad++) {
buf.append(" ");
}
// Add the tag or data
buf.append(part);
// If this is a start tag then increase indent
if (part.startsWith("<") &&
!part.startsWith("</") &&
!part.endsWith("/>")) {
indent++;
// Check for special <tag>data</tag> case
if ((index + 2) < list.length) {
part = (String) list[index+2];
if (part.startsWith("</")) {
part = (String) list[index+1];
if (!part.startsWith("<")) {
buf.append(part);
part = (String) list[index+2];
buf.append(part);
index = index + 2;
indent--;
}
}
}
}
}
index++;
}
formatted = new String(buf);
}
}
}
| 7,030 |
0 | Create_ds/axis-axis1-java/jetty-daemon/src/main/java/org/apache/axis/tools/daemon | Create_ds/axis-axis1-java/jetty-daemon/src/main/java/org/apache/axis/tools/daemon/jetty/WebAppDaemon.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.tools.daemon.jetty;
import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.resource.Resource;
import org.mortbay.resource.ResourceCollection;
/**
*
*
* @author Andreas Veithen
*/
public class WebAppDaemon implements Daemon {
private Server server;
public void init(DaemonContext daemonContext) throws DaemonInitException, Exception {
Options options = new Options();
{
Option option = new Option("p", true, "the HTTP port");
option.setArgName("port");
option.setRequired(true);
options.addOption(option);
}
{
Option option = new Option("r", true, "a list of resource directories");
option.setArgName("dirs");
option.setRequired(true);
options.addOption(option);
}
CommandLineParser parser = new GnuParser();
CommandLine cmdLine = parser.parse(options, daemonContext.getArguments());
server = new Server(Integer.parseInt(cmdLine.getOptionValue("p")));
WebAppContext context = new WebAppContext(server, null, "/");
String[] resourceDirs = cmdLine.getOptionValue("r").split(File.pathSeparator);
Resource[] resources = new Resource[resourceDirs.length];
for (int i=0; i<resourceDirs.length; i++) {
resources[i] = Resource.newResource(resourceDirs[i]);
}
context.setBaseResource(new ResourceCollection(resources));
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
}
public void destroy() {
server = null;
}
}
| 7,031 |
0 | Create_ds/axis-axis1-java/axis-model/src/test/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/test/java/org/apache/axis/model/wsdd/LoadTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.wsdd;
import java.io.File;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xml.sax.InputSource;
public class LoadTest extends TestCase {
private final File file;
public LoadTest(File file) {
this.file = file;
setName(file.getName());
}
protected void runTest() throws Throwable {
assertNotNull(WSDDUtil.load(new InputSource(file.toURL().toString())));
}
public static TestSuite suite() {
TestSuite suite = new TestSuite();
File[] files = new File("src/test/wsdd").listFiles();
for (int i=0; i<files.length; i++) {
File file = files[i];
if (file.isFile()) {
suite.addTest(new LoadTest(file));
}
}
return suite;
}
}
| 7,032 |
0 | Create_ds/axis-axis1-java/axis-model/src/test/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/test/java/org/apache/axis/model/wsdd/DeprecationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.wsdd;
import javax.xml.namespace.QName;
import junit.framework.TestCase;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.xml.sax.InputSource;
public class DeprecationTest extends TestCase {
public void testLanguageSpecificType() throws Exception {
Deployment deployment = WSDDUtil.load(new InputSource(DeprecationTest.class.getResource("languageSpecificType.wsdd").toString()));
Service service = (Service)deployment.getServices().get(0);
BeanMapping beanMapping = (BeanMapping)service.getBeanMappings().get(0);
assertEquals(new QName(WSDDConstants.URI_WSDD_JAVA, "test.rpc.Bean"), beanMapping.getType());
}
}
| 7,033 |
0 | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/util/AxisXMLResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.util;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl;
/**
* {@link XMLHelper} implementation that uses {@link AxisXMLHelper}.
*
* @author Andreas Veithen
*/
public class AxisXMLResource extends XMLResourceImpl {
/**
* Option to specify a namespace that will be ignored if it is used in an unqualified
* <tt>xsd:QName</tt> literal.
* <p>
* Axis 1.4 incorrectly assumes that <tt>xsd:QName</tt> literals that have no prefix don't
* belong to any namespace. This is incorrect: values of type <tt>xsd:QName</tt> are resolved in
* the same way as element names. An unqualified literal therefore belongs to the default
* namespace in scope where the <tt>xsd:QName</tt> appears.
* <p>
* Consider the following example:
*
* <pre>
* <deployment xmlns="http://xml.apache.org/axis/wsdd/"
* xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
* <transport name="http">
* <requestFlow>
* <handler type="URLMapper"/>
* <handler type="java:org.apache.axis.handlers.http.HTTPAuthHandler"/>
* </requestFlow>
* </transport>
* </deployment>
* </pre>
*
* If the <tt>type</tt> attribute is assumed to be of type <tt>xsd:QName</tt>, then the
* <tt>URLMapper</tt> literal actually resolves to
* <tt>{http://xml.apache.org/axis/wsdd/}URLMapper</tt>. However, Axis 1.4 incorrectly assumes
* that it has no namespace because it is unprefixed.
* <p>
* This option allows to preserve compatibility with Axis 1.4 by specifying a namespace that
* will be ignored if it is encountered in the resolution of a <tt>xsd:QName</tt> literal
* without prefix.
*/
public static final String OPTION_IGNORE_NAMESPACE_FOR_UNQUALIFIED_QNAME = "IGNORE_NAMESPACE_FOR_UNQUALIFIED_QNAME";
protected XMLHelper createXMLHelper() {
return new AxisXMLHelper(this);
}
}
| 7,034 |
0 | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/util/AxisXMLHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.util;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axis.constants.Style;
import org.apache.axis.constants.Use;
import org.apache.axis.model.soap.impl.SOAPPackageImpl;
import org.apache.axis.model.xml.impl.XmlPackageImpl;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EFactory;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl;
/**
* Custom {@link XMLHelper} that adds support for {@link QName}. This is necessary because we use an
* EMF version compatible with Java 1.4 and that version doesn't support {@link QName} (because it's
* not included in the JRE). Instead it uses its own class to represent QNames. Since Axis depends
* on {@link QName} anyway, we add support for it here.
*
* @author Andreas Veithen
*/
// TODO: this is actually not entirely correct; Axis may generate QNames that are not strictly valid (such as "ns:>fault") and they should be represented using a specific class
public class AxisXMLHelper extends XMLHelperImpl {
private String ignoreNamespaceForUnqualifiedQName;
public AxisXMLHelper(XMLResource resource) {
super(resource);
}
public void setOptions(Map options) {
super.setOptions(options);
ignoreNamespaceForUnqualifiedQName = (String)options.get(AxisXMLResource.OPTION_IGNORE_NAMESPACE_FOR_UNQUALIFIED_QNAME);
}
protected Object createFromString(EFactory eFactory, EDataType dataType, String value) {
if (dataType == XmlPackageImpl.eINSTANCE.getQName()) {
String prefix;
String localName;
int idx = value.indexOf(':');
if (idx == -1) {
prefix = "";
localName = value;
} else {
prefix = value.substring(0, idx);
localName = value.substring(idx+1);
}
String namespaceURI = getURI(prefix);
if (namespaceURI == null) {
if (prefix.length() == 0) {
namespaceURI = "";
} else {
throw new IllegalArgumentException("The prefix '" + prefix + "' is not declared for the QName '" + value + "'");
}
}
if (prefix.length() == 0 && namespaceURI.equals(ignoreNamespaceForUnqualifiedQName)) {
// TODO: emit warning here
// TODO: add unit test for this case
namespaceURI = "";
}
return new QName(namespaceURI, localName, prefix);
} else if (dataType == SOAPPackageImpl.eINSTANCE.getStyle()) {
return Style.getStyle(value);
} else if (dataType == SOAPPackageImpl.eINSTANCE.getUse()) {
return Use.getUse(value);
} else {
return super.createFromString(eFactory, dataType, value);
}
}
public String convertToString(EFactory factory, EDataType dataType, Object value) {
if (dataType == SOAPPackageImpl.eINSTANCE.getStyle()) {
return ((Style)value).getName();
} else if (dataType == SOAPPackageImpl.eINSTANCE.getUse()) {
return ((Use)value).getName();
} else {
return super.convertToString(factory, dataType, value);
}
}
protected String updateQNamePrefix(EFactory factory, EDataType dataType, Object value, boolean list) {
if (!list && value instanceof QName) {
QName qname = (QName)value;
String namespace = qname.getNamespaceURI();
if (namespace.length() == 0) {
return qname.getLocalPart();
} else {
EPackage ePackage = extendedMetaData.getPackage(namespace);
if (ePackage == null) {
ePackage = extendedMetaData.demandPackage(namespace);
}
String prefix = getPrefix(ePackage, true);
if (!packages.containsKey(ePackage)) {
packages.put(ePackage, prefix);
}
return prefix + ":" + qname.getLocalPart();
}
} else {
return super.updateQNamePrefix(factory, dataType, value, list);
}
}
}
| 7,035 |
0 | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/wsdd/WSDDExtendedMetaData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.wsdd;
import org.apache.axis.model.wsdd.impl.WSDDPackageImpl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.BasicExtendedMetaData;
final class WSDDExtendedMetaData extends BasicExtendedMetaData {
private static final EClass mapping = WSDDPackageImpl.eINSTANCE.getMapping();
public EStructuralFeature getAttribute(EClass eClass, String namespace, String name) {
if (mapping.isSuperTypeOf(eClass) && namespace == null && name.equals("languageSpecificType")) {
// TODO: emit warning
return mapping.getEStructuralFeature(WSDDPackageImpl.MAPPING__TYPE);
} else {
return super.getAttribute(eClass, namespace, name);
}
}
}
| 7,036 |
0 | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/wsdd/WSDDUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.wsdd;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.configuration.DefaultConfiguration;
import org.apache.axis.model.util.AxisXMLResource;
import org.apache.axis.model.wsdd.impl.WSDDPackageImpl;
import org.apache.commons.logging.Log;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.util.XMLProcessor;
import org.xml.sax.InputSource;
public final class WSDDUtil {
private static final Log log = LogFactory.getLog(WSDDUtil.class.getName());
private WSDDUtil() {}
public static Deployment load(InputSource is) throws IOException {
WSDDPackageImpl.eINSTANCE.eClass();
AxisXMLResource resource = new AxisXMLResource();
Map options = new HashMap();
options.put(XMLResource.OPTION_EXTENDED_META_DATA, new WSDDExtendedMetaData());
options.put(AxisXMLResource.OPTION_IGNORE_NAMESPACE_FOR_UNQUALIFIED_QNAME, WSDDPackageImpl.eNS_URI);
resource.load(is, options);
return (Deployment)resource.getContents().get(0);
}
/**
* Load the default Axis configuration. This method implements the same algorithm as
* {@link DefaultConfiguration}.
*
* @param cl
* the class loader to load the configuration from
* @param type
* the type of configuration (<tt>client</tt> or <tt>server</tt>)
* @return the default configuration
* @throws IOException
*/
public static Deployment buildDefaultConfiguration(ClassLoader cl, String type) throws IOException {
// Load the base configuration
String resourceName = "org/apache/axis/" + type + "/" + type + "-config.wsdd";
InputStream in = cl.getResourceAsStream(resourceName);
if (in == null) {
throw new IOException("Resource " + resourceName + " not found");
}
if (log.isDebugEnabled()) {
log.debug("Loading resource " + resourceName);
}
Deployment deployment;
try {
deployment = WSDDUtil.load(new InputSource(in));
} finally {
in.close();
}
// Discover and load additional default configuration fragments
resourceName = "META-INF/axis/default-" + type + "-config.wsdd";
Enumeration resources = cl.getResources(resourceName);
while (resources.hasMoreElements()) {
URL url = (URL)resources.nextElement();
if (log.isDebugEnabled()) {
log.debug("Loading " + url);
}
in = url.openStream();
try {
deployment.merge(WSDDUtil.load(new InputSource(in)));
} finally {
in.close();
}
}
return deployment;
}
public static void save(Deployment deployment, OutputStream out) throws IOException {
AxisXMLResource resource = new AxisXMLResource();
XMLProcessor processor = new XMLProcessor();
resource.getContents().add(deployment);
Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, "UTF-8");
processor.save(out, resource, options);
}
public static void save(Deployment deployment, Writer writer) throws IOException {
AxisXMLResource resource = new AxisXMLResource();
XMLProcessor processor = new XMLProcessor();
resource.getContents().add(deployment);
Map options = new HashMap();
options.put(XMLResource.OPTION_DECLARE_XML, Boolean.FALSE);
processor.save(writer, resource, options);
}
}
| 7,037 |
0 | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/wsdd | Create_ds/axis-axis1-java/axis-model/src/main/java/org/apache/axis/model/wsdd/impl/Helper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.model.wsdd.impl;
import java.util.Iterator;
import org.apache.axis.model.wsdd.Deployment;
import org.apache.axis.model.wsdd.GlobalConfiguration;
import org.apache.axis.model.wsdd.Parameter;
import org.apache.axis.model.wsdd.Parameterizable;
import org.apache.axis.model.wsdd.WSDDFactory;
final class Helper {
private Helper() {}
static void merge(Deployment that, Deployment other) {
// TODO: very naive implementation; need more fine grained merging
GlobalConfiguration otherGlobalConfiguration = other.getGlobalConfiguration();
if (otherGlobalConfiguration != null) {
that.setGlobalConfiguration(otherGlobalConfiguration);
}
that.getHandlers().addAll(other.getHandlers());
that.getTransports().addAll(other.getTransports());
that.getServices().addAll(other.getServices());
that.getTypeMappings().addAll(other.getTypeMappings());
that.getBeanMappings().addAll(other.getBeanMappings());
that.getArrayMappings().addAll(other.getArrayMappings());
}
static void setParameter(Parameterizable that, String name, String value) {
for (Iterator it = that.getParameters().iterator(); it.hasNext(); ) {
Parameter param = (Parameter)it.next();
if (name.equals(param.getName())) {
param.setValue(value);
return;
}
}
Parameter param = WSDDFactory.INSTANCE.createParameter();
param.setName(name);
param.setValue(value);
that.getParameters().add(param);
}
}
| 7,038 |
0 | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/providers/BSFProvider.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.providers;
import org.apache.axis.AxisFault;
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.components.script.Script;
import org.apache.axis.components.script.ScriptFactory;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCHeaderParam;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
import java.util.Vector;
public class BSFProvider extends BasicProvider {
protected static Log log =
LogFactory.getLog(BSFProvider.class.getName());
public static final String OPTION_LANGUAGE = "language";
public static final String OPTION_SRC = "src";
public static final String OPTION_SCRIPT = "script";
public void invoke(MessageContext msgContext) throws AxisFault {
try {
SOAPService service = msgContext.getService();
String language = (String) service.getOption(OPTION_LANGUAGE);
String scriptStr = (String) service.getOption(OPTION_SRC);
if (log.isDebugEnabled()) {
log.debug("Enter: BSFProvider.processMessage()");
}
OperationDesc operation = msgContext.getOperation();
Vector bodies = msgContext.getRequestMessage().getSOAPEnvelope().getBodyElements();
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("bodyElems00", "" + bodies.size()));
log.debug(Messages.getMessage("bodyIs00", "" + bodies.get(0)));
}
RPCElement body = null;
// Find the first "root" body element, which is the RPC call.
for (int bNum = 0; body == null && bNum < bodies.size(); bNum++) {
// If this is a regular old SOAPBodyElement, and it's a root,
// we're probably a non-wrapped doc/lit service. In this case,
// we deserialize the element, and create an RPCElement "wrapper"
// around it which points to the correct method.
// FIXME : There should be a cleaner way to do this...
if (!(bodies.get(bNum) instanceof RPCElement)) {
SOAPBodyElement bodyEl = (SOAPBodyElement) bodies.get(bNum);
// igors: better check if bodyEl.getID() != null
// to make sure this loop does not step on SOAP-ENC objects
// that follow the parameters! FIXME?
if (bodyEl.isRoot() && operation != null && bodyEl.getID() == null) {
ParameterDesc param = operation.getParameter(bNum);
// at least do not step on non-existent parameters!
if (param != null) {
Object val = bodyEl.getValueAsType(param.getTypeQName());
body = new RPCElement("",
operation.getName(),
new Object[]{val});
}
}
} else {
body = (RPCElement) bodies.get(bNum);
}
}
String methodName = body.getMethodName();
Vector args = body.getParams();
int numArgs = args.size();
Object[] argValues = new Object[numArgs];
// Put the values contained in the RPCParams into an array
// suitable for passing to java.lang.reflect.Method.invoke()
// Make sure we respect parameter ordering if we know about it
// from metadata, and handle whatever conversions are necessary
// (values -> Holders, etc)
for (int i = 0; i < numArgs; i++) {
RPCParam rpcParam = (RPCParam) args.get(i);
Object value = rpcParam.getObjectValue();
// first check the type on the paramter
ParameterDesc paramDesc = rpcParam.getParamDesc();
// if we found some type info try to make sure the value type is
// correct. For instance, if we deserialized a xsd:dateTime in
// to a Calendar and the service takes a Date, we need to convert
if (paramDesc != null && paramDesc.getJavaType() != null) {
// Get the type in the signature (java type or its holder)
Class sigType = paramDesc.getJavaType();
// Convert the value into the expected type in the signature
value = JavaUtils.convert(value,
sigType);
rpcParam.setObjectValue(value);
}
argValues[i] = value;
}
Script script = ScriptFactory.getScript();
Object result = script.run(language, service.getName(), scriptStr, methodName, argValues);
RPCElement resBody = new RPCElement(methodName + "Response");
resBody.setPrefix(body.getPrefix());
resBody.setNamespaceURI(body.getNamespaceURI());
resBody.setEncodingStyle(msgContext.getEncodingStyle());
Message resMsg = msgContext.getResponseMessage();
SOAPEnvelope resEnv;
// If we didn't have a response message, make sure we set one up
if (resMsg == null) {
resEnv = new SOAPEnvelope(msgContext.getSOAPConstants());
resMsg = new Message(resEnv);
msgContext.setResponseMessage(resMsg);
} else {
resEnv = resMsg.getSOAPEnvelope();
}
QName returnQName = operation.getReturnQName();
if (returnQName == null) {
returnQName = new QName("", methodName + "Return");
}
// For SOAP 1.2, add a result
if (msgContext.getSOAPConstants() ==
SOAPConstants.SOAP12_CONSTANTS) {
returnQName = Constants.QNAME_RPC_RESULT;
}
RPCParam param = new RPCParam(returnQName, result);
param.setParamDesc(operation.getReturnParamDesc());
if (!operation.isReturnHeader()) {
resBody.addParam(param);
} else {
resEnv.addHeader(new RPCHeaderParam(param));
}
resEnv.addBodyElement(resBody);
} catch (Exception e) {
entLog.debug(Messages.getMessage("toAxisFault00"), e);
throw AxisFault.makeFault(e);
}
}
public void initServiceDesc(SOAPService service, MessageContext msgContext)
throws AxisFault {
}
}
| 7,039 |
0 | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components/script/ScriptFactory.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.script;
import org.apache.axis.AxisProperties;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
/**
* This class implements a factory to instantiate an Script component.
* @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a>
* @since 2.0
*/
public class ScriptFactory {
protected static Log log =
LogFactory.getLog(ScriptFactory.class.getName());
static {
AxisProperties.setClassOverrideProperty(Script.class, "axis.Script");
AxisProperties.setClassDefaults(Script.class,
new String[]{
"org.apache.axis.components.script.BSF",
});
}
/**
* Get the Script implementation.
*/
public static Script getScript() {
Script script = (Script) AxisProperties.newInstance(Script.class);
log.debug("axis.Script: " + script.getClass().getName());
return script;
}
}
| 7,040 |
0 | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components/script/BSF.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.script;
import org.apache.bsf.BSFEngine;
import org.apache.bsf.BSFManager;
public class BSF implements Script {
public Object run(String language, String name, String scriptStr, String methodName, Object[] argValues)
throws Exception {
BSFManager manager = new BSFManager();
BSFEngine engine = manager.loadScriptingEngine(language);
manager.exec(language, "service script for '" +
name + "'", 0, 0, scriptStr);
Object result = engine.call(null, methodName, argValues);
return result;
}
}
| 7,041 |
0 | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/components/script/Script.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.script;
/**
* This interface defines a Script module functionality
* @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a>
* @since 2.0
*/
public interface Script {
public Object run(String language, String name, String scriptStr, String methodName, Object[] argValues)
throws Exception;
}
| 7,042 |
0 | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/deployment/wsdd | Create_ds/axis-axis1-java/axis-rt-provider-bsf/src/main/java/org/apache/axis/deployment/wsdd/providers/WSDDBsfProvider.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.deployment.wsdd.providers;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.Handler;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.deployment.wsdd.WSDDProvider;
import org.apache.axis.deployment.wsdd.WSDDService;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.providers.BSFProvider;
import java.io.IOException;
/**
*
*/
public class WSDDBsfProvider
extends WSDDProvider
{
public String getName() {
return WSDDConstants.PROVIDER_BSF;
}
public Handler newProviderInstance(WSDDService service,
EngineConfiguration registry)
throws Exception
{
Handler provider = new org.apache.axis.providers.BSFProvider();
String option = service.getParameter("language");
if (!option.equals("")) {
provider.setOption(BSFProvider.OPTION_LANGUAGE, option);
}
option = service.getParameter("src");
if (!option.equals("")) {
provider.setOption(BSFProvider.OPTION_SRC, option);
}
// !!! What to do here?
//option = XMLUtils.getInnerXMLString(prov);
if (!option.equals("")) {
provider.setOption(BSFProvider.OPTION_SCRIPT, option);
}
return provider;
}
/**
* Write this element out to a SerializationContext
*/
public void writeToContext(SerializationContext context)
throws IOException {
}
}
| 7,043 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/transport/http/CommonsHTTPSender.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.components.net.CommonsHTTPClientProperties;
import org.apache.axis.components.net.CommonsHTTPClientPropertiesFactory;
import org.apache.axis.components.net.TransportClientProperties;
import org.apache.axis.components.net.TransportClientPropertiesFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.soap.SOAP12Constants;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.NetworkUtils;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* This class uses Jakarta Commons's HttpClient to call a SOAP server.
*
* @author Davanum Srinivas (dims@yahoo.com)
* History: By Chandra Talluri
* Modifications done for maintaining sessions. Cookies needed to be set on
* HttpState not on MessageContext, since ttpMethodBase overwrites the cookies
* from HttpState. Also we need to setCookiePolicy on HttpState to
* CookiePolicy.COMPATIBILITY else it is defaulting to RFC2109Spec and adding
* Version information to it and tomcat server not recognizing it
*/
public class CommonsHTTPSender extends BasicHandler {
/** Field log */
protected static Log log =
LogFactory.getLog(CommonsHTTPSender.class.getName());
protected HttpConnectionManager connectionManager;
protected CommonsHTTPClientProperties clientProperties;
boolean httpChunkStream = true; //Use HTTP chunking or not.
public CommonsHTTPSender() {
initialize();
}
protected void initialize() {
MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();
this.clientProperties = CommonsHTTPClientPropertiesFactory.create();
cm.getParams().setDefaultMaxConnectionsPerHost(clientProperties.getMaximumConnectionsPerHost());
cm.getParams().setMaxTotalConnections(clientProperties.getMaximumTotalConnections());
// If defined, set the default timeouts
// Can be overridden by the MessageContext
if(this.clientProperties.getDefaultConnectionTimeout()>0) {
cm.getParams().setConnectionTimeout(this.clientProperties.getDefaultConnectionTimeout());
}
if(this.clientProperties.getDefaultSoTimeout()>0) {
cm.getParams().setSoTimeout(this.clientProperties.getDefaultSoTimeout());
}
this.connectionManager = cm;
}
/**
* invoke creates a socket connection, sends the request SOAP message and then
* reads the response SOAP message back from the SOAP server
*
* @param msgContext the messsage context
*
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
HttpMethodBase method = null;
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("enter00",
"CommonsHTTPSender::invoke"));
}
try {
URL targetURL =
new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
// no need to retain these, as the cookies/credentials are
// stored in the message context across multiple requests.
// the underlying connection manager, however, is retained
// so sockets get recycled when possible.
HttpClient httpClient = new HttpClient(this.connectionManager);
// the timeout value for allocation of connections from the pool
httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());
HostConfiguration hostConfiguration =
getHostConfiguration(httpClient, msgContext, targetURL);
boolean posting = true;
// If we're SOAP 1.2, allow the web method to be set from the
// MessageContext.
if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
if (webMethod != null) {
posting = webMethod.equals(HTTPConstants.HEADER_POST);
}
}
if (posting) {
Message reqMessage = msgContext.getRequestMessage();
method = new PostMethod(targetURL.toString());
// set false as default, addContetInfo can overwrite
method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
false);
addContextInfo(method, httpClient, msgContext, targetURL);
MessageRequestEntity requestEntity = null;
if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
} else {
requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
}
((PostMethod)method).setRequestEntity(requestEntity);
} else {
method = new GetMethod(targetURL.toString());
addContextInfo(method, httpClient, msgContext, targetURL);
}
String httpVersion =
msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
if (httpVersion != null) {
if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
method.getParams().setVersion(HttpVersion.HTTP_1_0);
}
// assume 1.1
}
// don't forget the cookies!
// Cookies need to be set on HttpState, since HttpMethodBase
// overwrites the cookies from HttpState
if (msgContext.getMaintainSession()) {
HttpState state = httpClient.getState();
method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
String host = hostConfiguration.getHost();
String path = targetURL.getPath();
boolean secure = hostConfiguration.getProtocol().isSecure();
fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
httpClient.setState(state);
}
int returnCode = httpClient.executeMethod(hostConfiguration, method, null);
String contentType =
getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
String contentLocation =
getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
String contentLength =
getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);
if ((returnCode > 199) && (returnCode < 300)) {
// SOAP return is OK - so fall through
} else if (msgContext.getSOAPConstants() ==
SOAPConstants.SOAP12_CONSTANTS) {
// For now, if we're SOAP 1.2, fall through, since the range of
// valid result codes is much greater
} else if ((contentType != null) && !contentType.equals("text/html")
&& ((returnCode > 499) && (returnCode < 600))) {
// SOAP Fault should be in here - so fall through
} else {
String statusMessage = method.getStatusText();
AxisFault fault = new AxisFault("HTTP",
"(" + returnCode + ")"
+ statusMessage, null,
null);
try {
fault.setFaultDetailString(
Messages.getMessage("return01",
"" + returnCode,
method.getResponseBodyAsString()));
fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
Integer.toString(returnCode));
throw fault;
} finally {
method.releaseConnection(); // release connection back to pool.
}
}
// wrap the response body stream so that close() also releases
// the connection back to the pool.
InputStream releaseConnectionOnCloseStream =
createConnectionReleasingInputStream(method);
Header contentEncoding =
method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
if (contentEncoding != null) {
if (contentEncoding.getValue().
equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
releaseConnectionOnCloseStream =
new GZIPInputStream(releaseConnectionOnCloseStream);
} else {
AxisFault fault = new AxisFault("HTTP",
"unsupported content-encoding of '"
+ contentEncoding.getValue()
+ "' found", null, null);
throw fault;
}
}
Message outMsg = new Message(releaseConnectionOnCloseStream,
false, contentType, contentLocation);
// Transfer HTTP headers of HTTP message to MIME headers of SOAP message
Header[] responseHeaders = method.getResponseHeaders();
MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
for (int i = 0; i < responseHeaders.length; i++) {
Header responseHeader = responseHeaders[i];
responseMimeHeaders.addHeader(responseHeader.getName(),
responseHeader.getValue());
}
outMsg.setMessageType(Message.RESPONSE);
msgContext.setResponseMessage(outMsg);
if (log.isDebugEnabled()) {
if (null == contentLength) {
log.debug("\n"
+ Messages.getMessage("no00", "Content-Length"));
}
log.debug("\n" + Messages.getMessage("xmlRecd00"));
log.debug("-----------------------------------------------");
log.debug(outMsg.getSOAPPartAsString());
}
// if we are maintaining session state,
// handle cookies (if any)
if (msgContext.getMaintainSession()) {
Header[] headers = method.getResponseHeaders();
for (int i = 0; i < headers.length; i++) {
if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
} else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
}
}
}
// always release the connection back to the pool if
// it was one way invocation
if (msgContext.isPropertyTrue("axis.one.way")) {
method.releaseConnection();
}
} catch (Exception e) {
log.debug(e);
throw AxisFault.makeFault(e);
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("exit00",
"CommonsHTTPSender::invoke"));
}
}
/**
* little helper function for cookies. fills up the message context with
* a string or an array of strings (if there are more than one Set-Cookie)
*
* @param cookieName
* @param cookie
* @param msgContext
*/
public void handleCookie(String cookieName, String cookie,
MessageContext msgContext) {
cookie = cleanupCookie(cookie);
int keyIndex = cookie.indexOf("=");
String key = (keyIndex != -1) ? cookie.substring(0, keyIndex) : cookie;
ArrayList cookies = new ArrayList();
Object oldCookies = msgContext.getProperty(cookieName);
boolean alreadyExist = false;
if(oldCookies != null) {
if(oldCookies instanceof String[]) {
String[] oldCookiesArray = (String[])oldCookies;
for(int i = 0; i < oldCookiesArray.length; i++) {
String anOldCookie = oldCookiesArray[i];
if (key != null && anOldCookie.indexOf(key) == 0) { // same cookie key
anOldCookie = cookie; // update to new one
alreadyExist = true;
}
cookies.add(anOldCookie);
}
} else {
String oldCookie = (String)oldCookies;
if (key != null && oldCookie.indexOf(key) == 0) { // same cookie key
oldCookie = cookie; // update to new one
alreadyExist = true;
}
cookies.add(oldCookie);
}
}
if (!alreadyExist) {
cookies.add(cookie);
}
if(cookies.size()==1) {
msgContext.setProperty(cookieName, cookies.get(0));
} else if (cookies.size() > 1) {
msgContext.setProperty(cookieName, cookies.toArray(new String[cookies.size()]));
}
}
/**
* Add cookies from message context
*
* @param msgContext
* @param state
* @param header
* @param host
* @param path
* @param secure
*/
private void fillHeaders(MessageContext msgContext, HttpState state, String header, String host, String path, boolean secure) {
Object ck1 = msgContext.getProperty(header);
if (ck1 != null) {
if (ck1 instanceof String[]) {
String [] cookies = (String[]) ck1;
for (int i = 0; i < cookies.length; i++) {
addCookie(state, cookies[i], host, path, secure);
}
} else {
addCookie(state, (String) ck1, host, path, secure);
}
}
}
/**
* add cookie to state
* @param state
* @param cookie
*/
private void addCookie(HttpState state, String cookie,String host, String path, boolean secure) {
int index = cookie.indexOf('=');
state.addCookie(new Cookie(host, cookie.substring(0, index),
cookie.substring(index + 1), path,
null, secure));
}
/**
* cleanup the cookie value.
*
* @param cookie initial cookie value
*
* @return a cleaned up cookie value.
*/
private String cleanupCookie(String cookie) {
cookie = cookie.trim();
// chop after first ; a la Apache SOAP (see HTTPUtils.java there)
int index = cookie.indexOf(';');
if (index != -1) {
cookie = cookie.substring(0, index);
}
return cookie;
}
protected HostConfiguration getHostConfiguration(HttpClient client,
MessageContext context,
URL targetURL) {
TransportClientProperties tcp =
TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or https
int port = targetURL.getPort();
boolean hostInNonProxyList =
isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());
HostConfiguration config = new HostConfiguration();
if (port == -1) {
if(targetURL.getProtocol().equalsIgnoreCase("https")) {
port = 443; // default port for https being 443
} else { // it must be http
port = 80; // default port for http being 80
}
}
if(hostInNonProxyList){
config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
} else {
if (tcp.getProxyHost().length() == 0 ||
tcp.getProxyPort().length() == 0) {
config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
} else {
if (tcp.getProxyUser().length() != 0) {
Credentials proxyCred =
new UsernamePasswordCredentials(tcp.getProxyUser(),
tcp.getProxyPassword());
// if the username is in the form "user\domain"
// then use NTCredentials instead.
int domainIndex = tcp.getProxyUser().indexOf("\\");
if (domainIndex > 0) {
String domain = tcp.getProxyUser().substring(0, domainIndex);
if (tcp.getProxyUser().length() > domainIndex + 1) {
String user = tcp.getProxyUser().substring(domainIndex + 1);
proxyCred = new NTCredentials(user,
tcp.getProxyPassword(),
tcp.getProxyHost(), domain);
}
}
client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
}
int proxyPort = new Integer(tcp.getProxyPort()).intValue();
config.setProxy(tcp.getProxyHost(), proxyPort);
}
}
return config;
}
/**
* Extracts info from message context.
*
* @param method Post method
* @param httpClient The client used for posting
* @param msgContext the message context
* @param tmpURL the url to post to.
*
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method,
HttpClient httpClient,
MessageContext msgContext,
URL tmpURL)
throws Exception {
// optionally set a timeout for the request
if (msgContext.getTimeout() != 0) {
/* ISSUE: these are not the same, but MessageContext has only one
definition of timeout */
// SO_TIMEOUT -- timeout for blocking reads
httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
// timeout for initial connection
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
}
// Get SOAPAction, default to ""
String action = msgContext.useSOAPAction()
? msgContext.getSOAPActionURI()
: "";
if (action == null) {
action = "";
}
Message msg = msgContext.getRequestMessage();
if (msg != null){
method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
msg.getContentType(msgContext.getSOAPConstants())));
}
method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION,
"\"" + action + "\""));
method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
String userID = msgContext.getUsername();
String passwd = msgContext.getPassword();
// if UserID is not part of the context, but is in the URL, use
// the one in the URL.
if ((userID == null) && (tmpURL.getUserInfo() != null)) {
String info = tmpURL.getUserInfo();
int sep = info.indexOf(':');
if ((sep >= 0) && (sep + 1 < info.length())) {
userID = info.substring(0, sep);
passwd = info.substring(sep + 1);
} else {
userID = info;
}
}
if (userID != null) {
Credentials proxyCred =
new UsernamePasswordCredentials(userID,
passwd);
// if the username is in the form "user\domain"
// then use NTCredentials instead.
int domainIndex = userID.indexOf("\\");
if (domainIndex > 0) {
String domain = userID.substring(0, domainIndex);
if (userID.length() > domainIndex + 1) {
String user = userID.substring(domainIndex + 1);
proxyCred = new NTCredentials(user,
passwd,
NetworkUtils.getLocalHostname(), domain);
}
}
httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
}
// add compression headers if needed
if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
HTTPConstants.COMPRESSION_GZIP);
}
if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING,
HTTPConstants.COMPRESSION_GZIP);
}
// Transfer MIME headers of SOAPMessage to HTTP headers.
MimeHeaders mimeHeaders = msg.getMimeHeaders();
if (mimeHeaders != null) {
for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader mimeHeader = (MimeHeader) i.next();
//HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
//Let's not duplicate them.
String headerName = mimeHeader.getName();
if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
|| headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
continue;
}
method.addRequestHeader(mimeHeader.getName(),
mimeHeader.getValue());
}
}
// process user defined headers for information.
Hashtable userHeaderTable =
(Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
if (userHeaderTable != null) {
for (Iterator e = userHeaderTable.entrySet().iterator();
e.hasNext();) {
Map.Entry me = (Map.Entry) e.next();
Object keyObj = me.getKey();
if (null == keyObj) {
continue;
}
String key = keyObj.toString().trim();
String value = me.getValue().toString().trim();
if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) &&
value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
true);
} else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
String val = me.getValue().toString();
if (null != val) {
httpChunkStream = JavaUtils.isTrue(val);
}
} else {
method.addRequestHeader(key, value);
}
}
}
}
/**
* Check if the specified host is in the list of non proxy hosts.
*
* @param host host name
* @param nonProxyHosts string containing the list of non proxy hosts
*
* @return true/false
*/
protected boolean isHostInNonProxyList(String host, String nonProxyHosts) {
if ((nonProxyHosts == null) || (host == null)) {
return false;
}
/*
* The http.nonProxyHosts system property is a list enclosed in
* double quotes with items separated by a vertical bar.
*/
StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|\"");
while (tokenizer.hasMoreTokens()) {
String pattern = tokenizer.nextToken();
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("match00",
new String[]{"HTTPSender",
host,
pattern}));
}
if (match(pattern, host, false)) {
return true;
}
}
return false;
}
/**
* Matches a string against a pattern. The pattern contains two special
* characters:
* '*' which means zero or more characters,
*
* @param pattern the (non-null) pattern to match against
* @param str the (non-null) string that must be matched against the
* pattern
* @param isCaseSensitive
*
* @return <code>true</code> when the string matches against the pattern,
* <code>false</code> otherwise.
*/
protected static boolean match(String pattern, String str,
boolean isCaseSensitive) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = false;
for (int i = 0; i < patArr.length; i++) {
if (patArr[i] == '*') {
containsStar = true;
break;
}
}
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = patArr[i];
if (isCaseSensitive && (ch != strArr[i])) {
return false; // Character mismatch
}
if (!isCaseSensitive
&& (Character.toUpperCase(ch)
!= Character.toUpperCase(strArr[i]))) {
return false; // Character mismatch
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ((ch = patArr[patIdxStart]) != '*'
&& (strIdxStart <= strIdxEnd)) {
if (isCaseSensitive && (ch != strArr[strIdxStart])) {
return false; // Character mismatch
}
if (!isCaseSensitive
&& (Character.toUpperCase(ch)
!= Character.toUpperCase(strArr[strIdxStart]))) {
return false; // Character mismatch
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while ((ch = patArr[patIdxEnd]) != '*' && (strIdxStart <= strIdxEnd)) {
if (isCaseSensitive && (ch != strArr[strIdxEnd])) {
return false; // Character mismatch
}
if (!isCaseSensitive
&& (Character.toUpperCase(ch)
!= Character.toUpperCase(strArr[strIdxEnd]))) {
return false; // Character mismatch
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while ((patIdxStart != patIdxEnd) && (strIdxStart <= strIdxEnd)) {
int patIdxTmp = -1;
for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
if (patArr[i] == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart + 1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patIdxStart - 1);
int strLength = (strIdxEnd - strIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = patArr[patIdxStart + j + 1];
if (isCaseSensitive
&& (ch != strArr[strIdxStart + i + j])) {
continue strLoop;
}
if (!isCaseSensitive && (Character
.toUpperCase(ch) != Character
.toUpperCase(strArr[strIdxStart + i + j]))) {
continue strLoop;
}
}
foundIdx = strIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
private static String getHeader(HttpMethodBase method, String headerName) {
Header header = method.getResponseHeader(headerName);
return (header == null) ? null : header.getValue().trim();
}
private InputStream createConnectionReleasingInputStream(final HttpMethodBase method) throws IOException {
return new FilterInputStream(method.getResponseBodyAsStream()) {
public void close() throws IOException {
try {
super.close();
} finally {
method.releaseConnection();
}
}
};
}
private static class MessageRequestEntity implements RequestEntity {
private HttpMethodBase method;
private Message message;
boolean httpChunkStream = true; //Use HTTP chunking or not.
public MessageRequestEntity(HttpMethodBase method, Message message) {
this.message = message;
this.method = method;
}
public MessageRequestEntity(HttpMethodBase method, Message message, boolean httpChunkStream) {
this.message = message;
this.method = method;
this.httpChunkStream = httpChunkStream;
}
public boolean isRepeatable() {
return true;
}
public void writeRequest(OutputStream out) throws IOException {
try {
this.message.writeTo(out);
} catch (SOAPException e) {
throw new IOException(e.getMessage());
}
}
protected boolean isContentLengthNeeded() {
return this.method.getParams().getVersion() == HttpVersion.HTTP_1_0 || !httpChunkStream;
}
public long getContentLength() {
if (isContentLengthNeeded()) {
try {
return message.getContentLength();
} catch (Exception e) {
}
}
return -1; /* -1 for chunked */
}
public String getContentType() {
return null; // a separate header is added
}
}
private static class GzipMessageRequestEntity extends MessageRequestEntity {
public GzipMessageRequestEntity(HttpMethodBase method, Message message) {
super(method, message);
}
public GzipMessageRequestEntity(HttpMethodBase method, Message message, boolean httpChunkStream) {
super(method, message, httpChunkStream);
}
public void writeRequest(OutputStream out) throws IOException {
if (cachedStream != null) {
cachedStream.writeTo(out);
} else {
GZIPOutputStream gzStream = new GZIPOutputStream(out);
super.writeRequest(gzStream);
gzStream.finish();
}
}
public long getContentLength() {
if(isContentLengthNeeded()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
writeRequest(baos);
cachedStream = baos;
return baos.size();
} catch (IOException e) {
// fall through to doing chunked.
}
}
return -1; // do chunked
}
private ByteArrayOutputStream cachedStream;
}
}
| 7,044 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components/net/CommonsHTTPClientProperties.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.net;
/**
* Interface implemented by classes seeking to configure the properties
* of the multi threaded connection pool used in the CommonsHTTPSender
* transport implementation.
*
* @author Eric Friedman
*/
public interface CommonsHTTPClientProperties {
/**
* Used to set the maximum number of connections that the pool can open
* for all hosts. Since connections imply sockets and sockets imply
* file descriptors, the setting you use must not exceed any limits
* your system imposes on the number of open file descriptors a
* single process may have.
*
* @return an integer > 1
*/
public int getMaximumTotalConnections();
/**
* Used to set the maximum number of connections that will be pooled
* for a given host. This setting is also constrained by
* the one returned from getMaximumTotalConnections.
*
* @return an integer > 1
*/
public int getMaximumConnectionsPerHost();
/**
* Used to set the amount of time, in milliseconds, spent waiting
* for an available connection from the pool. An exception is raised
* if the timeout is triggered.
*
* @return an integer > 1 OR 0 for infinite timeout
*/
public int getConnectionPoolTimeout();
/**
* Used to set the default amount of time, in milliseconds, spent waiting
* for a connection. This can be overridden by the MessageContext
*
* @return an integer >= 0
*/
public int getDefaultConnectionTimeout();
/**
* Used to set the default amount of time, in milliseconds, spent waiting
* for a reponse. This can be overridden by the MessageContext
*
* @return an integer >= 0
*/
public int getDefaultSoTimeout();
}
| 7,045 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components/net/CommonsHTTPClientPropertiesFactory.java | /*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.net;
import org.apache.axis.AxisProperties;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
/**
* @author Eric Friedman
*/
public class CommonsHTTPClientPropertiesFactory {
protected static Log log =
LogFactory.getLog(CommonsHTTPClientPropertiesFactory.class.getName());
private static CommonsHTTPClientProperties properties;
public static synchronized CommonsHTTPClientProperties create() {
if (properties == null) {
properties = (CommonsHTTPClientProperties)
AxisProperties.newInstance(CommonsHTTPClientProperties.class,
DefaultCommonsHTTPClientProperties.class);
}
return properties;
}
}
| 7,046 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-http-hc3/src/main/java/org/apache/axis/components/net/DefaultCommonsHTTPClientProperties.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.net;
import org.apache.axis.AxisProperties;
/**
* Default property set for the of the multi threaded connection pool
* used in the CommonsHTTPSender transport implementation. Values
* returned by this implementation are identical to the defaults for
* the Commons HTTPClient library itself, unless overridden with
* Axis properties.
*
* @author Eric Friedman
*/
public class DefaultCommonsHTTPClientProperties implements CommonsHTTPClientProperties {
/** the key for the Axis Property that controls the maximum total connections
allowed in the httpclient pool */
public static final String MAXIMUM_TOTAL_CONNECTIONS_PROPERTY_KEY =
"axis.http.client.maximum.total.connections";
/** the key for the Axis Property that controls the maximum connections
per host allowed by the httpclient pool */
public static final String MAXIMUM_CONNECTIONS_PER_HOST_PROPERTY_KEY =
"axis.http.client.maximum.connections.per.host";
/** the key for the Axis Property that sets the connection pool timeout
for the httpclient pool */
public static final String CONNECTION_POOL_TIMEOUT_KEY =
"axis.http.client.connection.pool.timeout";
/** the key for the Axis Property that sets the default connection timeout
for the httpclient, can be overriden by the MessageContext */
public static final String CONNECTION_DEFAULT_CONNECTION_TIMEOUT_KEY =
"axis.http.client.connection.default.connection.timeout";
/** the key for the Axis Property that sets the read timeout
for the httpclient */
public static final String CONNECTION_DEFAULT_SO_TIMEOUT_KEY =
"axis.http.client.connection.default.so.timeout";
/**
* Convert the value for <tt>property</tt> into an int or, if none is found,
* use the <tt>dephault</tt> value instead.
*
* @return an integer value
*/
protected final int getIntegerProperty(String property, String dephault) {
return Integer.parseInt(AxisProperties.getProperty(property, dephault));
}
/**
* Return the integer value associated with the property
* axis.http.client.maximum.total.connections or a default of 20.
*
* @return a whole integer
*/
public int getMaximumTotalConnections() {
int i = getIntegerProperty(MAXIMUM_TOTAL_CONNECTIONS_PROPERTY_KEY, "20");
if (i < 1) {
throw new IllegalStateException(MAXIMUM_TOTAL_CONNECTIONS_PROPERTY_KEY + " must be > 1");
}
return i;
}
/**
* Return the integer value associated with the property
* axis.http.client.maximum.connections.per.host or a default of 2.
*
* @return a whole integer
*/
public int getMaximumConnectionsPerHost() {
int i = getIntegerProperty(MAXIMUM_CONNECTIONS_PER_HOST_PROPERTY_KEY, "2");
if (i < 1) {
throw new IllegalStateException(MAXIMUM_CONNECTIONS_PER_HOST_PROPERTY_KEY + " must be > 1");
}
return i;
}
/**
* Return the integer value associated with the property
* axis.http.client.connection.pool.timeout or a default of 0.
*
* @return an integer >= 0
*/
public int getConnectionPoolTimeout() {
int i = getIntegerProperty(CONNECTION_POOL_TIMEOUT_KEY, "0");
if (i < 0) {
throw new IllegalStateException(CONNECTION_POOL_TIMEOUT_KEY + " must be >= 0");
}
return i;
}
/**
* Return the integer value associated with the property
* axis.http.client.connection.default.connection.timeout or a default of 0.
*
* @return an integer >= 0
*/
public int getDefaultConnectionTimeout() {
int i = getIntegerProperty(CONNECTION_DEFAULT_CONNECTION_TIMEOUT_KEY, "0");
if (i < 0) {
throw new IllegalStateException(CONNECTION_DEFAULT_CONNECTION_TIMEOUT_KEY + " must be >= 0");
}
return i;
}
/**
* Return the integer value associated with the property
* axis.http.client.connection.default.so.timeout or a default of 0.
*
* @return an integer >= 0
*/
public int getDefaultSoTimeout() {
int i = getIntegerProperty(CONNECTION_DEFAULT_SO_TIMEOUT_KEY, "0");
if (i < 0) {
throw new IllegalStateException(CONNECTION_DEFAULT_SO_TIMEOUT_KEY + " must be >= 0");
}
return i;
}
}
| 7,047 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/Functions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Locale;
import javax.el.FunctionMapper;
public class Functions extends FunctionMapper {
public Method resolveFunction(String prefix, String localName) {
if (prefix.equals("fn")) {
for (Method method : Functions.class.getMethods()) {
if (Modifier.isStatic(method.getModifiers()) && method.getName().equals(localName)) {
return method;
}
}
}
return null;
}
public static String toUpperCase(String s) {
return s.toUpperCase(Locale.ENGLISH);
}
} | 7,048 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/Variables.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.util.HashMap;
import java.util.Map;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Variables extends VariableMapper {
private static final Log log = LogFactory.getLog(Variables.class);
private final Map<String,ValueExpression> variables = new HashMap<String,ValueExpression>();
public <T> void bind(String name, Class<T> clazz, T value) {
if (log.isDebugEnabled()) {
log.debug("Binding variable: " + name + "=" + value);
}
variables.put(name, new ValueExpressionLiteral<T>(clazz, value));
}
public ValueExpression resolveVariable(String name) {
return variables.get(name);
}
public ValueExpression setVariable(String name, ValueExpression valueExpression) {
return (variables.put(name, valueExpression));
}
} | 7,049 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/Context.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import javax.el.BeanELResolver;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.FunctionMapper;
import javax.el.VariableMapper;
public class Context extends ELContext {
private final BeanELResolver resolver = new BeanELResolver();
private final FunctionMapper functionMapper = new Functions();
private final Variables variables;
public Context(Variables variables) {
this.variables = variables;
}
@Override
public ELResolver getELResolver() {
return resolver;
}
@Override
public FunctionMapper getFunctionMapper() {
return functionMapper;
}
@Override
public VariableMapper getVariableMapper() {
return variables;
}
}
| 7,050 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/MockPostHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class MockPostHandler extends SOAPHandler implements InitializingBean {
private static final Log log = LogFactory.getLog(MockPostHandler.class);
private List<MessageProcessor> requestProcessors;
private List<Exchange> exchanges;
private Set<String> supportedContentTypes;
public void setRequestProcessors(List<MessageProcessor> requestProcessors) {
this.requestProcessors = requestProcessors;
}
public void setExchanges(List<Exchange> exchanges) {
this.exchanges = exchanges;
}
public void afterPropertiesSet() throws Exception {
supportedContentTypes = new HashSet<String>();
for (Exchange exchange : exchanges) {
supportedContentTypes.add(exchange.getRequestContentType());
}
}
@Override
protected void handleSOAPRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
if (!httpRequest.getMethod().equals("POST")) {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "This endpoint only supports POST requests");
return;
}
String requestContentTypeHeader = httpRequest.getContentType();
if (requestContentTypeHeader == null) {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "No Content-Type header");
return;
}
MimeType requestContentType;
try {
requestContentType = new MimeType(requestContentTypeHeader);
} catch (MimeTypeParseException ex) {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Content-Type header: " + ex.getMessage());
return;
}
String requestBaseContentType = requestContentType.getBaseType().toLowerCase(Locale.ENGLISH);
if (!supportedContentTypes.contains(requestBaseContentType)) {
httpResponse.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Only " + supportedContentTypes + " are supported");
return;
}
String charset = requestContentType.getParameter(Constants.CHARSET_PARAM);
Document requestDocument;
try {
requestDocument = DOMUtil.parse(httpRequest.getInputStream(), charset);
} catch (SAXException ex) {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unparsable request " + ex.getMessage());
return;
}
if (charset == null) {
charset = requestDocument.getXmlEncoding();
if (log.isDebugEnabled()) {
log.debug("Setting charset from request entity: " + charset);
}
}
Element request = requestDocument.getDocumentElement();
DOMUtil.removeWhitespace(request);
if (requestProcessors != null) {
for (MessageProcessor processor : requestProcessors) {
if (log.isDebugEnabled()) {
log.debug("Executing message processor " + processor);
}
processor.process(request);
}
}
Element responseMessage = null;
for (Exchange exchange : exchanges) {
if (exchange.getRequestContentType().equals(requestBaseContentType)) {
responseMessage = exchange.matchRequest(request);
if (responseMessage != null) {
break;
}
}
}
if (responseMessage == null) {
httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Don't know how to respond");
return;
}
MimeType responseContentType;
try {
responseContentType = new MimeType(SOAPUtil.getContentType(responseMessage));
} catch (MimeTypeParseException ex) {
throw new ServletException("Unexpected exception", ex);
}
responseContentType.setParameter(Constants.CHARSET_PARAM, charset);
httpResponse.setContentType(responseContentType.toString());
Transformer transformer;
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException ex) {
throw new ServletException("Unexpected exception", ex);
}
transformer.setOutputProperty(OutputKeys.ENCODING, charset);
try {
transformer.transform(new DOMSource(responseMessage), new StreamResult(httpResponse.getOutputStream()));
} catch (TransformerException ex) {
throw new ServletException(ex);
}
}
}
| 7,051 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/MustUnderstandNormalizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MustUnderstandNormalizer implements MessageProcessor {
private static final Log log = LogFactory.getLog(MustUnderstandNormalizer.class);
public void process(Element message) {
if (SOAPConstants.SOAP12_ENV_NAMESPACE.equals(message.getNamespaceURI())
&& message.getLocalName().equals("Envelope")) {
log.debug("Found SOAP 1.2 envelope");
NodeList children = message.getChildNodes();
for (int i=0, l=children.getLength(); i<l; i++) {
Node child = children.item(i);
if (child instanceof Element) {
Element childElement = (Element)child;
if (SOAPConstants.SOAP12_ENV_NAMESPACE.equals(childElement.getNamespaceURI())
&& childElement.getLocalName().equals("Header")) {
processSOAPHeader(childElement);
break;
}
}
}
}
}
private void processSOAPHeader(Element header) {
NodeList children = header.getChildNodes();
for (int i=0, l=children.getLength(); i<l; i++) {
Node child = children.item(i);
if (child instanceof Element) {
processHeaderElement((Element)child);
}
}
}
private void processHeaderElement(Element header) {
if (log.isDebugEnabled()) {
log.debug("Found header: uri=" + header.getNamespaceURI() + "; name=" + header.getLocalName());
}
Attr muAttr = header.getAttributeNodeNS(SOAPConstants.SOAP12_ENV_NAMESPACE, "mustUnderstand");
if (muAttr != null) {
String value = muAttr.getValue();
if (value.equals("0") || value.equals("false")) {
log.debug("Removing unnecessary mustUnderstand attribute");
header.removeAttributeNode(muAttr);
} else if (value.equals("true")) {
log.debug("Normalizing mustUnderstand attribute value");
muAttr.setValue("1");
}
}
}
}
| 7,052 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/MockGetHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.w3c.dom.Element;
public class MockGetHandler extends SOAPHandler implements InitializingBean {
private static final Log log = LogFactory.getLog(MockGetHandler.class);
private Resource response;
private Element responseMessage;
private String responseContentType;
public void setResponse(Resource response) {
this.response = response;
}
public void afterPropertiesSet() throws Exception {
responseMessage = DOMUtil.parse(response).getDocumentElement();
DOMUtil.removeWhitespace(responseMessage);
responseContentType = SOAPUtil.getContentType(responseMessage);
}
@Override
protected void handleSOAPRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
if (!httpRequest.getMethod().equals("GET")) {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "This endpoint only supports GET requests");
return;
}
httpResponse.setContentType(responseContentType + "; " + Constants.CHARSET_PARAM + "=UTF-8");
Transformer transformer;
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException ex) {
throw new ServletException("Unexpected exception", ex);
}
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
if (log.isDebugEnabled()) {
log.debug("Returning " + response);
}
try {
transformer.transform(new DOMSource(responseMessage), new StreamResult(httpResponse.getOutputStream()));
} catch (TransformerException ex) {
throw new ServletException(ex);
}
}
}
| 7,053 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/SOAPConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
public final class SOAPConstants {
private SOAPConstants() {}
public static final String SOAP11_ENV_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/";
public static final String SOAP12_ENV_NAMESPACE = "http://www.w3.org/2003/05/soap-envelope";
}
| 7,054 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/DOMUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public final class DOMUtil {
private final static DocumentBuilder documentBuilder;
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
try {
documentBuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new Error(ex);
}
}
private DOMUtil() {}
public static Document newDocument() {
return documentBuilder.newDocument();
}
public static Document parse(Resource resource) throws SAXException, IOException {
InputStream in = resource.getInputStream();
try {
return documentBuilder.parse(in);
} finally {
in.close();
}
}
public static Document parse(InputStream in, String encoding) throws SAXException, IOException {
InputSource is = new InputSource(in);
is.setEncoding(encoding);
return documentBuilder.parse(is);
}
public static void removeWhitespace(Element element) {
Node previousChild = null;
Node child = element.getFirstChild();
while (child != null) {
Node nextChild = child.getNextSibling();
switch (child.getNodeType()) {
case Node.TEXT_NODE:
if (previousChild != null || nextChild != null) {
String content = ((Text)child).getData();
boolean isWhitespace = true;
for (int i=0; i<content.length(); i++) {
// Non whitespace characters below 32 are illegal in XML 1.0 and would
// have been rejected by the parser.
if (content.charAt(i) > ' ') {
isWhitespace = false;
break;
}
}
if (isWhitespace) {
element.removeChild(child);
}
}
break;
case Node.ELEMENT_NODE:
removeWhitespace((Element)child);
}
previousChild = child;
child = nextChild;
}
}
}
| 7,055 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/SerializationContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import com.sun.msv.datatype.SerializationContext;
public class SerializationContextImpl implements SerializationContext {
public String getNamespacePrefix(String namespaceURI) {
// TODO Auto-generated method stub
return null;
}
}
| 7,056 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/ValueExpressionLiteral.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import javax.el.ELContext;
import javax.el.PropertyNotWritableException;
import javax.el.ValueExpression;
import org.apache.commons.lang.ObjectUtils;
public final class ValueExpressionLiteral<T> extends ValueExpression {
private static final long serialVersionUID = -3847213439349942695L;
private final Class<T> clazz;
private final T value;
public ValueExpressionLiteral(Class<T> clazz, T value) {
if (clazz == null || value == null) {
throw new IllegalArgumentException();
}
this.clazz = clazz;
this.value = value;
}
public Object getValue(ELContext context) {
return this.value;
}
public void setValue(ELContext context, Object value) {
throw new PropertyNotWritableException();
}
public boolean isReadOnly(ELContext context) {
return true;
}
public Class<?> getType(ELContext context) {
return clazz;
}
public Class<?> getExpectedType() {
return clazz;
}
public String getExpressionString() {
throw new UnsupportedOperationException();
}
public boolean equals(Object obj) {
return (obj instanceof ValueExpressionLiteral && equals((ValueExpressionLiteral<?>)obj));
}
public boolean equals(ValueExpressionLiteral<?> ve) {
return ve != null && ObjectUtils.equals(value, ve.value);
}
public int hashCode() {
return value.hashCode();
}
public boolean isLiteralText() {
return true;
}
}
| 7,057 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/SOAPHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.web.HttpRequestHandler;
public abstract class SOAPHandler implements HttpRequestHandler {
private Resource wsdl;
public void setWsdl(Resource wsdl) {
this.wsdl = wsdl;
}
public final void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getMethod().equals("GET") && request.getQueryString() != null && request.getQueryString().equalsIgnoreCase("wsdl")) {
if (wsdl == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "No WSDL available for this service");
} else {
response.setContentType("text/xml");
InputStream in = wsdl.getInputStream();
try {
IOUtils.copy(in, response.getOutputStream());
} finally {
in.close();
}
}
} else {
handleSOAPRequest(request, response);
}
}
protected abstract void handleSOAPRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
| 7,058 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/ValidationContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import org.relaxng.datatype.ValidationContext;
public class ValidationContextImpl implements ValidationContext {
public String getBaseUri() {
// TODO Auto-generated method stub
return null;
}
public boolean isNotation(String arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean isUnparsedEntity(String arg0) {
// TODO Auto-generated method stub
return false;
}
public String resolveNamespacePrefix(String arg0) {
// TODO Auto-generated method stub
return null;
}
}
| 7,059 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/SOAPUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import org.w3c.dom.Element;
public final class SOAPUtil {
private SOAPUtil() {}
public static String getContentType(Element envelope) {
String namespaceURI = envelope.getNamespaceURI();
if (SOAPConstants.SOAP12_ENV_NAMESPACE.equals(namespaceURI)) {
return "application/soap+xml";
} else if (SOAPConstants.SOAP11_ENV_NAMESPACE.equals(namespaceURI)) {
return "text/xml";
} else {
return null;
}
}
}
| 7,060 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/MessageProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import org.w3c.dom.Element;
public interface MessageProcessor {
void process(Element message);
}
| 7,061 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/Exchange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
import java.util.ArrayList;
import java.util.List;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.relaxng.datatype.DatatypeException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import com.sun.msv.datatype.xsd.DatatypeFactory;
import com.sun.msv.datatype.xsd.XSDatatype;
/**
* Describes a request-response message exchange supported by a {@link MockPostHandler}. An instance
* of this class matches a given request against an expected request (specified by a
* {@link Resource}), and if the request matches, returns a configurable response (specified by
* another {@link Resource}). The configured request and response messages can contain simple
* template constructs. During request matching, these templates are used to infer variable values,
* and these variables can then be substituted in the response. The following template constructs
* are supported:
* <ol>
* <li><code>${<i>expression</i>}</code> appearing in text nodes. In a request message, the
* expression must be a simple variable expression (e.g. <code>${myInputParameter}</code>). During
* request matching, the value of the variable will be set to the content of the text node in the
* actual request. In a response message, the expression can be any EL expression as defined by the
* <code>javax.el</code> API.
* <li>Element templates in the form
* <code><t:element t:name="${var}" xmlns:t="http://axis.apache.org/mock/template">...</t:element></code>.
* In a request message this template matches any element, and the {@link QName} of that element
* is assigned to the variable specified by the <tt>t:name</tt> attribute. In a response message the
* template element will be substituted by an element with the given name. Note that the template
* element may have children as well as additional attributes (not in the
* <tt>http://axis.apache.org/mock/template</tt> namespace). They are matched/copied as any other
* node.
* </ol>
*/
public class Exchange implements InitializingBean {
private static final String MOCK_NS = "http://axis.apache.org/mock/template";
private static final Log log = LogFactory.getLog(Exchange.class);
private Resource request;
private Resource response;
private Element requestMessage;
private Element responseMessage;
private String requestContentType;
public void setRequest(Resource request) {
this.request = request;
}
public void setResponse(Resource response) {
this.response = response;
}
public void afterPropertiesSet() throws Exception {
requestMessage = DOMUtil.parse(request).getDocumentElement();
DOMUtil.removeWhitespace(requestMessage);
requestContentType = SOAPUtil.getContentType(requestMessage);
responseMessage = DOMUtil.parse(response).getDocumentElement();
DOMUtil.removeWhitespace(responseMessage);
}
public String getRequestContentType() {
return requestContentType;
}
public Element matchRequest(Element root) {
if (log.isDebugEnabled()) {
log.debug("Attempting to match " + request);
}
Variables inferredVariables = new Variables();
if (match(requestMessage, root, inferredVariables)) {
log.debug("Message matches");
Element clonedResponseMessage = (Element)DOMUtil.newDocument().importNode(responseMessage, true);
ExpressionFactory factory = ExpressionFactory.newInstance();
Context context = new Context(inferredVariables);
substituteVariables(clonedResponseMessage, factory, context);
return clonedResponseMessage;
} else {
log.debug("Message doesn't match");
return null;
}
}
private void getLocation(StringBuilder buffer, Element element) {
Node parent = element.getParentNode();
if (parent instanceof Element) {
getLocation(buffer, (Element)parent);
buffer.append('/');
}
String prefix = element.getPrefix();
if (prefix != null) {
buffer.append(prefix);
buffer.append(':');
}
buffer.append(element.getLocalName());
}
/**
* Get the location of the given element as a pseudo XPath expression for use in log messages.
*
* @param element
* the element
* @return the location of the element
*/
private String getLocation(Element element) {
StringBuilder buffer = new StringBuilder();
getLocation(buffer, element);
return buffer.toString();
}
private String getLocation(Attr attr) {
StringBuilder buffer = new StringBuilder();
getLocation(buffer, attr.getOwnerElement());
buffer.append("/@");
String prefix = attr.getPrefix();
if (prefix != null) {
buffer.append(prefix);
buffer.append(':');
}
buffer.append(attr.getLocalName());
return buffer.toString();
}
private boolean match(Element expected, Element actual, Variables inferredVariables) {
String namespaceURI = expected.getNamespaceURI();
String localName = expected.getLocalName();
String attributesVariableName;
// Check if the element in the actual request is a template construct
if (MOCK_NS.equals(namespaceURI)) {
if (localName.equals("element")) {
inferredVariables.bind(checkVariable(expected.getAttributeNS(MOCK_NS, "name")),
QName.class, new QName(actual.getNamespaceURI(), actual.getLocalName()));
Attr attributesAttr = expected.getAttributeNodeNS(MOCK_NS, "attributes");
if (attributesAttr == null) {
attributesVariableName = null;
} else {
attributesVariableName = checkVariable(attributesAttr.getValue());
if (attributesVariableName == null) {
log.error("Expected variable at " + getLocation(attributesAttr));
return false;
}
}
} else {
log.error("Unexpected template element " + localName);
return false;
}
} else {
// Compare local name and namespace URI
if (!ObjectUtils.equals(localName, actual.getLocalName())) {
if (log.isDebugEnabled()) {
log.debug("Local name mismatch: expected=" + expected.getLocalName() + "; actual=" + actual.getLocalName());
}
return false;
}
if (!ObjectUtils.equals(namespaceURI, actual.getNamespaceURI())) {
if (log.isDebugEnabled()) {
log.debug("Namespace mismatch: expected=" + expected.getNamespaceURI() + "; actual=" + actual.getNamespaceURI());
}
return false;
}
attributesVariableName = null;
}
// Compare attributes
NamedNodeMap expectedAttributes = expected.getAttributes();
NamedNodeMap actualAttributes = actual.getAttributes();
// Check that all expected attributes are present and have matching values
for (int i=0; i<expectedAttributes.getLength(); i++) {
Attr expectedAttribute = (Attr)expectedAttributes.item(i);
String attrNamespaceURI = expectedAttribute.getNamespaceURI();
// Ignore namespace declarations and attributes used in template constructs
if (!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrNamespaceURI)
&& !MOCK_NS.equals(attrNamespaceURI)) {
Attr actualAttribute = (Attr)actualAttributes.getNamedItemNS(attrNamespaceURI, expectedAttribute.getLocalName());
if (actualAttribute == null) {
if (log.isDebugEnabled()) {
log.debug("Attribute " + getLocation(expectedAttribute) + " not found in actual request");
}
return false;
}
if (!actualAttribute.getValue().equals(expectedAttribute.getValue())) {
if (log.isDebugEnabled()) {
log.debug("Attribute value mismatch at " + getLocation(expectedAttribute)
+ ": expected=" + expectedAttribute.getValue()
+ "; actual=" + actualAttribute.getValue());
}
return false;
}
}
}
if (attributesVariableName == null) {
// Check that there are no unexpected attributes
for (int i=0, l=actualAttributes.getLength(); i<l; i++) {
Attr actualAttribute = (Attr)actualAttributes.item(i);
String attrNamespaceURI = actualAttribute.getNamespaceURI();
if (!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrNamespaceURI) &&
expectedAttributes.getNamedItemNS(attrNamespaceURI, actualAttribute.getLocalName()) == null) {
if (log.isDebugEnabled()) {
log.debug("Unexpected attribute at " + getLocation(expected) + ": uri=" + actualAttribute.getNamespaceURI()
+ "; name=" + actualAttribute.getLocalName());
}
return false;
}
}
} else {
List<Attr> attributes = new ArrayList<Attr>();
for (int i=0, l=actualAttributes.getLength(); i<l; i++) {
Attr actualAttribute = (Attr)actualAttributes.item(i);
String attrNamespaceURI = actualAttribute.getNamespaceURI();
if (!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrNamespaceURI) &&
expectedAttributes.getNamedItemNS(attrNamespaceURI, actualAttribute.getLocalName()) == null) {
attributes.add(actualAttribute);
}
}
inferredVariables.bind(attributesVariableName, Attr[].class, attributes.toArray(new Attr[attributes.size()]));
}
// Compare children
NodeList expectedChildren = expected.getChildNodes();
NodeList actualChildren = actual.getChildNodes();
int expectedChildrenLength = expectedChildren.getLength();
int actualChildrenLength = actualChildren.getLength();
if (expectedChildrenLength == 1) {
Node firstExpectedChild = expectedChildren.item(0);
if (firstExpectedChild.getNodeType() == Node.ELEMENT_NODE && MOCK_NS.equals(firstExpectedChild.getNamespaceURI()) && firstExpectedChild.getLocalName().equals("value")) {
if (actualChildrenLength == 0) {
return matchValue((Element)firstExpectedChild, "", inferredVariables);
} else if (actualChildrenLength == 1) {
Node firstActualChild = actualChildren.item(0);
if (firstActualChild.getNodeType() == Node.TEXT_NODE) {
return matchValue((Element)firstExpectedChild, ((Text)firstActualChild).getData(), inferredVariables);
} else {
if (log.isDebugEnabled()) {
log.debug("Unexpected child type at " + getLocation(expected) + ": expected a text child");
}
return false;
}
} else {
if (log.isDebugEnabled()) {
log.debug("Unexpected content at " + getLocation(expected) + ": expected a single text child");
}
return false;
}
}
}
if (expectedChildrenLength != actualChildrenLength) {
if (log.isDebugEnabled()) {
log.debug("Children count mismatch at " + getLocation(expected) + ": expected=" + expectedChildrenLength + "; actual=" + actualChildrenLength);
}
return false;
}
for (int i=0; i<expectedChildrenLength; i++) {
Node expectedChild = expectedChildren.item(i);
Node actualChild = actualChildren.item(i);
if (expectedChild.getNodeType() != actualChild.getNodeType()) {
if (log.isDebugEnabled()) {
log.debug("Child type mismatch");
}
return false;
}
switch (expectedChild.getNodeType()) {
case Node.ELEMENT_NODE:
if (!match((Element)expectedChild, (Element)actualChild, inferredVariables)) {
return false;
}
break;
case Node.TEXT_NODE:
String expectedContent = ((Text)expectedChild).getData();
String actualContent = ((Text)actualChild).getData();
if (!expectedContent.equals(actualContent)) {
if (log.isDebugEnabled()) {
log.debug("Text content mismatch at " + getLocation(expected)
+ ": expected=" + expectedContent + "; actual=" + actualContent);
}
return false;
}
break;
default:
if (log.isDebugEnabled()) {
log.debug("Unexpected node type " + expectedChild.getNodeType());
}
throw new IllegalStateException("Unexpected node type");
}
}
return true;
}
private <T> void castAndBindVariable(Variables variables, String name, Class<T> clazz, Object value) {
variables.bind(name, clazz, clazz.cast(value));
}
private String checkVariable(String text) {
if (text.startsWith("${") && text.endsWith("}")) {
return text.substring(2, text.length()-1);
} else {
return null;
}
}
private void substituteVariables(Element element, ExpressionFactory expressionFactory, ELContext context) {
Node child = element.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element)child;
if (MOCK_NS.equals(childElement.getNamespaceURI())) {
if (childElement.getLocalName().equals("value")) {
Text text = element.getOwnerDocument().createTextNode(substituteValue(childElement, expressionFactory, context));
element.replaceChild(text, child);
child = text;
}
// TODO: throw exception if an unknown element is encountered
} else {
substituteVariables(childElement, expressionFactory, context);
}
}
child = child.getNextSibling();
}
}
private boolean matchValue(Element element, String text, Variables inferredVariables) {
// TODO: null checks
Attr expressionAttr = element.getAttributeNodeNS(null, "expression");
Attr typeAttr = element.getAttributeNodeNS(null, "type");
String varName = checkVariable(expressionAttr.getValue());
XSDatatype type;
try {
type = DatatypeFactory.getTypeByName(typeAttr.getValue());
} catch (DatatypeException ex) {
// TODO: define a proper exception here
throw new RuntimeException(ex);
}
Object value = type.createJavaObject(text, new ValidationContextImpl());
if (value == null) {
if (log.isDebugEnabled()) {
log.debug("'" + text + "' is not a valid lexical value for type " + type.getName());
}
return false;
} else {
castAndBindVariable(inferredVariables, varName, (Class<?>)type.getJavaObjectType(), value);
return true;
}
}
private String substituteValue(Element element, ExpressionFactory expressionFactory, ELContext context) {
// TODO: null checks
Attr expressionAttr = element.getAttributeNodeNS(null, "expression");
Attr typeAttr = element.getAttributeNodeNS(null, "type");
XSDatatype type;
try {
type = DatatypeFactory.getTypeByName(typeAttr.getValue());
} catch (DatatypeException ex) {
// TODO: define a proper exception here
throw new RuntimeException(ex);
}
Object value = expressionFactory.createValueExpression(context, expressionAttr.getValue(), type.getJavaObjectType()).getValue(context);
return type.serializeJavaObject(value, new SerializationContextImpl());
}
}
| 7,062 |
0 | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop | Create_ds/axis-axis1-java/interop-mock/src/main/java/org/apache/axis/test/interop/mock/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.test.interop.mock;
public final class Constants {
private Constants() {}
public static final String CHARSET_PARAM = "charset";
}
| 7,063 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/QuitHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
import javax.xml.rpc.server.ServletEndpointContext;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.utils.Admin;
/**
* Handler that looks for the {@link MessageContext#QUIT_REQUESTED} flag set by {@link Admin} and
* initiates the shutdown procedure if the flag is set.
* <p>
* Note: this is an internal class that should not be used by application code.
*
* @author Andreas Veithen
*/
// Must be public so that the Axis core can load it
public final class QuitHandler extends BasicHandler {
public static final String QUIT_LISTENER = QuitListener.class.getName();
public void invoke(MessageContext msgContext) throws AxisFault {
if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
ServletEndpointContext sec = ((ServletEndpointContext)msgContext.getProperty(Constants.MC_SERVLET_ENDPOINT_CONTEXT));
((QuitListener)sec.getServletContext().getAttribute(QUIT_LISTENER)).requestQuit();
}
}
}
| 7,064 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/LimitSessionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
import java.util.Iterator;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.mortbay.jetty.servlet.AbstractSessionManager;
import org.mortbay.jetty.servlet.HashSessionManager;
/**
* {@link HashSessionManager} extension that limits the number of concurrently active session.
*
* @author Andreas Veithen
*/
final class LimitSessionManager extends HashSessionManager {
// This is only needed to get access to some protected methods/fields.
class Session extends HashSessionManager.Session {
private static final long serialVersionUID = -6648322281268846583L;
Session(HttpServletRequest request) {
super(request);
}
long accessed() {
return _accessed;
}
protected void timeout() {
super.timeout();
}
}
private final int maxSessions;
private ScheduledExecutorService executor;
LimitSessionManager(int maxSessions) {
this.maxSessions = maxSessions;
}
public void doStart() throws Exception {
super.doStart();
executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleWithFixedDelay(new Runnable() {
public void run() {
scavenge();
}
}, 5, 5, TimeUnit.SECONDS);
}
protected AbstractSessionManager.Session newSession(HttpServletRequest request) {
return new Session(request);
}
void scavenge() {
while (true) {
Session sessionToRemove = null;
synchronized (this) {
if (_sessions.size() <= maxSessions) {
break;
}
long minAccessed = Long.MAX_VALUE;
for (Iterator it = _sessions.values().iterator(); it.hasNext(); ) {
Session session = (Session)it.next();
long accessed = session.accessed();
if (accessed < minAccessed) {
minAccessed = accessed;
sessionToRemove = session;
}
}
}
sessionToRemove.timeout();
}
}
public void doStop() throws Exception {
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
super.doStop();
}
}
| 7,065 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/ServerException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
public class ServerException extends Exception {
private static final long serialVersionUID = 2996112474203025829L;
public ServerException(Throwable cause) {
super(cause);
}
}
| 7,066 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/StandaloneAxisServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.SessionManager;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.HashSessionManager;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.servlet.ServletMapping;
import org.mortbay.jetty.servlet.SessionHandler;
import org.mortbay.resource.Resource;
import org.mortbay.resource.ResourceCollection;
/**
* Jetty based stand-alone Axis server.
*
* @author Andreas Veithen
*/
public final class StandaloneAxisServer {
private int port;
private File workDir;
private int maxSessions = -1;
private File[] jwsDirs;
private Server server;
private QuitListener quitListener;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public File getWorkDir() {
return workDir;
}
public void setWorkDir(File workDir) {
this.workDir = workDir;
}
public int getMaxSessions() {
return maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public File[] getJwsDirs() {
return jwsDirs == null ? null : (File[])jwsDirs.clone();
}
public void setJwsDirs(File[] jwsDirs) {
this.jwsDirs = jwsDirs == null ? null : (File[])jwsDirs.clone();
}
public void init() throws ServerException {
StandaloneAxisServlet servlet = new StandaloneAxisServlet();
List resources = new ArrayList();
// Add the work dir as a resource so that Axis can create its server-config.wsdd file there
new File(workDir, "WEB-INF").mkdir();
try {
resources.add(Resource.newResource(workDir.getAbsolutePath()));
} catch (IOException ex) {
throw new ServerException(ex);
}
if (jwsDirs != null) {
for (int i=0; i<jwsDirs.length; i++) {
try {
resources.add(Resource.newResource(jwsDirs[i].getAbsolutePath()));
} catch (IOException ex) {
throw new ServerException(ex);
}
}
}
server = new Server(port);
server.setGracefulShutdown(1000);
Context context = new Context(server, "/axis");
context.setBaseResource(new ResourceCollection((Resource[])resources.toArray(new Resource[resources.size()])));
SessionManager sessionManager;
if (maxSessions == -1) {
sessionManager = new HashSessionManager();
} else {
sessionManager = new LimitSessionManager(maxSessions);
}
context.setSessionHandler(new SessionHandler(sessionManager));
quitListener = new QuitListener();
context.setAttribute(QuitHandler.QUIT_LISTENER, quitListener);
ServletHandler servletHandler = context.getServletHandler();
ServletHolder axisServletHolder = new ServletHolder(servlet);
axisServletHolder.setName("AxisServlet");
servletHandler.addServlet(axisServletHolder);
{
ServletMapping mapping = new ServletMapping();
mapping.setServletName("AxisServlet");
mapping.setPathSpec("/services/*");
servletHandler.addServletMapping(mapping);
}
{
ServletMapping mapping = new ServletMapping();
mapping.setServletName("AxisServlet");
mapping.setPathSpec("/servlet/AxisServlet");
servletHandler.addServletMapping(mapping);
}
if (jwsDirs != null && jwsDirs.length > 0) {
ServletMapping mapping = new ServletMapping();
mapping.setServletName("AxisServlet");
mapping.setPathSpec("*.jws");
servletHandler.addServletMapping(mapping);
}
}
public void start() throws ServerException {
try {
server.start();
} catch (Exception ex) {
throw new ServerException(ex);
}
}
public void awaitQuitRequest() throws InterruptedException {
quitListener.awaitQuitRequest();
}
public void stop() throws ServerException {
try {
server.stop();
} catch (Exception ex) {
throw new ServerException(ex);
}
}
}
| 7,067 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/QuitListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
/**
* Used to trigger the shutdown of the stand-alone server.
*
* @author Andreas Veithen
*/
final class QuitListener {
private boolean quit;
synchronized void requestQuit() {
quit = true;
notifyAll();
}
synchronized void awaitQuitRequest() throws InterruptedException {
while (!quit) {
wait();
}
}
}
| 7,068 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/StandaloneAxisServlet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.axis.WSDDEngineConfiguration;
import org.apache.axis.deployment.wsdd.WSDDDeployment;
import org.apache.axis.deployment.wsdd.WSDDDocument;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.http.AxisServlet;
import org.apache.axis.utils.XMLUtils;
/**
* Extends {@link AxisServlet} to register the {@link QuitHandler}.
*
* @author Andreas Veithen
*/
final class StandaloneAxisServlet extends AxisServlet {
private final List/*<URL>*/ wsddUrls;
public StandaloneAxisServlet() {
wsddUrls = new ArrayList();
wsddUrls.add(StandaloneAxisServlet.class.getResource("quit-handler-deploy.wsdd"));
}
public void init() throws ServletException {
super.init();
try {
AxisServer engine = getEngine();
WSDDDeployment registry = ((WSDDEngineConfiguration)engine.getConfig()).getDeployment();
for (Iterator it = wsddUrls.iterator(); it.hasNext(); ) {
URL url = (URL)it.next();
WSDDDocument wsdd = new WSDDDocument(XMLUtils.newDocument(url.toExternalForm()));
wsdd.deploy(registry);
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
| 7,069 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/cli/ConfiguratorException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone.cli;
public class ConfiguratorException extends Exception {
private static final long serialVersionUID = 664045878448812254L;
public ConfiguratorException(Throwable cause) {
super(cause);
}
public ConfiguratorException(String message) {
super(message);
}
}
| 7,070 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/cli/Main.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone.cli;
import java.io.PrintWriter;
import org.apache.axis.server.standalone.ServerException;
import org.apache.axis.server.standalone.StandaloneAxisServer;
/**
* Main class to run the stand-alone server from the command line.
*
* @author Andreas Veithen
*/
public class Main {
public static void main(String[] args) {
StandaloneAxisServer server = new StandaloneAxisServer();
if (args.length == 0) {
Configurator.INSTANCE.printHelp(new PrintWriter(System.out), Main.class.getName());
return;
}
try {
Configurator.INSTANCE.configure(server, args);
} catch (ConfiguratorException ex) {
System.err.println(ex.getMessage());
System.exit(1);
return; // Make compiler happy
}
try {
server.init();
server.start();
try {
server.awaitQuitRequest();
} catch (InterruptedException ex) {
// Just continue and stop the server
}
server.stop();
} catch (ServerException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
| 7,071 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/cli/Configurator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone.cli;
import java.io.File;
import java.io.PrintWriter;
import org.apache.axis.server.standalone.StandaloneAxisServer;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public final class Configurator {
public static final Configurator INSTANCE = new Configurator();
private final Options options;
private Configurator() {
options = new Options();
{
Option option = new Option("p", true, "the HTTP port");
option.setArgName("port");
option.setRequired(true);
options.addOption(option);
}
{
Option option = new Option("w", true, "the work directory");
option.setArgName("dir");
option.setRequired(true);
options.addOption(option);
}
{
Option option = new Option("j", true, "a list of directories to look up JWS files from");
option.setArgName("dirs");
options.addOption(option);
}
{
Option option = new Option("m", true, "the maximum number of concurrently active sessions");
option.setArgName("count");
options.addOption(option);
}
}
public void printHelp(PrintWriter pw, String app) {
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(pw, 100, app, options);
formatter.printOptions(pw, 100, options, 1, 2);
pw.flush();
}
public void configure(StandaloneAxisServer server, String[] args) throws ConfiguratorException {
CommandLineParser parser = new GnuParser();
CommandLine cmdLine;
try {
cmdLine = parser.parse(options, args);
} catch (ParseException ex) {
throw new ConfiguratorException(ex.getMessage());
}
server.setPort(Integer.parseInt(cmdLine.getOptionValue("p")));
server.setWorkDir(new File(cmdLine.getOptionValue("w")));
if (cmdLine.hasOption("m")) {
server.setMaxSessions(Integer.parseInt(cmdLine.getOptionValue("m")));
}
if (cmdLine.hasOption("j")) {
String[] jwsDirStrings = cmdLine.getOptionValue("j").split(File.pathSeparator);
File[] jwsDirs = new File[jwsDirStrings.length];
for (int i=0; i<jwsDirStrings.length; i++) {
jwsDirs[i] = new File(jwsDirStrings[i]);
}
server.setJwsDirs(jwsDirs);
}
}
}
| 7,072 |
0 | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone | Create_ds/axis-axis1-java/axis-standalone-server/src/main/java/org/apache/axis/server/standalone/daemon/AxisServerDaemon.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis.server.standalone.daemon;
import org.apache.axis.server.standalone.StandaloneAxisServer;
import org.apache.axis.server.standalone.cli.Configurator;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
/**
* {@link Daemon} implementation that runs the stand-alone Axis server.
*
* @author Andreas Veithen
*/
public class AxisServerDaemon implements Daemon {
private StandaloneAxisServer server;
public void init(DaemonContext context) throws DaemonInitException, Exception {
server = new StandaloneAxisServer();
Configurator.INSTANCE.configure(server, context.getArguments());
server.init();
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
}
public void destroy() {
server = null;
}
}
| 7,073 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/namespace/QName.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 javax.xml.namespace;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* <code>QName</code> class represents the value of a qualified name
* as specified in <a href="http://www.w3.org/TR/xmlschema-2/#QName">XML
* Schema Part2: Datatypes specification</a>.
* <p>
* The value of a QName contains a <b>namespaceURI</b>, a <b>localPart</b> and a
* <b>prefix</b>. The localPart provides the local part of the qualified name.
* The namespaceURI is a URI reference identifying the namespace.
*
* @version 1.1
*/
public class QName implements Serializable {
/** Comment/shared empty <code>String</code>. */
private static final String emptyString = "".intern();
private String namespaceURI;
private String localPart;
private String prefix;
/**
* Constructor for the QName.
*
* @param localPart local part of the QName
*/
public QName(String localPart) {
this(emptyString, localPart, emptyString);
}
/**
* Constructor for the QName.
*
* @param namespaceURI namespace URI for the QName
* @param localPart local part of the QName.
*/
public QName(String namespaceURI, String localPart) {
this(namespaceURI, localPart, emptyString);
}
/**
* Constructor for the QName.
*
* @param namespaceURI Namespace URI for the QName
* @param localPart Local part of the QName.
* @param prefix Prefix of the QName.
*/
public QName(String namespaceURI, String localPart, String prefix) {
this.namespaceURI = (namespaceURI == null)
? emptyString
: namespaceURI.intern();
if (localPart == null) {
throw new IllegalArgumentException("invalid QName local part");
} else {
this.localPart = localPart.intern();
}
if (prefix == null) {
throw new IllegalArgumentException("invalid QName prefix");
} else {
this.prefix = prefix.intern();
}
}
/**
* Gets the namespace URI for this QName.
*
* @return namespace URI
*/
public String getNamespaceURI() {
return namespaceURI;
}
/**
* Gets the local part for this QName.
*
* @return the local part
*/
public String getLocalPart() {
return localPart;
}
/**
* Gets the prefix for this QName.
*
* @return the prefix
*/
public String getPrefix() {
return prefix;
}
/**
* Returns a string representation of this QName.
*
* @return a string representation of the QName
*/
public String toString() {
return ((namespaceURI == emptyString)
? localPart
: '{' + namespaceURI + '}' + localPart);
}
/**
* Tests this QName for equality with another object.
* <p>
* If the given object is not a QName or is null then this method
* returns <tt>false</tt>.
* <p>
* For two QNames to be considered equal requires that both
* localPart and namespaceURI must be equal. This method uses
* <code>String.equals</code> to check equality of localPart
* and namespaceURI. Any class that extends QName is required
* to satisfy this equality contract.
* <p>
* This method satisfies the general contract of the <code>Object.equals</code> method.
*
* @param obj the reference object with which to compare
*
* @return <code>true</code> if the given object is identical to this
* QName: <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof QName)) {
return false;
}
if ((namespaceURI == ((QName) obj).namespaceURI)
&& (localPart == ((QName) obj).localPart)) {
return true;
}
return false;
}
/**
* Returns a QName holding the value of the specified String.
* <p>
* The string must be in the form returned by the QName.toString()
* method, i.e. "{namespaceURI}localPart", with the "{namespaceURI}"
* part being optional.
* <p>
* This method doesn't do a full validation of the resulting QName.
* In particular, it doesn't check that the resulting namespace URI
* is a legal URI (per RFC 2396 and RFC 2732), nor that the resulting
* local part is a legal NCName per the XML Namespaces specification.
*
* @param s the string to be parsed
* @throws java.lang.IllegalArgumentException If the specified String cannot be parsed as a QName
* @return QName corresponding to the given String
*/
public static QName valueOf(String s) {
if ((s == null) || s.equals("")) {
throw new IllegalArgumentException("invalid QName literal");
}
if (s.charAt(0) == '{') {
int i = s.indexOf('}');
if (i == -1) {
throw new IllegalArgumentException("invalid QName literal");
}
if (i == s.length() - 1) {
throw new IllegalArgumentException("invalid QName literal");
} else {
return new QName(s.substring(1, i), s.substring(i + 1));
}
} else {
return new QName(s);
}
}
/**
* Returns a hash code value for this QName object. The hash code
* is based on both the localPart and namespaceURI parts of the
* QName. This method satisfies the general contract of the
* <code>Object.hashCode</code> method.
*
* @return a hash code value for this Qname object
*/
public int hashCode() {
return namespaceURI.hashCode() ^ localPart.hashCode();
}
/**
* Ensure that deserialization properly interns the results.
* @param in the ObjectInputStream to be read
* @throws IOException if there was a failure in the object input stream
* @throws ClassNotFoundException if the class of any sub-objects could
* not be found
*/
private void readObject(ObjectInputStream in) throws
IOException, ClassNotFoundException {
in.defaultReadObject();
namespaceURI = namespaceURI.intern();
localPart = localPart.intern();
prefix = prefix.intern();
}
}
| 7,074 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/ServiceException.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 javax.xml.rpc;
/**
* The <code>javax.xml.rpc.ServiceException</code> is thrown from the
* methods in the <code>javax.xml.rpc.Service</code> interface and
* <code>ServiceFactory</code> class.
*
*
* @version 1.0
*/
public class ServiceException extends Exception {
// fixme: could we refactor this to use the jdk1.4 exception wrapping stuff?
/** The cause of this exception. */
Throwable cause;
/**
* Constructs a new exception with <code>null</code> as its
* detail message. The cause is not initialized.
*/
public ServiceException() {}
/**
* Constructs a new exception with the specified detail
* message. The cause is not initialized.
*
* @param message The detail message which is later
* retrieved using the <code>getMessage</code> method
*/
public ServiceException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail
* message and cause.
*
* @param message the detail message which is later retrieved
* using the <code>getMessage</code> method
* @param cause the cause which is saved for the later
* retrieval throw by the <code>getCause</code>
* method
*/
public ServiceException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
/**
* Constructs a new exception with the specified cause
* and a detail message of <tt>(cause==null ? null :
* cause.toString())</tt> (which typically contains the
* class and detail message of <tt>cause</tt>).
*
* @param cause the cause which is saved for the later
* retrieval throw by the getCause method.
* (A <tt>null</tt> value is permitted, and
* indicates that the cause is nonexistent or
* unknown.)
*/
public ServiceException(Throwable cause) {
super( (cause == null) ? null : cause.toString() );
this.cause = cause;
}
/**
* Gets the linked cause.
*
* @return the cause of this Exception or <code>null</code>
* if the cause is noexistent or unknown
*/
public Throwable getLinkedCause() {
return cause;
}
}
| 7,075 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/NamespaceConstants.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 javax.xml.rpc;
/**
* Constants used in JAX-RPC for namespace prefixes and URIs.
*
* @version 1.0
*/
public class NamespaceConstants {
// fixme: we should have a private constructor and/or be final
/**
* Constructor NamespaceConstants.
*/
public NamespaceConstants() {}
/** Namespace prefix for SOAP Envelope. */
public static final String NSPREFIX_SOAP_ENVELOPE = "soapenv";
/** Namespace prefix for SOAP Encoding. */
public static final String NSPREFIX_SOAP_ENCODING = "soapenc";
/** Namespace prefix for XML schema XSD. */
public static final String NSPREFIX_SCHEMA_XSD = "xsd";
/** Namespace prefix for XML Schema XSI. */
public static final String NSPREFIX_SCHEMA_XSI = "xsi";
/** Nameapace URI for SOAP 1.1 Envelope. */
public static final String NSURI_SOAP_ENVELOPE =
"http://schemas.xmlsoap.org/soap/envelope/";
/** Nameapace URI for SOAP 1.1 Encoding. */
public static final String NSURI_SOAP_ENCODING =
"http://schemas.xmlsoap.org/soap/encoding/";
/** Nameapace URI for SOAP 1.1 next actor role. */
public static final String NSURI_SOAP_NEXT_ACTOR =
"http://schemas.xmlsoap.org/soap/actor/next";
/** Namespace URI for XML Schema XSD. */
public static final String NSURI_SCHEMA_XSD =
"http://www.w3.org/2001/XMLSchema";
/** Namespace URI for XML Schema XSI. */
public static final String NSURI_SCHEMA_XSI =
"http://www.w3.org/2001/XMLSchema-instance";
}
| 7,076 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/Stub.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.xml.rpc;
import java.util.Iterator;
/**
* The interface <code>javax.xml.rpc.Stub</code> is the common base interface
* for the stub classes. All generated stub classes are required to
* implement the <code>javax.xml.rpc.Stub</code> interface. An instance
* of a stub class represents a client side proxy or stub instance for
* the target service endpoint.
*
* <p>The <code>javax.xml.rpc.Stub</code> interface provides an
* extensible property mechanism for the dynamic configuration of
* a stub instance.
*
* @version 1.0
*/
public interface Stub {
// Constants for the standard properties
/**
* Standard property: User name for authentication.
* <p>Type: java.lang.String
*/
public static final String USERNAME_PROPERTY = Call.USERNAME_PROPERTY;
/**
* Standard property: Password for authentication.
* <p>Type: java.lang.String
*/
public static final String PASSWORD_PROPERTY = Call.PASSWORD_PROPERTY;
/**
* Standard property: Target service endpoint address. The
* URI scheme for the endpoint address specification must
* correspond to the protocol/transport binding for this
* stub class.
* <p>Type: java.lang.String
*/
public static final String ENDPOINT_ADDRESS_PROPERTY =
"javax.xml.rpc.service.endpoint.address";
/**
* Standard property: This boolean property is used by a service
* client to indicate whether or not it wants to participate in
* a session with a service endpoint. If this property is set to
* true, the service client indicates that it wants the session
* to be maintained. If set to false, the session is not maintained.
* The default value for this property is false.
* <p>Type: java.lang.Boolean
*/
public static final String SESSION_MAINTAIN_PROPERTY =
Call.SESSION_MAINTAIN_PROPERTY;
/**
* Sets the name and value of a configuration property
* for this Stub instance. If the Stub instances contains
* a value of the same property, the old value is replaced.
* <p>Note that the <code>_setProperty</code> method may not
* perform validity check on a configured property value. An
* example is the standard property for the target service
* endpoint address that is not checked for validity in the
* <code>_setProperty</code> method.
* In this case, stub configuration errors are detected at
* the remote method invocation.
*
* @param name Name of the configuration property
* @param value Value of the property
* @throws JAXRPCException <ul>
* <li>If an optional standard property name is
* specified, however this Stub implementation
* class does not support the configuration of
* this property.
* <li>If an invalid or unsupported property name is
* specified or if a value of mismatched property
* type is passed.
* <li>If there is any error in the configuration of
* a valid property.
* </ul>
*/
public void _setProperty(String name, Object value);
/**
* Gets the value of a specific configuration property.
*
* @param name Name of the property whose value is to be
* retrieved
* @return Value of the configuration property
* @throws JAXRPCException if an invalid or
* unsupported property name is passed.
*/
public Object _getProperty(String name);
/**
* Returns an <code>Iterator</code> view of the names of the properties
* that can be configured on this stub instance.
*
* @return Iterator for the property names of the type
* <code>java.lang.String</code>
*/
public Iterator _getPropertyNames();
} // interface Stub
| 7,077 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/ParameterMode.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 javax.xml.rpc;
/**
* The <code>javax.xml.rpc.ParameterMode</code> is a type-safe
* enumeration for parameter mode. This class is used in the
* <code>Call</code>API to specify parameter passing modes.
*
* @version 1.0
*/
public class ParameterMode {
/** Mode name. */
private final String mode;
/** The mode is 'IN'. */
public static final ParameterMode IN = new ParameterMode("IN");
/** The mode is 'INOUT'. */
public static final ParameterMode INOUT = new ParameterMode("INOUT");
/** The mode is 'OUT'. */
public static final ParameterMode OUT = new ParameterMode("OUT");
/**
* Make a new mode.
*
* @param mode name for the mode
*/
private ParameterMode(String mode) {
this.mode = mode;
}
public String toString() {
return mode;
}
}
| 7,078 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/FactoryFinder.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 javax.xml.rpc;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* This code is designed to implement the pluggability
* feature and is designed to both compile and run on JDK version 1.1 and
* later. The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
*
* This class is duplicated for each subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXRPC
* API.
*/
class FactoryFinder {
/** Set to true for debugging. */
private static final boolean debug = false;
private static void debugPrintln(String msg) {
if (debug) {
System.err.println("JAXRPC: " + msg);
}
}
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*
* @return the <code>ClassLoader</code>
* @throws ConfigurationError if this class is unable to work with the
* host JDK
*/
private static ClassLoader findClassLoader()
throws ConfigurationError
{
Method m = null;
try {
m = Thread.class.getMethod("getContextClassLoader", null);
} catch (NoSuchMethodException e) {
// Assume that we are running JDK 1.1, use the current ClassLoader
debugPrintln("assuming JDK 1.1");
return FactoryFinder.class.getClassLoader();
}
try {
return (ClassLoader) m.invoke(Thread.currentThread(), null);
} catch (IllegalAccessException e) {
// assert(false)
throw new ConfigurationError("Unexpected IllegalAccessException",
e);
} catch (InvocationTargetException e) {
// assert(e.getTargetException() instanceof SecurityException)
throw new ConfigurationError("Unexpected InvocationTargetException",
e);
}
}
/**
* Create an instance of a class using the specified
* <code>ClassLoader</code>, or if that fails from the
* <code>ClassLoader</code> that loaded this class.
*
* @param className the name of the class to instantiate
* @param classLoader a <code>ClassLoader</code> to load the class from
*
* @return a new <code>Object</code> that is an instance of the class of
* the given name from the given class loader
* @throws ConfigurationError if the class could not be found or
* instantiated
*/
private static Object newInstance(String className,
ClassLoader classLoader)
throws ConfigurationError
{
try {
if (classLoader != null) {
try {
return classLoader.loadClass(className).newInstance ();
} catch (ClassNotFoundException x) {
// try again
}
}
return Class.forName(className).newInstance();
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception FactoryFinder.ConfigurationError
*
* Package private so this code can be shared.
*/
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
debugPrintln("debug is on");
ClassLoader classLoader = findClassLoader();
// Use the system property first
try {
String systemProp =
System.getProperty( factoryId );
if( systemProp!=null) {
debugPrintln("found system property " + systemProp);
return newInstance(systemProp, classLoader);
}
} catch (SecurityException se) {
}
// try to read from $java.home/lib/xml.properties
try {
String javah=System.getProperty( "java.home" );
String configFile = javah + File.separator +
"lib" + File.separator + "jaxrpc.properties";
File f=new File( configFile );
if( f.exists()) {
Properties props=new Properties();
props.load( new FileInputStream(f));
String factoryClassName = props.getProperty(factoryId);
debugPrintln("found java.home property " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
} catch(Exception ex ) {
if( debug ) ex.printStackTrace();
}
String serviceId = "META-INF/services/" + factoryId;
// try to find services in CLASSPATH
try {
InputStream is=null;
if (classLoader == null) {
is=ClassLoader.getSystemResourceAsStream( serviceId );
} else {
is=classLoader.getResourceAsStream( serviceId );
}
if( is!=null ) {
debugPrintln("found " + serviceId);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
String factoryClassName = rd.readLine();
rd.close();
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
debugPrintln("loaded from services: " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
}
} catch( Exception ex ) {
if( debug ) ex.printStackTrace();
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
debugPrintln("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, classLoader);
}
static class ConfigurationError extends Error {
// fixme: should this be refactored to use the jdk1.4 exception
// wrapping?
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*
* @param msg the Message for this error
* @param x an Exception that caused this failure, or null
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
}
| 7,079 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/ServiceFactory.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.xml.rpc;
import javax.xml.namespace.QName;
import java.net.URL;
/**
* The <code>javax.xml.rpc.ServiceFactory</code> is an abstract class
* that provides a factory for the creation of instances of the type
* <code>javax.xml.rpc.Service</code>. This abstract class follows the
* abstract static factory design pattern. This enables a J2SE based
* client to create a <code>Service instance</code> in a portable manner
* without using the constructor of the <code>Service</code>
* implementation class.
* <p>
* The ServiceFactory implementation class is set using the
* system property <code>SERVICEFACTORY_PROPERTY</code>.
*
* @version 1.0
*/
public abstract class ServiceFactory {
/** Protected constructor. */
protected ServiceFactory() {}
/**
* A constant representing the property used to lookup the
* name of a <code>ServiceFactory</code> implementation
* class.
*/
public static final java.lang.String SERVICEFACTORY_PROPERTY =
"javax.xml.rpc.ServiceFactory";
/**
* Gets an instance of the <code>ServiceFactory</code>
*
* <p>Only one copy of a factory exists and is returned to the
* application each time this method is called.
*
* <p> The implementation class to be used can be overridden by
* setting the javax.xml.rpc.ServiceFactory system property.
*
* @return ServiceFactory.
* @throws ServiceException
*/
public static ServiceFactory newInstance() throws ServiceException {
try {
return (ServiceFactory) FactoryFinder.find(
/* The default property name according to the JAXRPC spec */
SERVICEFACTORY_PROPERTY,
/* The fallback implementation class name */
"org.apache.axis.client.ServiceFactory");
} catch (FactoryFinder.ConfigurationError e) {
throw new ServiceException(e.getException());
}
}
/**
* Create a <code>Service</code> instance.
*
* @param wsdlDocumentLocation URL for the WSDL document location
* @param serviceName QName for the service.
* @return Service.
* @throws ServiceException If any error in creation of the
* specified service
*/
public abstract Service createService(
URL wsdlDocumentLocation, QName serviceName) throws ServiceException;
/**
* Create a <code>Service</code> instance.
*
* @param serviceName QName for the service
* @return Service.
* @throws ServiceException If any error in creation of the specified service
*/
public abstract Service createService(QName serviceName)
throws ServiceException;
public abstract Service loadService(java.lang.Class class1)
throws ServiceException;
public abstract Service loadService(java.net.URL url,
java.lang.Class class1,
java.util.Properties properties)
throws ServiceException;
public abstract Service loadService(java.net.URL url,
QName qname,
java.util.Properties properties)
throws ServiceException;
}
| 7,080 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/Call.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.xml.rpc;
import javax.xml.namespace.QName;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* The <code>javax.xml.rpc.Call</code> interface provides support
* for the dynamic invocation of a service endpoint. The
* <code>javax.xml.rpc.Service</code> interface acts as a factory
* for the creation of <code>Call</code> instances.
* <p>
* Once a <code>Call</code> instance is created, various setter
* and getter methods may be used to configure this <code>Call</code>
* instance.
*
* @version 1.0
*/
public interface Call {
/**
* Standard property: User name for authentication
* <p>Type: <code>java.lang.String</code>
*/
public static final String USERNAME_PROPERTY =
"javax.xml.rpc.security.auth.username";
/**
* Standard property: Password for authentication
* <p>Type: <code>java.lang.String</code>
*/
public static final String PASSWORD_PROPERTY =
"javax.xml.rpc.security.auth.password";
/**
* Standard property for operation style. This property is
* set to "rpc" if the operation style is rpc; "document"
* if the operation style is document.
* <p>Type: <code>java.lang.String</code>
*/
public static final String OPERATION_STYLE_PROPERTY =
"javax.xml.rpc.soap.operation.style";
/**
* Standard property for SOAPAction. This boolean property
* indicates whether or not SOAPAction is to be used. The
* default value of this property is false indicating that
* the SOAPAction is not used.
* <p>Type: <code>java.lang.Boolean</code>
*/
public static final String SOAPACTION_USE_PROPERTY =
"javax.xml.rpc.soap.http.soapaction.use";
/**
* Standard property for SOAPAction. Indicates the SOAPAction
* URI if the <code>javax.xml.rpc.soap.http.soapaction.use</code>
* property is set to <code>true</code>.
* <p>Type: <code>java.lang.String</code>
*/
public static final String SOAPACTION_URI_PROPERTY =
"javax.xml.rpc.soap.http.soapaction.uri";
/**
* Standard property for encoding Style: Encoding style specified
* as a namespace URI. The default value is the SOAP 1.1 encoding
* <code>http://schemas.xmlsoap.org/soap/encoding/</code>
* <p>Type: <code>java.lang.String</code>
*/
public static final String ENCODINGSTYLE_URI_PROPERTY =
"javax.xml.rpc.encodingstyle.namespace.uri";
/**
* Standard property: This boolean property is used by a service
* client to indicate whether or not it wants to participate in
* a session with a service endpoint. If this property is set to
* true, the service client indicates that it wants the session
* to be maintained. If set to false, the session is not maintained.
* The default value for this property is <code>false</code>.
* <p>Type: <code>java.lang.Boolean</code>
*/
public static final String SESSION_MAINTAIN_PROPERTY =
"javax.xml.rpc.session.maintain";
/**
* Indicates whether <code>addParameter</code> and
* <code>setReturnType</code> methods
* are to be invoked to specify the parameter and return type
* specification for a specific operation.
*
* @param operationName Qualified name of the operation
*
* @return Returns true if the Call implementation class
* requires addParameter and setReturnType to be
* invoked in the client code for the specified
* operation. This method returns false otherwise.
*/
public boolean isParameterAndReturnSpecRequired(QName operationName);
/**
* Adds a parameter type and mode for a specific operation.
* Note that the client code may not call any
* <code>addParameter</code> and <code>setReturnType</code>
* methods before calling the <code>invoke</code> method. In
* this case, the Call implementation class determines the
* parameter types by using reflection on parameters, using
* the WSDL description and configured type mapping registry.
*
* @param paramName Name of the parameter
* @param xmlType XML datatype of the parameter
* @param parameterMode Mode of the parameter-whether
* <code>ParameterMode.IN</code>,
* <code>ParameterMode.OUT</code>,
* or <code>ParameterMode.INOUT</code>
* @throws JAXRPCException This exception may
* be thrown if the method <code>isParameterAndReturnSpecRequired</code>
* returns <code>false</code> for this operation.
* @throws java.lang.IllegalArgumentException If any illegal
* parameter name or XML type is specified
*/
public void addParameter(String paramName, QName xmlType,
ParameterMode parameterMode);
/**
* Adds a parameter type and mode for a specific operation.
* This method is used to specify the Java type for either
* OUT or INOUT parameters.
*
* @param paramName Name of the parameter
* @param xmlType XML datatype of the parameter
* @param javaType The Java class of the parameter
* @param parameterMode Mode of the parameter-whether
* ParameterMode.IN, OUT or INOUT
* @throws JAXRPCException <ul>
*
* <li>This exception may be thrown if this method is
* invoked when the method <code>isParameterAndReturnSpecRequired</code>
* returns <code>false</code>.
* <li>If specified XML type and Java type mapping
* is not valid. For example, <code>TypeMappingRegistry</code>
* has no serializers for this mapping.
* </ul>
* @throws java.lang.IllegalArgumentException If any illegal
* parameter name or XML type is specified
* @throws java.lang.UnsupportedOperationException If this
* method is not supported
*/
public void addParameter(String paramName, QName xmlType, Class javaType,
ParameterMode parameterMode);
/**
* Gets the XML type of a parameter by name.
*
* @param paramName name of the parameter
*
* @return Returns XML type for the specified parameter
*/
public QName getParameterTypeByName(String paramName);
/**
* Sets the return type for a specific operation. Invoking
* <code>setReturnType(null)</code> removes the return
* type for this Call object.
*
* @param xmlType XML data type of the return value
* @throws JAXRPCException This exception
* may be thrown when the method
* <code>isParameterAndReturnSpecRequired</code> returns
* <code>false</code>.
* @throws java.lang.IllegalArgumentException If an illegal
* XML type is specified
*/
public void setReturnType(QName xmlType);
/**
* Sets the return type for a specific operation.
*
* @param xmlType XML data type of the return value
* @param javaType Java class of the return value
* @throws JAXRPCException <ul>
* <li>This exception may be thrown if this method is
* invoked when the method <code>isParameterAndReturnSpecRequired</code>
* returns <code>false</code>.
* <li>If XML type and Java type cannot be mapped
* using the standard type mapping or TypeMapping
* registry
* </ul>
* @throws java.lang.UnsupportedOperationException If this
* method is not supported
* @throws java.lang.IllegalArgumentException If an illegal
* XML type is specified
*/
public void setReturnType(QName xmlType, Class javaType);
/**
* Gets the return type for a specific operation.
*
* @return the XML type for the return value
*/
public QName getReturnType();
/**
* Removes all specified parameters from this <code>Call</code> instance.
* Note that this method removes only the parameters and not
* the return type. The <code>setReturnType(null)</code> is
* used to remove the return type.
*
* @throws JAXRPCException This exception may be
* thrown If this method is called when the method
* <code>isParameterAndReturnSpecRequired</code>
* returns <code>false</code> for this Call's operation.
*/
public void removeAllParameters();
/**
* Gets the name of the operation to be invoked using this Call instance.
*
* @return Qualified name of the operation
*/
public QName getOperationName();
/**
* Sets the name of the operation to be invoked using this
* <code>Call</code> instance.
*
* @param operationName QName of the operation to be
* invoked using the Call instance
*/
public void setOperationName(QName operationName);
/**
* Gets the qualified name of the port type.
*
* @return Qualified name of the port type
*/
public QName getPortTypeName();
/**
* Sets the qualified name of the port type.
*
* @param portType Qualified name of the port type
*/
public void setPortTypeName(QName portType);
/**
* Sets the address of the target service endpoint.
* This address must correspond to the transport specified
* in the binding for this <code>Call</code> instance.
*
* @param address Address of the target service endpoint;
* specified as an URI
*/
public void setTargetEndpointAddress(String address);
/**
* Gets the address of a target service endpoint.
*
* @return Endpoint address of the target service port as an URI
*/
public String getTargetEndpointAddress();
/**
* Sets the value for a named property. JAX-RPC specification
* specifies a standard set of properties that may be passed
* to the <code>Call.setProperty</code> method.
*
* @param name Name of the property
* @param value Value of the property
* @throws JAXRPCException <ul>
* <li>If an optional standard property name is
* specified, however this <code>Call</code> implementation
* class does not support the configuration of
* this property.
* <li>If an invalid (or unsupported) property name is
* specified or if a value of mismatched property
* type is passed.
* <li>If there is any error in the configuration of
* a valid property.
* </ul>
*/
public void setProperty(String name, Object value);
/**
* Gets the value of a named property.
*
* @param name Name of the property
*
* @return Value of the named property
* @throws JAXRPCException if an invalid or
* unsupported property name is passed.
*/
public Object getProperty(String name);
/**
* Removes a named property.
*
* @param name Name of the property
* @throws JAXRPCException if an invalid or
* unsupported property name is passed.
*/
public void removeProperty(String name);
/**
* Gets the names of configurable properties supported by
* this <code>Call</code> object.
*
* @return Iterator for the property names
*/
public Iterator getPropertyNames();
// Remote Method Invocation methods
/**
* Invokes a specific operation using a synchronous request-response
* interaction mode.
*
* @param inputParams Object[]--Parameters for this invocation. This
* includes only the input params
*
* @return Returns the return value or <code>null</code>
*
* @throws java.rmi.RemoteException if there is any error in the remote
* method invocation or if the Call
* object is not configured properly.
* @throws javax.xml.rpc.soap.SOAPFaultException Indicates a SOAP fault
* @throws JAXRPCException <ul>
*
* <li>If there is an error in the configuration of the
* <code>Call</code> object
* <li>If <code>inputParams</code> do not match the required parameter
* set (as specified through the <code>addParameter</code>
* invocations or in the corresponding WSDL)
* <li>If parameters and return type are incorrectly
* specified
* </ul>
*/
public Object invoke(Object[] inputParams) throws java.rmi.RemoteException;
/**
* Invokes a specific operation using a synchronous request-response
* interaction mode.
*
* @param operationName QName of the operation
* @param inputParams Object[]--Parameters for this invocation. This
* includes only the input params.
*
* @return Return value or null
*
* @throws java.rmi.RemoteException if there is any error in the
* remote method invocation.
* @throws javax.xml.rpc.soap.SOAPFaultException Indicates a SOAP fault
* @throws JAXRPCException <ul>
* <li>If there is an error in the configuration of the
* <code>Cal</code>l object
* <li>If <code>inputParam</code>s do not match the required parameter
* set (as specified through the <code>addParameter</code>
* invocations or in the corresponding WSDL)
* <li>If parameters and return type are incorrectly
* specified
* </ul>
*/
public Object invoke(QName operationName, Object[] inputParams)
throws java.rmi.RemoteException;
/**
* Invokes a remote method using the one-way interaction mode. The
* client thread does not block waiting for the completion of the
* server processing for this remote method invocation. This method
* must not throw any remote exceptions. This method may throw a
* <code>JAXRPCException</code> during the processing of the one-way
* remote call.
*
* @param params Object[]--Parameters for this invocation. This
* includes only the input params.
*
* @throws JAXRPCException if there is an error in the
* configuration of the <code>Call</code> object (example: a
* non-void return type has been incorrectly specified for the
* one-way call) or if there is any error during the
* invocation of the one-way remote call
*/
public void invokeOneWay(Object[] params);
/**
* Returns a <code>Map</code> of {name, value} for the output parameters of
* the last invoked operation. The parameter names in the
* returned Map are of type <code>java.lang.String</code>.
*
* @return Map Output parameters for the last <code>Call.invoke()</code>.
* Empty <code>Map</code> is returned if there are no output
* parameters.
* @throws javax.xml.rpc.JAXRPCException If this method is invoked for a
* one-way operation or is invoked before any
* <code>invoke</code> method has been called.
*/
public Map getOutputParams();
/**
* Returns a <code>List</code> values for the output parameters
* of the last invoked operation.
*
* @return java.util.List Values for the output parameters. An
* empty <code>List</code> is returned if there are
* no output values.
*
* @throws JAXRPCException If this method is invoked for a
* one-way operation or is invoked before any
* <code>invoke</code> method has been called.
*/
public List getOutputValues();
}
| 7,081 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/Service.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.xml.rpc;
import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import javax.xml.rpc.handler.HandlerRegistry;
/**
* <code>Service</code> class acts as a factory of the following:
* <ul>
* <li>Dynamic proxy for the target service endpoint.
* <li>Instance of the type <code>javax.xml.rpc.Call</code> for
* the dynamic invocation of a remote operation on the
* target service endpoint.
* <li>Instance of a generated stub class
* </ul>
*
* @version 1.0
*/
public interface Service {
/**
* The getPort method returns either an instance of a generated
* stub implementation class or a dynamic proxy. A service client
* uses this dynamic proxy to invoke operations on the target
* service endpoint. The <code>serviceEndpointInterface</code>
* specifies the service endpoint interface that is supported by
* the created dynamic proxy or stub instance.
*
* @param portName Qualified name of the service endpoint in
* the WSDL service description
* @param serviceEndpointInterface Service endpoint interface
* supported by the dynamic proxy or stub
* instance
* @return java.rmi.Remote Stub instance or dynamic proxy that
* supports the specified service endpoint
* interface
* @throws ServiceException This exception is thrown in the
* following cases:
* <ul>
* <li>If there is an error in creation of
* the dynamic proxy or stub instance
* <li>If there is any missing WSDL metadata
* as required by this method
* <li>Optionally, if an illegal
* <code>serviceEndpointInterface</code>
* or <code>portName</code> is specified
* </ul>
*/
public java.rmi
.Remote getPort(QName portName, Class serviceEndpointInterface)
throws ServiceException;
/**
* The getPort method returns either an instance of a generated
* stub implementation class or a dynamic proxy. The parameter
* <code>serviceEndpointInterface</code> specifies the service
* endpoint interface that is supported by the returned stub or
* proxy. In the implementation of this method, the JAX-RPC
* runtime system takes the responsibility of selecting a protocol
* binding (and a port) and configuring the stub accordingly.
* The returned <code>Stub</code> instance should not be
* reconfigured by the client.
*
* @param serviceEndpointInterface Service endpoint interface
* @return Stub instance or dynamic proxy that supports the
* specified service endpoint interface
*
* @throws ServiceException <ul>
* <li>If there is an error during creation
* of stub instance or dynamic proxy
* <li>If there is any missing WSDL metadata
* as required by this method
* <li>Optionally, if an illegal
* <code>serviceEndpointInterface</code>
*
* is specified
* </ul>
*/
public java.rmi.Remote getPort(Class serviceEndpointInterface)
throws ServiceException;
/**
* Gets an array of preconfigured <code>Call</code> objects for
* invoking operations on the specified port. There is one
* <code>Call</code> object per operation that can be invoked
* on the specified port. Each <code>Call</code> object is
* pre-configured and does not need to be configured using
* the setter methods on <code>Call</code> interface.
*
* <p>Each invocation of the <code>getCalls</code> method
* returns a new array of preconfigured <code>Call</code>
*
* objects
*
* <p>This method requires the <code>Service</code> implementation
* class to have access to the WSDL related metadata.
*
* @param portName Qualified name for the target service endpoint
* @return Call[] Array of pre-configured Call objects
* @throws ServiceException If this Service class does not
* have access to the required WSDL metadata
* or if an illegal <code>portName</code> is
* specified.
*/
public Call[] getCalls(QName portName) throws ServiceException;
/**
* Creates a <code>Call</code> instance.
*
* @param portName Qualified name for the target service endpoint
* @return Call instance
* @throws ServiceException If any error in the creation of
* the <code>Call</code> object
*/
public Call createCall(QName portName) throws ServiceException;
/**
* Creates a <code>Call</code> instance.
*
* @param portName Qualified name for the target service
* endpoint
* @param operationName Qualified Name of the operation for
* which this <code>Call</code> object is to
* be created.
* @return Call instance
* @throws ServiceException If any error in the creation of
* the <code>Call</code> object
*/
public Call createCall(QName portName, QName operationName)
throws ServiceException;
/**
* Creates a <code>Call</code> instance.
*
* @param portName Qualified name for the target service
* endpoint
* @param operationName Name of the operation for which this
* <code>Call</code> object is to be
* created.
* @return Call instance
* @throws ServiceException If any error in the creation of
* the <code>Call</code> object
*/
public Call createCall(QName portName, String operationName)
throws ServiceException;
/**
* Creates a <code>Call</code> object not associated with
* specific operation or target service endpoint. This
* <code>Call</code> object needs to be configured using the
* setter methods on the <code>Call</code> interface.
*
* @return Call object
* @throws ServiceException If any error in the creation of
* the <code>Call</code> object
*/
public Call createCall() throws ServiceException;
/**
* Gets the name of this Service.
*
* @return Qualified name of this service
*/
public QName getServiceName();
/**
* Returns an <code>Iterator</code> for the list of
* <code>QName</code>s of service endpoints grouped by this
* service.
*
* @return Returns <code>java.util.Iterator</code> with elements
* of type <code>javax.xml.namespace.QName</code>
* @throws ServiceException If this Service class does not
* have access to the required WSDL metadata
*/
public java.util.Iterator getPorts() throws ServiceException;
/**
* Gets location of the WSDL document for this Service.
*
* @return URL for the location of the WSDL document for
* this service
*/
public java.net.URL getWSDLDocumentLocation();
/**
* Gets the <code>TypeMappingRegistry</code> for this
* <code>Service</code> object. The returned
* <code>TypeMappingRegistry</code> instance is pre-configured
* to support the standard type mapping between XML and Java
* types types as required by the JAX-RPC specification.
*
* @return The TypeMappingRegistry for this Service object.
* @throws java.lang.UnsupportedOperationException if the <code>Service</code> class does not support
* the configuration of <code>TypeMappingRegistry</code>.
*/
public TypeMappingRegistry getTypeMappingRegistry();
/**
* Returns the configured <code>HandlerRegistry</code> instance
* for this <code>Service</code> instance.
*
* @return HandlerRegistry
* @throws java.lang.UnsupportedOperationException - if the <code>Service</code> class does not support
* the configuration of a <code>HandlerRegistry</code>
*/
public HandlerRegistry getHandlerRegistry();
}
| 7,082 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/JAXRPCException.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 javax.xml.rpc;
/**
* The <code>javax.xml.rpc.JAXRPCException</code> is thrown from
* the core JAX-RPC APIs to indicate an exception related to the
* JAX-RPC runtime mechanisms.
*
* @version 1.0
*/
public class JAXRPCException extends RuntimeException {
// fixme: Why doesn't this use the jdk1.4 exception wrapping APIs?
/** The cause of this error. */
Throwable cause;
/**
* Constructs a new exception with <code>null</code> as its
* detail message. The cause is not initialized.
*/
public JAXRPCException() {}
/**
* Constructs a new exception with the specified detail
* message. The cause is not initialized.
*
* @param message The detail message which is later
* retrieved using the getMessage method
*/
public JAXRPCException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail
* message and cause.
*
* @param message The detail message which is later retrieved
* using the getMessage method
* @param cause The cause which is saved for the later
* retrieval throw by the getCause method
*/
public JAXRPCException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
/**
* Constructs a new JAXRPCException with the specified cause
* and a detail message of <tt>(cause==null ? null :
* cause.toString())</tt> (which typically contains the
* class and detail message of <tt>cause</tt>).
*
* @param cause The cause which is saved for the later
* retrieval throw by the getCause method.
* (A <tt>null</tt> value is permitted, and
* indicates that the cause is nonexistent or
* unknown.)
*/
public JAXRPCException(Throwable cause) {
super( (cause == null) ? null : cause.toString() );
this.cause = cause;
}
/**
* Gets the linked cause.
*
* @return The cause of this Exception or <code>null</code>
* if the cause is noexistent or unknown
*/
public Throwable getLinkedCause() {
return cause;
}
}
| 7,083 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/MessageContext.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 javax.xml.rpc.handler;
import java.util.Iterator;
/**
* The interface <code>MessageContext</code> abstracts the message
* context that is processed by a handler in the <code>handle</code>
* method.
*
* <p>The <code>MessageContext</code> interface provides methods to
* manage a property set. <code>MessageContext</code> properties
* enable handlers in a handler chain to share processing related
* state.
*
* @version 1.0
*/
public interface MessageContext {
/**
* Sets the name and value of a property associated with the
* <code>MessageContext</code>. If the <code>MessageContext</code>
* contains a value of the same property, the old value is replaced.
*
* @param name ame of the property associated with the
* <code>MessageContext</code>
* @param value Value of the property
* @throws java.lang.IllegalArgumentException If some aspect
* the property is prevents it from being stored
* in the context
* @throws java.lang.UnsupportedOperationException If this method is
* not supported.
*/
public abstract void setProperty(String name, Object value);
/**
* Gets the value of a specific property from the
* <code>MessageContext</code>.
*
* @param name the name of the property whose value is to be
* retrieved
* @return the value of the property
* @throws java.lang.IllegalArgumentException if an illegal
* property name is specified
*/
public abstract Object getProperty(String name);
/**
* Removes a property (name-value pair) from the
* <code>MessageContext</code>.
*
* @param name the name of the property to be removed
*
* @throws java.lang.IllegalArgumentException if an illegal
* property name is specified
*/
public abstract void removeProperty(String name);
/**
* Returns true if the <code>MessageContext</code> contains a property
* with the specified name.
* @param name Name of the property whose presense is to be tested
* @return Returns true if the MessageContext contains the
* property; otherwise false
*/
public abstract boolean containsProperty(String name);
/**
* Returns an Iterator view of the names of the properties
* in this <code>MessageContext</code>.
*
* @return Iterator for the property names
*/
public abstract Iterator getPropertyNames();
}
| 7,084 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/Handler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.xml.rpc.handler;
import javax.xml.namespace.QName;
/**
* The <code>javax.xml.rpc.handler.Handler</code> interface is
* required to be implemented by a SOAP message handler. The
* <code>handleRequest</code>, <code>handleResponse</code>
* and <code>handleFault</code> methods for a SOAP message
* handler get access to the <code>SOAPMessage</code> from the
* <code>SOAPMessageContext</code>. The implementation of these
* methods can modify the <code>SOAPMessage</code> including the
* headers and body elements.
*
* @version 1.0
*/
public interface Handler {
/**
* The <code>handleRequest</code> method processes the request message.
*
* @param context MessageContext parameter provides access to the request
* message.
* @return boolean boolean Indicates the processing mode
* <ul>
* <li>Return <code>true</code> to indicate continued
* processing of the request handler chain. The
* <code>HandlerChain</code>
* takes the responsibility of invoking the next
* entity. The next entity may be the next handler
* in the <code>HandlerChain</code> or if this
* handler is the last handler in the chain, the
* next entity is the service endpoint object.
* <li>Return <code>false</code> to indicate blocking
* of the request handler chain. In this case,
* further processing of the request handler chain
* is blocked and the target service endpoint is
* not dispatched. The JAX-RPC runtime system takes
* the responsibility of invoking the response
* handler chain next with the SOAPMessageContext.
* The Handler implementation class has the the
* responsibility of setting the appropriate response
* SOAP message in either handleRequest and/or
* handleResponse method. In the default processing
* model, the response handler chain starts processing
* from the same Handler instance (that returned false)
* and goes backward in the execution sequence.
* </ul>
*
* @throws javax.xml.rpc.JAXRPCException
* indicates a handler-specific
* runtime error. If <code>JAXRPCException</code> is thrown
* by a handleRequest method, the HandlerChain
* terminates the further processing of this handler
* chain. On the server side, the HandlerChain
* generates a SOAP fault that indicates that the
* message could not be processed for reasons not
* directly attributable to the contents of the
* message itself but rather to a runtime error
* during the processing of the message. On the
* client side, the exception is propagated to
* the client code
* @throws javax.xml.rpc.soap.SOAPFaultException
* indicates a SOAP fault. The Handler
* implementation class has the the responsibility
* of setting the SOAP fault in the SOAP message in
* either handleRequest and/or handleFault method.
* If SOAPFaultException is thrown by a server-side
* request handler's handleRequest method, the
* HandlerChain terminates the further processing
* of the request handlers in this handler chain
* and invokes the handleFault method on the
* HandlerChain with the SOAP message context. Next,
* the HandlerChain invokes the handleFault method
* on handlers registered in the handler chain,
* beginning with the Handler instance that threw
* the exception and going backward in execution. The
* client-side request handler's handleRequest method
* should not throw the SOAPFaultException.
*/
public boolean handleRequest(MessageContext context);
/**
* The <code>handleResponse</code> method processes the response SOAP message.
*
* @param context MessageContext parameter provides access to
* the response SOAP message
*
* @return boolean Indicates the processing mode
* <ul>
* <li>Return <code>true</code> to indicate continued
* processing ofthe response handler chain. The
* HandlerChain invokes the <code>handleResponse</code>
* method on the next <code>Handler</code> in
* the handler chain.
* <li>Return <code>false</code> to indicate blocking
* of the response handler chain. In this case, no
* other response handlers in the handler chain
* are invoked.
* </ul>
*
* @throws javax.xml.rpc.JAXRPCException
* indicates a handler specific runtime error.
* If JAXRPCException is thrown by a handleResponse
* method, the HandlerChain terminates the further
* processing of this handler chain. On the server side,
* the HandlerChain generates a SOAP fault that
* indicates that the message could not be processed
* for reasons not directly attributable to the contents
* of the message itself but rather to a runtime error
* during the processing of the message. On the client
* side, the runtime exception is propagated to the
* client code.
*/
public boolean handleResponse(MessageContext context);
/**
* The <code>handleFault</code> method processes the SOAP faults
* based on the SOAP message processing model.
*
* @param context MessageContext parameter provides access to
* the SOAP message
* @return boolean Indicates the processing mode
* <ul>
* <li>Return <code>true</code> to indicate continued
* processing of SOAP Fault. The HandlerChain invokes
* the <code>handleFault</code> method on the
* next <code>Handler</code> in the handler chain.
* <li>Return <code>false</code> to indicate end
* of the SOAP fault processing. In this case, no
* other handlers in the handler chain
* are invoked.
* </ul>
* @throws javax.xml.rpc.JAXRPCException indicates handler specific runtime
* error. If JAXRPCException is thrown by a handleFault
* method, the HandlerChain terminates the further
* processing of this handler chain. On the server side,
* the HandlerChain generates a SOAP fault that
* indicates that the message could not be processed
* for reasons not directly attributable to the contents
* of the message itself but rather to a runtime error
* during the processing of the message. On the client
* side, the JAXRPCException is propagated to the
* client code.
*/
public boolean handleFault(MessageContext context);
/**
* The <code>init</code> method enables the Handler instance to
* initialize itself. The <code>init</code> method passes the
* handler configuration as a <code>HandlerInfo</code> instance.
* The HandlerInfo is used to configure the Handler (for example:
* setup access to an external resource or service) during the
* initialization.
* <p>
* In the init method, the Handler class may get access to
* any resources (for example; access to a logging service or
* database) and maintain these as part of its instance variables.
* Note that these instance variables must not have any state
* specific to the SOAP message processing performed in the
* various handle method.
*
* @param config HandlerInfo configuration for the initialization of this
* handler
*
* @param config
* @throws javax.xml.rpc.JAXRPCException if initialization of the handler
* fails
*/
public abstract void init(HandlerInfo config);
/**
* The <code>destroy</code> method indicates the end of lifecycle
* for a Handler instance. The Handler implementation class should
* release its resources and perform cleanup in the implementation
* of the <code>destroy</code> method.
*
* @throws javax.xml.rpc.JAXRPCException if there was any error during
* destroy
*/
public abstract void destroy();
/**
* Gets the header blocks processed by this Handler instance.
*
* @return Array of QNames of header blocks processed by this
* handler instance. <code>QName</code> is the qualified
* name of the outermost element of the Header block.
*/
public QName[] getHeaders();
}
| 7,085 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/HandlerChain.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 javax.xml.rpc.handler;
import java.util.List;
import java.util.Map;
/**
* The <code>javax.xml.rpc.handler.HandlerChain</code> represents
* a list of handlers. All elements in the HandlerChain are of
* the type <code>javax.xml.rpc.handler.Handler</code>.
* <p>
* An implementation class for the <code>HandlerChain</code>
* interface abstracts the policy and mechanism for the invocation
* of the registered handlers.
*
* @version 1.0
*/
public interface HandlerChain extends List {
/**
* The <code>handleRequest</code> method initiates the request
* processing for this handler chain.
* @param context MessageContext parameter provides access to
* the request SOAP message.
* @return boolean Returns <code>true</code> if all handlers in
* chain have been processed. Returns <code>false</code>
*
* if a handler in the chain returned
* <code>false</code> from its handleRequest
* method.
* @throws javax.xml.rpc.JAXRPCException if any processing error happens
*/
public boolean handleRequest(MessageContext context);
/**
* The <code>handleResponse</code> method initiates the response
* processing for this handler chain.
*
* @param context MessageContext parameter provides access to the response
* SOAP message.
* @return boolean Returns <code>true</code> if all handlers in
* chain have been processed. Returns <code>false</code>
* if a handler in the chain returned
* <code>false</code> from its handleResponse method.
* @throws javax.xml.rpc.JAXRPCException if any processing error happens
*/
public boolean handleResponse(MessageContext context);
/**
* The <code>handleFault</code> method initiates the SOAP
* fault processing for this handler chain.
*
* @param context MessageContext parameter provides access to the SOAP
* message.
* @return Returns boolean Returns <code>true</code> if all handlers in
* chain have been processed. Returns <code>false</code>
* if a handler in the chain returned
* <code>false</code> from its handleFault method.
* @throws javax.xml.rpc.JAXRPCException if any processing error happens
*/
public boolean handleFault(MessageContext context);
/**
* Initializes the configuration for a HandlerChain.
*
* @param config Configuration for the initialization of this handler
* chain
*
* @throws javax.xml.rpc.JAXRPCException if there is any error that prevents
* initialization
*/
public void init(Map config);
/**
* Indicates the end of lifecycle for a HandlerChain.
*
* @throws javax.xml.rpc.JAXRPCException if there was any error that
* prevented destroy from completing
*/
public void destroy();
/**
* Sets SOAP Actor roles for this <code>HandlerChain</code>. This
* specifies the set of roles in which this HandlerChain is to act
* for the SOAP message processing at this SOAP node. These roles
* assumed by a HandlerChain must be invariant during the
* processing of an individual SOAP message through the HandlerChain.
* <p>
* A <code>HandlerChain</code> always acts in the role of the
* special SOAP actor <code>next</code>. Refer to the SOAP
* specification for the URI name for this special SOAP actor.
* There is no need to set this special role using this method.
*
* @param soapActorNames URIs for SOAP actor name
*/
public void setRoles(String[] soapActorNames);
/**
* Gets SOAP actor roles registered for this HandlerChain at
* this SOAP node. The returned array includes the special
* SOAP actor <code>next</code>.
* @return String[] SOAP Actor roles as URIs
*/
public java.lang.String[] getRoles();
}
| 7,086 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/GenericHandler.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 javax.xml.rpc.handler;
import javax.xml.namespace.QName;
/**
* The <code>javax.xml.rpc.handler.GenericHandler</code> class
* implements the <code>Handler</code> interface. SOAP Message
* Handler developers should typically subclass
* <code>GenericHandler</code> class unless the Handler class
* needs another class as a superclass.
*
* <p>
* The <code>GenericHandler</code> class is a convenience abstract
* class that makes writing Handlers easy. This class provides
* default implementations of the lifecycle methods <code>init</code>
* and <code>destroy</code> and also different handle methods.
* A Handler developer should only override methods that it needs
* to specialize as part of the derived <code>Handler</code>
* implementation class.
*
* @version 1.0
*/
public abstract class GenericHandler implements Handler {
/**
* Default constructor.
*/
protected GenericHandler() {}
/**
* The <code>handleRequest</code> method processes the request
* SOAP message. The default implementation of this method returns
* <code>true</code>. This indicates that the handler chain
* should continue processing of the request SOAP message.
* This method should be overridden if the derived Handler class
* needs to specialize implementation of this method.
*
* @param context the message context
* @return true/false
*/
public boolean handleRequest(MessageContext context) {
return true;
}
/**
* The <code>handleResponse</code> method processes the response
* message. The default implementation of this method returns
* <code>true</code>. This indicates that the handler chain
* should continue processing of the response SOAP message.
* This method should be overridden if the derived Handler class
* needs to specialize implementation of this method.
*
* @param context the message context
* @return true/false
*/
public boolean handleResponse(MessageContext context) {
return true;
}
/**
* The <code>handleFault</code> method processes the SOAP faults
* based on the SOAP message processing model. The default
* implementation of this method returns <code>true</code>. This
* indicates that the handler chain should continue processing
* of the SOAP fault. This method should be overridden if
* the derived Handler class needs to specialize implementation
* of this method.
*
* @param context the message context
* @return true/false
*/
public boolean handleFault(MessageContext context) {
return true;
}
/**
* The <code>init</code> method to enable the Handler instance to
* initialize itself. This method should be overridden if
* the derived Handler class needs to specialize implementation
* of this method.
*
* @param config handler configuration
*/
public void init(HandlerInfo config) {}
/**
* The <code>destroy</code> method indicates the end of lifecycle
* for a Handler instance. This method should be overridden if
* the derived Handler class needs to specialize implementation
* of this method.
*/
public void destroy() {}
/**
* Gets the header blocks processed by this Handler instance.
*
* @return Array of QNames of header blocks processed by this handler instance.
* <code>QName</code> is the qualified name of the outermost element of the Header block.
*/
public abstract QName[] getHeaders();
}
| 7,087 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/HandlerRegistry.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 javax.xml.rpc.handler;
import javax.xml.namespace.QName;
import java.io.Serializable;
/**
* The <code>javax.xml.rpc.handler.HandlerRegistry</code>
* provides support for the programmatic configuration of
* handlers in a <code>HandlerRegistry</code>.
* <p>
* A handler chain is registered per service endpoint, as
* indicated by the qualified name of a port. The getHandlerChain
* returns the handler chain (as a java.util.List) for the
* specified service endpoint. The returned handler chain is
* configured using the java.util.List interface. Each element
* in this list is required to be of the Java type
* <code>javax.xml.rpc.handler.HandlerInfo</code>
*
* @version 1.0
*/
public interface HandlerRegistry extends Serializable {
/**
* Gets the handler chain for the specified service endpoint.
* The returned <code>List</code> is used to configure this
* specific handler chain in this <code>HandlerRegistry</code>.
* Each element in this list is required to be of the Java type
* <code>javax.xml.rpc.handler.HandlerInfo</code>.
*
* @param portName Qualified name of the target service
* @return HandlerChain java.util.List Handler chain
* @throws java.lang.IllegalArgumentException If an invalid <code>portName</code> is specified
*/
public java.util.List getHandlerChain(QName portName);
/**
* Sets the handler chain for the specified service endpoint
* as a <code>java.util.List</code>. Each element in this list
* is required to be of the Java type
* <code>javax.xml.rpc.handler.HandlerInfo</code>.
*
* @param portName Qualified name of the target service endpoint
* @param chain a List representing configuration for the
* handler chain
* @throws javax.xml.rpc.JAXRPCException if there is any error in the
* configuration of the handler chain
* @throws java.lang.UnsupportedOperationException if this
* set operation is not supported. This is done to
* avoid any overriding of a pre-configured handler
* chain.
* @throws java.lang.IllegalArgumentException If an invalid
* <code>portName</code> is specified
*/
public abstract void setHandlerChain(QName portName, java.util.List chain);
}
| 7,088 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/HandlerInfo.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 javax.xml.rpc.handler;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The <code>javax.xml.rpc.handler.HandlerInfo</code> represents
* information about a handler in the HandlerChain. A HandlerInfo
* instance is passed in the <code>Handler.init</code> method to
* initialize a <code>Handler</code> instance.
*
* @version 1.0
* @see HandlerChain
*/
public class HandlerInfo implements Serializable {
/** Default constructor. */
public HandlerInfo() {
handlerClass = null;
config = new HashMap();
}
/**
* Constructor for HandlerInfo.
*
* @param handlerClass Java Class for the Handler
* @param config Handler Configuration as a java.util.Map
* @param headers QNames for the header blocks processed
* by this Handler. QName is the qualified name
* of the outermost element of a header block
*/
public HandlerInfo(Class handlerClass, Map config, QName[] headers) {
this.handlerClass = handlerClass;
this.config = config;
this.headers = headers;
}
/**
* Sets the Handler class.
*
* @param handlerClass Class for the Handler
*/
public void setHandlerClass(Class handlerClass) {
this.handlerClass = handlerClass;
}
/**
* Gets the Handler class.
*
* @return Returns null if no Handler class has been
* set; otherwise the set handler class
*/
public Class getHandlerClass() {
return handlerClass;
}
/**
* Sets the Handler configuration as <code>java.util.Map</code>
* @param config Configuration map
*/
public void setHandlerConfig(Map config) {
this.config = config;
}
/**
* Gets the Handler configuration.
*
* @return Returns empty Map if no configuration map
* has been set; otherwise returns the set configuration map
*/
public Map getHandlerConfig() {
return config;
}
/**
* Sets the header blocks processed by this Handler.
* @param headers QNames of the header blocks. QName
* is the qualified name of the outermost
* element of the SOAP header block
*/
public void setHeaders(QName[] headers) {
this.headers = headers;
}
/**
* Gets the header blocks processed by this Handler.
* @return Array of QNames for the header blocks. Returns
* <code>null</code> if no header blocks have been
* set using the <code>setHeaders</code> method.
*/
public QName[] getHeaders() {
return headers;
}
/** Handler Class. */
private Class handlerClass;
/** Configuration Map. */
private Map config;
/** Headers. */
private QName[] headers;
}
| 7,089 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/handler/soap/SOAPMessageContext.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 javax.xml.rpc.handler.soap;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.soap.SOAPMessage;
/**
* The interface <code>javax.xml.rpc.soap.SOAPMessageContext</code>
* provides access to the SOAP message for either RPC request or
* response. The <code>javax.xml.soap.SOAPMessage</code> specifies
* the standard Java API for the representation of a SOAP 1.1 message
* with attachments.
*
* @version 1.0
* @see javax.xml.soap.SOAPMessage
*/
public interface SOAPMessageContext extends MessageContext {
/**
* Gets the SOAPMessage from this message context.
*
* @return the <code>SOAPMessage</code>; <code>null</code> if no request
* <code>SOAPMessage</code> is present in this
* <code>SOAPMessageContext</code>
*/
public abstract SOAPMessage getMessage();
/**
* Sets the <code>SOAPMessage</code> for this message context.
*
* @param message SOAP message
* @throws javax.xml.rpc.JAXRPCException if any error during the setting
* of the SOAPMessage in this message context
* @throws java.lang.UnsupportedOperationException if this
* operation is not supported
*/
public abstract void setMessage(SOAPMessage message);
/**
* Gets the SOAP actor roles associated with an execution
* of the HandlerChain and its contained Handler instances.
* Note that SOAP actor roles apply to the SOAP node and
* are managed using <code>HandlerChain.setRoles</code> and
* <code>HandlerChain.getRoles</code>. Handler instances in
* the HandlerChain use this information about the SOAP actor
* roles to process the SOAP header blocks. Note that the
* SOAP actor roles are invariant during the processing of
* SOAP message through the HandlerChain.
*
* @return Array of URIs for SOAP actor roles
* @see javax.xml.rpc.handler.HandlerChain#setRoles(java.lang.String[]) HandlerChain.setRoles(java.lang.String[])
* @see javax.xml.rpc.handler.HandlerChain#getRoles() HandlerChain.getRoles()
*/
public abstract String[] getRoles();
}
| 7,090 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/BooleanHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>boolean</code>s.
*
* @version 1.0
*/
public final class BooleanHolder implements Holder {
/** The <code>boolean</code> contained by this holder. */
public boolean value;
/**
* Make a new <code>BooleanHolder</code> with a <code>null</code> value.
*/
public BooleanHolder() {}
/**
* Make a new <code>BooleanHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>boolean</code> to hold
*/
public BooleanHolder(boolean value) {
this.value = value;
}
}
| 7,091 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/ShortWrapperHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>Short</code>s.
*
* @version 1.0
*/
public final class ShortWrapperHolder implements Holder {
/** The <code>Short</code> contained by this holder. */
public Short value;
/**
* Make a new <code>ShortWrapperHolder</code> with a <code>null</code> value.
*/
public ShortWrapperHolder() {}
/**
* Make a new <code>ShortWrapperHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>Short</code> to hold
*/
public ShortWrapperHolder(Short value) {
this.value = value;
}
}
| 7,092 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/ByteArrayHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>byte[]</code>s.
*
* @version 1.0
*/
public final class ByteArrayHolder implements Holder {
/** The <code>byte[]</code> contained by this holder. */
public byte[] value;
/**
* Make a new <code>ByteArrayHolder</code> with a <code>null</code> value.
*/
public ByteArrayHolder() {}
/**
* Make a new <code>ByteArrayHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>byte[]</code> to hold
*/
public ByteArrayHolder(byte[] value) {
this.value = value;
}
}
| 7,093 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/CalendarHolder.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 javax.xml.rpc.holders;
import java.util.Calendar;
/**
* Holder for <code>Calendar</code>s.
*
* @version 1.0
*/
public final class CalendarHolder implements Holder {
/** The <code>Calendar</code> that is held. */
public Calendar value;
/**
* Make a new <code>CalendarHolder</code> with a <code>null</code> value.r
*/
public CalendarHolder() {}
/**
* Make a new <code>CalendarHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>Calendar</code> to hold
*/
public CalendarHolder(Calendar value) {
this.value = value;
}
}
| 7,094 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/DoubleHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>double</code>s.
*
* @version 1.0
*/
public final class DoubleHolder implements Holder {
/** The <code>double</code> contained by this holder. */
public double value;
/**
* Make a new <code>DoubleHolder</code> with a <code>null</code> value.
*/
public DoubleHolder() {}
/**
* Make a new <code>DoubleHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>double</code> to hold
*/
public DoubleHolder(double value) {
this.value = value;
}
}
| 7,095 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/Holder.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 javax.xml.rpc.holders;
/**
* The <code>java.xml.rpc.holders.Holder</code> interface represents the base interface for both standard and
* generated Holder classes. A generated Holder class is required to implement this Holder interface.
*
* @version 1.0
*/
public interface Holder {}
| 7,096 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/ShortHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>short</code>s.
*
* @version 1.0
*/
public final class ShortHolder implements Holder {
/** The <code>short</code> contained by this holder. */
public short value;
/**
* Make a new <code>ShortHolder</code> with a <code>null</code> value.
*/
public ShortHolder() {}
/**
* Make a new <code>ShortHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>short</code> to hold
*/
public ShortHolder(short value) {
this.value = value;
}
}
| 7,097 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/ByteHolder.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 javax.xml.rpc.holders;
/**
* Holder for <code>byte</code>s.
*
* @version 1.0
*/
public final class ByteHolder implements Holder {
/** The <code>byte</code> contained by this holder. */
public byte value;
/**
* Make a new <code>ByteHolder</code> with a <code>null</code> value.
*/
public ByteHolder() {}
/**
* Make a new <code>ByteHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>byte</code> to hold
*/
public ByteHolder(byte value) {
this.value = value;
}
}
| 7,098 |
0 | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc | Create_ds/axis-axis1-java/axis-jaxrpc/src/main/java/javax/xml/rpc/holders/BigDecimalHolder.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 javax.xml.rpc.holders;
import java.math.BigDecimal;
/**
* Holder for <code>BigDecimal</code>s.
*
* @version 1.0
*/
public final class BigDecimalHolder implements Holder {
/** The <code>BigDecimal</code> contained by this holder. */
public BigDecimal value;
/**
* Make a new <code>BigDecimalHolder</code> with a <code>null</code> value.
*/
public BigDecimalHolder() {}
/**
* Make a new <code>BigDecimalHolder</code> with <code>value</code> as
* the value.
*
* @param value the <code>BigDecimal</code> to hold
*/
public BigDecimalHolder(BigDecimal value) {
this.value = value;
}
}
| 7,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.