index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/wsdd/TestBadWSDD.java
package test.wsdd; import junit.framework.TestCase; import org.apache.axis.Handler; import org.apache.axis.client.AdminClient; import org.apache.axis.configuration.XMLStringProvider; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.server.AxisServer; import org.apache.axis.transport.local.LocalTransport; import java.io.ByteArrayInputStream; /** * Try various bad deployments, and make sure that we get back reasonable * errors and don't screw up the engine's configuration. * * @author Glen Daniels (gdaniels@apache.org) */ public class TestBadWSDD extends TestCase { static final String HANDLER_NAME = "logger"; static final String PARAM_NAME = "testParam"; static final String PARAM_VAL = "testValue"; static final String goodWSDD = "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " + "xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" + " <handler type=\"java:org.apache.axis.handlers.LogHandler\" " + "name=\"" + HANDLER_NAME + "\">\n" + " <parameter name=\"" + PARAM_NAME + "\" value=\"" + PARAM_VAL + "\"/>\n" + " </handler>\n" + " <handler type=\"logger\" name=\"other\"/>\n" + " <service name=\"AdminService\" provider=\"java:MSG\">\n" + " <parameter name=\"allowedMethods\" value=\"AdminService\"/>" + " <parameter name=\"enableRemoteAdmin\" value=\"false\"/>" + " <parameter name=\"className\"" + " value=\"org.apache.axis.utils.Admin\"/>" + " </service>" + "</deployment>"; static final String header = "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " + "xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n"; static final String footer = "</deployment>"; static final String badHandler = " <handler name=\"nameButNoType\"/>\n"; /** * Initialize an engine with a single handler with a parameter set, and * another reference to that same handler with a different name. * * Make sure the param is set for both the original and the reference * handler. * */ public void testOptions() throws Exception { XMLStringProvider provider = new XMLStringProvider(goodWSDD); AxisServer server = new AxisServer(provider); Handler h1 = server.getHandler(HANDLER_NAME); assertNotNull("Couldn't get logger handler from engine!", h1); AdminClient client = new AdminClient(true); String doc = header + badHandler + footer; ByteArrayInputStream stream = new ByteArrayInputStream(doc.getBytes()); LocalTransport transport = new LocalTransport(server); transport.setUrl("local:///AdminService"); client.getCall().setTransport(transport); try { client.process(stream); } catch (Exception e) { return; } fail("Successfully processed bad WSDD!"); } }
7,300
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/jaxrpc/TestSOAPService.java
package test.jaxrpc; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Handler; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.message.Detail; import org.apache.axis.server.AxisServer; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.soap.SOAPFaultException; public class TestSOAPService extends AJAXRPC { /** * All Handlers in Chain return true for handleRequest and handleResponse * <p/> * <p/> * * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleResponse * H1.handleResponse * H0.handleResponse * * @throws Exception */ public void testPositiveCourseFlow() throws Exception { TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); soapService.invoke(new TestMessageContext()); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 1, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } /** * Tests scenario where one handler returns false on a call * to handleRequest(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest returns false * H1.handleResponse * H0.handleResponse * * @throws Exception */ public void testRequestHandlerReturnsFalse() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO RETURN FALSE handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); soapService.invoke(msgContext); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 1, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } /** * @throws Exception */ public void testRequestHandlerThrowsSFE() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO THROW SOAPFaultException handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", new SOAPFaultException(null, "f", "f", new Detail())); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); soapService.invoke(msgContext); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 1); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 1); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } /** * @throws Exception */ public void testRequestHandlerThrowsJAXRPCException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO THROW JAXRPCException handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } } public void testRequestHandlerThrowsRuntimeException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO THROW JAXRPCException handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } } public void testResponseHandlerReturnsFalse() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 3rd HANDLER IN THE CHAIN TO RETURN FALSE on handleResponse handler2Config.put("HANDLE_RESPONSE_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); soapService.invoke(msgContext); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } public void testResponseHandlerThrowsJAXRPCException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE CHAIN TO THROW JAXRPCException on handleResponse handler1Config.put("HANDLE_RESPONSE_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } } public void testResponseHandlerThrowsRuntimeException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE 2nd HANDLER IN THE CHAIN TO THROW RuntimeException on handleResponse handler1Config.put("HANDLE_RESPONSE_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } } public void testHandleFaultReturnsFalse() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE LAST HANDLER IN THE REQUEST CHAIN TO THROW SOAPFaultException handler2Config.put("HANDLE_REQUEST_RETURN_VALUE", new SOAPFaultException(null, "f", "f", new Detail())); handler1Config.put("HANDLE_FAULT_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); soapService.invoke(msgContext); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 1); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 1); } /** * Tests to see if we handle the scenario of a handler throwing a * runtime exception during the handleFault(...) processing correctly * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest SOAPFaultException * H2.handleFault * H1.handleFault throws JAXRPCException * * @throws Exception */ public void testFaultHandlerThrowsJAXRPCException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE LAST HANDLER IN THE REQUEST CHAIN TO THROW SOAPFaultException handler2Config.put("HANDLE_REQUEST_RETURN_VALUE", new SOAPFaultException(null, "f", "f", new Detail())); handler1Config.put("HANDLE_FAULT_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 1); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 1); } } /** * Tests to see if we handle the scenario of a handler throwing a * runtime exception during the handleFault(...) processing correctly * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest throws SOAPFaultException * H2.handleFault * H1.handleFault throws RuntimeException * * @throws Exception */ public void testFaultHandlerThrowsRuntimeException() throws Exception { SOAPService soapService = new SOAPService(); // SETUP THE LAST HANDLER IN THE REQUEST CHAIN TO THROW SOAPFaultException handler2Config.put("HANDLE_REQUEST_RETURN_VALUE", new SOAPFaultException(null, "f", "f", new Detail())); handler1Config.put("HANDLE_FAULT_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 1); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 1); } } /** * Tests scenario where service object throws Axis Fault. * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest * ServiceObject.invoke() throws AxisFault * H2.handleFault * H1.handleFault * H0.handleFault * * @throws Exception */ public void testServiceObjectThrowsAxisFault() throws Exception { Handler serviceHandler = new MockServiceHandler(); SOAPService soapService = new SOAPService(null, null, serviceHandler); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.init(); MessageContext msgContext = new TestMessageContext(); try { soapService.invoke(msgContext); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 1); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 1); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 1); } } private class TestMessageContext extends org.apache.axis.MessageContext { public String listByAreaCode = "<soap:Envelope\n" + "xmlns:s0=\"http://www.tilisoft.com/ws/LocInfo/literalTypes\"\n" + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + "<soap:Header>\n" + "<WSABIHeader>\n" + "<SubscriptionId>192168001100108165800640600008</SubscriptionId>\n" + "</WSABIHeader>\n" + "</soap:Header>\n" + "<soap:Body>\n" + "<s0:ListByAreaCode>\n" + "<s0:AreaCode>617</s0:AreaCode>\n" + "</s0:ListByAreaCode>\n" + "</soap:Body>\n" + "</soap:Envelope>\n"; public TestMessageContext() { super(new AxisServer()); Message message = new Message(listByAreaCode); message.setMessageType(Message.REQUEST); setRequestMessage(message); } } }
7,301
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/jaxrpc/AJAXRPC.java
package test.jaxrpc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.rpc.handler.HandlerChain; import javax.xml.rpc.handler.HandlerInfo; import junit.framework.TestCase; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.handlers.HandlerInfoChainFactory; /** * * * @author Guillaume Sauthier */ public abstract class AJAXRPC extends TestCase { HandlerInfo handlerInfo0 = null; HandlerInfo handlerInfo1 = null; HandlerInfo handlerInfo2 = null; Map handler0Config = null; protected Map handler1Config = null; protected Map handler2Config = null; /** * Sets up the handlerInfo and handlerConfigs for all tests. * Each test has 3 JAX-RPC Handlers of the same type to keep things * simple. * * @throws Exception */ protected void setUp() throws Exception { handlerInfo0 = new HandlerInfo(); handlerInfo0.setHandlerClass(AAAHandler.class); handlerInfo1 = new HandlerInfo(); handlerInfo1.setHandlerClass(AAAHandler.class); handlerInfo2 = new HandlerInfo(); handlerInfo2.setHandlerClass(AAAHandler.class); handler0Config = new HashMap(); handler1Config = new HashMap(); handler2Config = new HashMap(); handlerInfo0.setHandlerConfig(handler0Config); handlerInfo1.setHandlerConfig(handler1Config); handlerInfo2.setHandlerConfig(handler2Config); } /** * Convenience method to organize all test checking for a particular * handler. * <p/> * Checks to see if the expected number of calls to handleRequest, handleResponse * and handleFault reconciles with actuals * * @param message * @param handler the target handler to reconcile * @param numHandleRequest # of expected calls to handleRequest * @param numHandleResponse # of expected calls to handleResponse * @param numHandleFault # of expected call to handleFault */ protected void assertHandlerRuntime(String message, AAAHandler handler, int numHandleRequest, int numHandleResponse, int numHandleFault) { assertEquals(message + ": handleRequest", numHandleRequest, handler.getHandleRequestInvocations()); assertEquals(message + ": handleResponse", numHandleResponse, handler.getHandleResponseInvocations()); assertEquals(message + ": handleFault", numHandleFault, handler.getHandleFaultInvocations()); } /** * Convenience method to create a HandlerInfoChainFactory * * @return */ protected TestHandlerInfoChainFactory buildInfoChainFactory() { List handlerInfos = new ArrayList(); handlerInfos.add(handlerInfo0); handlerInfos.add(handlerInfo1); handlerInfos.add(handlerInfo2); TestHandlerInfoChainFactory factory = new TestHandlerInfoChainFactory( handlerInfos); return factory; } /** * Mock Service Handler used to simulate a service object throwing * an AxisFault. */ protected class MockServiceHandler extends BasicHandler { public void invoke(MessageContext msgContext) throws AxisFault { throw new AxisFault(); } } /** * Helper class for keeping references to the JAX-RPC Handlers * that are created by the Factory. * <p/> * This class allows us to access the individual handlers after * the test case has been executed in order to make sure that * the expected methods of the handler instance have been invoked. */ protected class TestHandlerInfoChainFactory extends HandlerInfoChainFactory { AAAHandler[] handlers; public TestHandlerInfoChainFactory(List handlerInfos) { super(handlerInfos); } public HandlerChain createHandlerChain() { HandlerChain chain = super.createHandlerChain(); handlers = new AAAHandler[chain.size()]; for (int i = 0; i < chain.size(); i++) { handlers[i] = (AAAHandler) chain.get(i); } return chain; } public AAAHandler[] getHandlers() { return handlers; } } }
7,302
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/jaxrpc/TestAxisClient.java
package test.jaxrpc; import javax.xml.namespace.QName; import javax.xml.rpc.JAXRPCException; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.Constants; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.client.AxisClient; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.configuration.FileProvider; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDTransport; import org.apache.axis.handlers.soap.SOAPService; /** * * * @author Guillaume Sauthier */ public class TestAxisClient extends AJAXRPC { /** * * * @author Guillaume Sauthier */ protected class AxisFaultWSDDTransport extends WSDDTransport { /** * @see org.apache.axis.deployment.wsdd.WSDDDeployableItem#makeNewInstance(org.apache.axis.EngineConfiguration) */ public Handler makeNewInstance(EngineConfiguration registry) throws ConfigurationException { return new MockServiceHandler(); } /** * @see org.apache.axis.deployment.wsdd.WSDDDeployableItem#getQName() */ public QName getQName() { return new QName("faulter"); } } /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * All Handlers in Chain return true for handleRequest and handleResponse * <p/> * <p/> * * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleResponse * H1.handleResponse * H0.handleResponse * * @throws Exception */ public void testPositiveCourseFlow() throws Exception { TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); client.invoke(context); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 1, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } /** * Tests scenario where one handler returns false on a call * to handleRequest(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest returns false * H1.handleResponse * H0.handleResponse * * @throws Exception */ public void testRequestHandlerReturnsFalse() throws Exception { // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO RETURN FALSE handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); client.invoke(context); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 1, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } /** * Tests scenario where one handler throws a JAXRPCException * to handleRequest(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest throws JAXRPCException * * @throws Exception */ public void testRequestHandlerThrowsJAXRPCException() throws Exception { // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO THROW JAXRPCException handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); try { client.invoke(context); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } } /** * Tests scenario where one handler throws a RuntimeException * to handleRequest(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest throws JAXRPCException * * @throws Exception */ public void testRequestHandlerThrowsRuntimeException() throws Exception { // SETUP THE 2nd HANDLER IN THE REQUEST CHAIN TO THROW JAXRPCException handler1Config.put("HANDLE_REQUEST_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 0, 0, 0); } } /** * Tests scenario where one handler returns false on a call * to handleResponse(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleResponse return false * * @throws Exception */ public void testResponseHandlerReturnsFalse() throws Exception { // SETUP THE 3rd HANDLER IN THE CHAIN TO RETURN FALSE on handleResponse handler2Config.put("HANDLE_RESPONSE_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); client.invoke(context); AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } /** * Tests scenario where one handler throws JAXRPCException on a call * to handleResponse(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleResponse * H1.handlerResponse throws JAXRPCException * * @throws Exception */ public void testResponseHandlerThrowsJAXRPCException() throws Exception { // SETUP THE 2nd HANDLER IN THE CHAIN TO THROW JAXRPCException on handleResponse handler1Config.put("HANDLE_RESPONSE_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } } /** * Tests scenario where one handler throws RuntimeException on a call * to handleResponse(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleResponse * H1.handlerResponse throws RuntimeException * * @throws Exception */ public void testResponseHandlerThrowsRuntimeException() throws Exception { // SETUP THE 2nd HANDLER IN THE CHAIN TO THROW RuntimeException on handleResponse handler1Config.put("HANDLE_RESPONSE_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); MessageContext context = new TestMessageContext(client); context.setTransportName("local"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 1, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 1, 0); } } /** * Tests scenario where one handler returns false on a call * to handleFault(...). * <p/> * Expected Chain invocation sequence looks like..... * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleFault * H1.handleFault return false * * @throws Exception */ public void testHandleFaultReturnsFalse() throws Exception { // SETUP A MOCK SERVICE THAT SIMULATE A SOAPFAULT THROWN BY ENDPOINT handler1Config.put("HANDLE_FAULT_RETURN_VALUE", Boolean.FALSE); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); SOAPService soapService = new SOAPService(); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); addFaultTransport(client); MessageContext context = new TestMessageContext(client); context.setTransportName("faulter"); context.setService(soapService); try { client.invoke(context); fail("Expecting an AxisFault"); } catch (AxisFault f) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 0); } } /** * Tests to see if we handle the scenario of a handler throwing a * runtime exception during the handleFault(...) processing correctly * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleFault * H1.handleFault throws JAXRPCException * * @throws Exception */ public void testFaultHandlerThrowsJAXRPCException() throws Exception { handler1Config.put("HANDLE_FAULT_RETURN_VALUE", new JAXRPCException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); Handler serviceHandler = new MockServiceHandler(); SOAPService soapService = new SOAPService(null, serviceHandler, null); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); addFaultTransport(client); MessageContext context = new TestMessageContext(client); context.setTransportName("faulter"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 0); } } /** * Tests to see if we handle the scenario of a handler throwing a * runtime exception during the handleFault(...) processing correctly * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest * H2.handleFault * H1.handleFault throws RuntimeException * * @throws Exception */ public void testFaultHandlerThrowsRuntimeException() throws Exception { // SETUP THE LAST HANDLER IN THE REQUEST CHAIN TO THROW SOAPFaultException handler1Config.put("HANDLE_FAULT_RETURN_VALUE", new RuntimeException()); TestHandlerInfoChainFactory factory = buildInfoChainFactory(); Handler serviceHandler = new MockServiceHandler(); SOAPService soapService = new SOAPService(null, serviceHandler, null); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); addFaultTransport(client); MessageContext context = new TestMessageContext(client); context.setTransportName("faulter"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 0); } } /** * Tests scenario where service object throws Axis Fault. * <p/> * Expected chain sequence: * H0.handleRequest * H1.handleRequest * H2.handleRequest * ServiceObject.invoke() throws AxisFault * H2.handleFault * H1.handleFault * H0.handleFault * * @throws Exception */ public void testServiceObjectThrowsAxisFault() throws Exception { TestHandlerInfoChainFactory factory = buildInfoChainFactory(); Handler serviceHandler = new MockServiceHandler(); SOAPService soapService = new SOAPService(null, serviceHandler, null); soapService.setOption(Constants.ATTR_HANDLERINFOCHAIN, factory); soapService.setOption(Call.WSDL_SERVICE, new Service()); soapService.setOption(Call.WSDL_PORT_NAME, new QName("Fake")); soapService.init(); AxisClient client = new AxisClient(); addFaultTransport(client); MessageContext context = new TestMessageContext(client); context.setTransportName("faulter"); context.setService(soapService); try { client.invoke(context); fail("Expected AxisFault to be thrown"); } catch (AxisFault e) { AAAHandler handlerZero = factory.getHandlers()[0]; AAAHandler handlerOne = factory.getHandlers()[1]; AAAHandler handlerTwo = factory.getHandlers()[2]; assertHandlerRuntime("handlerZero", handlerZero, 1, 0, 0); assertHandlerRuntime("handlerOne", handlerOne, 1, 0, 0); assertHandlerRuntime("handlerTwo", handlerTwo, 1, 0, 0); } } /** * Configure a transport handler that simulate a Fault on server-side * @param client AxisClient */ private void addFaultTransport(AxisClient client) { FileProvider config = (FileProvider) client.getConfig(); WSDDDeployment depl = config.getDeployment(); if (depl == null) { depl = new WSDDDeployment(); } WSDDTransport trans = new AxisFaultWSDDTransport(); depl.deployTransport(trans); } private class TestMessageContext extends org.apache.axis.MessageContext { public String listByAreaCode = "<soap:Envelope\n" + "xmlns:s0=\"http://www.tilisoft.com/ws/LocInfo/literalTypes\"\n" + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + "<soap:Header>\n" + "<WSABIHeader>\n" + "<SubscriptionId>192168001100108165800640600008</SubscriptionId>\n" + "</WSABIHeader>\n" + "</soap:Header>\n" + "<soap:Body>\n" + "<s0:ListByAreaCode>\n" + "<s0:AreaCode>617</s0:AreaCode>\n" + "</s0:ListByAreaCode>\n" + "</soap:Body>\n" + "</soap:Envelope>\n"; public TestMessageContext(AxisClient client) { super(client); Message message = new Message(listByAreaCode); message.setMessageType(Message.REQUEST); setRequestMessage(message); } } }
7,303
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/jaxrpc/AAAHandler.java
package test.jaxrpc; import javax.xml.namespace.QName; import javax.xml.rpc.handler.Handler; import javax.xml.rpc.handler.HandlerInfo; import javax.xml.rpc.handler.MessageContext; import java.util.Map; public class AAAHandler implements Handler { private int handleRequestInvocations = 0; private int handleResponseInvocations = 0; private int handleFaultInvocations = 0; public Object handleRequestReturnValue = null; public Object handleResponseReturnValue = null; public Object handleFaultReturnValue = null; public boolean handleRequest(MessageContext context) { handleRequestInvocations++; return returnAppropriateValue(handleRequestReturnValue); } public boolean handleResponse(MessageContext context) { handleResponseInvocations++; return returnAppropriateValue(handleResponseReturnValue); } public boolean handleFault(MessageContext context) { handleFaultInvocations++; return returnAppropriateValue(handleFaultReturnValue); } private boolean returnAppropriateValue(Object returnValue) { if (returnValue == null) return true; else if (returnValue instanceof Boolean) return ((Boolean) returnValue).booleanValue(); else if (returnValue instanceof RuntimeException) throw (RuntimeException) returnValue; else { throw new RuntimeException(); } } public void init(HandlerInfo config) { Map map = config.getHandlerConfig(); handleRequestReturnValue = map.get("HANDLE_REQUEST_RETURN_VALUE"); handleResponseReturnValue = map.get("HANDLE_RESPONSE_RETURN_VALUE"); handleFaultReturnValue = map.get("HANDLE_FAULT_RETURN_VALUE"); } public void destroy() { } public QName[] getHeaders() { return new QName[0]; } public int getHandleRequestInvocations() { return handleRequestInvocations; } public int getHandleResponseInvocations() { return handleResponseInvocations; } public int getHandleFaultInvocations() { return handleFaultInvocations; } public Object getHandleRequestReturnValue() { return handleRequestReturnValue; } public void setHandleRequestReturnValue(Object handleRequestReturnValue) { this.handleRequestReturnValue = handleRequestReturnValue; } public Object getHandleResponseReturnValue() { return handleResponseReturnValue; } public void setHandleResponseReturnValue(Object handleResponseReturnValue) { this.handleResponseReturnValue = handleResponseReturnValue; } public Object getHandleFaultReturnValue() { return handleFaultReturnValue; } public void setHandleFaultReturnValue(Object handleFaultReturnValue) { this.handleFaultReturnValue = handleFaultReturnValue; } }
7,304
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/chains/TestSimpleChain.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test.chains; import junit.framework.TestCase; import org.apache.axis.AxisFault; import org.apache.axis.Handler; import org.apache.axis.InternalException; import org.apache.axis.MessageContext; import org.apache.axis.SimpleChain; import org.apache.axis.handlers.BasicHandler; public class TestSimpleChain extends TestCase { private class TestHandler extends BasicHandler { public TestHandler() {} public void invoke(MessageContext msgContext) throws AxisFault {} } public void testSimpleChainAddHandler() { SimpleChain c = new SimpleChain(); Handler h1 = new TestHandler(); assertTrue("Empty chain has a handler", !c.contains(h1)); c.addHandler(h1); assertTrue("Added handler not in chain", c.contains(h1)); } public void testSimpleChainAddHandlerAfterInvoke() { try { SimpleChain c = new SimpleChain(); Handler h1 = new TestHandler(); c.addHandler(h1); // A null engine is good enough for this test MessageContext mc = new MessageContext(null); c.invoke(mc); // while testing, disable noise boolean oldLogging = InternalException.getLogging(); InternalException.setLogging(false); try { Handler h2 = new TestHandler(); c.addHandler(h2); assertTrue("Handler added after chain invoked", false); } catch (Exception e) { // Correct behaviour. Exact exception isn't critical } // resume noise InternalException.setLogging(oldLogging); } catch (AxisFault af) { assertTrue("Unexpected exception", false); } } }
7,305
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/chains/TestChainFault.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test.chains; import junit.framework.TestCase; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.SimpleChain; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.server.AxisServer; import javax.xml.soap.SOAPBody; /** * Used to verify that Faults are processed properly in the Handler chain * @author Russell Butek (butek@us.ibm.com) * @author Chris Haddad <haddadc@cobia.net> */ public class TestChainFault extends TestCase { // correlation message public static String FAULT_MESSAGE = "Blew a gasket!"; private class TestMessageContext extends MessageContext { private int hcount = 0; public TestMessageContext() { super(new AxisServer()); } public void incCount() { hcount++; } public void decCount() { hcount--; } public int count() { return hcount; } } private class TestHandler extends BasicHandler { private int chainPos; private boolean doFault = false; private String stFaultCatch = null; /* The following state really relates to a Message Context, so this Handler * must not be used for more than one Message Context. However, it * is sufficient for the purpose of this testcase. */ private boolean invoked = false; public TestHandler(int pos) { chainPos = pos; } public void setToFault() { doFault = true; } public void setFaultCatch(String stValue) { stFaultCatch = stValue; } public String getFaultCatch() { return stFaultCatch; } public void invoke(MessageContext msgContext) throws AxisFault { TestMessageContext mc = (TestMessageContext)msgContext; assertEquals("Handler.invoke out of sequence", chainPos, mc.count()); invoked = true; if (doFault) { throw new AxisFault(TestChainFault.FAULT_MESSAGE); } mc.incCount(); } public void onFault(MessageContext msgContext) { TestMessageContext mc = (TestMessageContext)msgContext; mc.decCount(); assertEquals("Handler.onFault out of sequence", chainPos, mc.count()); assertTrue("Handler.onFault protocol error", invoked); // grap the Soap Fault String stFaultCatch = getFaultString(msgContext); } } /** * Extract the fault string from the Soap Response * **/ String getFaultString(MessageContext msgContext) { String stRetval = null; Message message = msgContext.getResponseMessage(); try { if (message != null) { SOAPBody oBody = message.getSOAPEnvelope().getBody(); stRetval = oBody.getFault().getFaultString(); } } catch (javax.xml.soap.SOAPException e) { e.printStackTrace(); assertTrue("Unforseen soap exception", false); } catch (AxisFault f) { f.printStackTrace(); assertTrue("Unforseen axis fault", false); } return stRetval; } public void testSimpleChainFaultAfterInvoke() { try { SimpleChain c = new SimpleChain(); for (int i = 0; i < 5; i++) { c.addHandler(new TestHandler(i)); } TestMessageContext mc = new TestMessageContext(); c.invoke(mc); c.onFault(mc); assertEquals("Some onFaults were missed", mc.count(), 0); } catch (Exception ex) { assertTrue("Unexpected exception", false); ex.printStackTrace(); } } public void testSimpleChainFaultDuringInvoke() { try { SimpleChain c = new SimpleChain(); for (int i = 0; i < 5; i++) { TestHandler th = new TestHandler(i); if (i == 3) { th.setToFault(); } c.addHandler(th); } TestMessageContext mc = new TestMessageContext(); try { c.invoke(mc); assertTrue("Testcase error - didn't throw fault", false); } catch (AxisFault f) { assertEquals("Some onFaults were missed", mc.count(), 0); } } catch (Exception ex) { ex.printStackTrace(); assertTrue("Unexpected exception", false); } } /** * Ensure that the fault detail is being passed back * to handlers that executed prior to the fault **/ public void testFaultDetailAvailableDuringInvoke() { // the handler instance to validate // NOTE:must execute before the handler that throws the fault TestHandler testHandler = null; try { SimpleChain c = new SimpleChain(); for (int i = 0; i < 5; i++) { TestHandler th = new TestHandler(i); if (i == 2) testHandler = th; if (i == 3) { th.setToFault(); } c.addHandler(th); } TestMessageContext mc = new TestMessageContext(); try { c.invoke(mc); assertTrue("Testcase error - didn't throw fault", false); } catch (AxisFault f) { // did we save off the fault string? assertEquals("faultstring does not match constant", TestChainFault.FAULT_MESSAGE, testHandler.getFaultCatch()); // does saved faultString match AxisFault? assertEquals("Fault not caught by handler", testHandler.getFaultCatch(),f.getFaultString()); } } catch (Exception ex) { assertTrue("Unexpected exception", false); } } }
7,306
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/test/session/TestSimpleSession.java
package test.session; import junit.framework.TestCase; import org.apache.axis.EngineConfiguration; import org.apache.axis.MessageContext; 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.configuration.XMLStringProvider; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.handlers.SimpleSessionHandler; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.providers.java.RPCProvider; import org.apache.axis.server.AxisServer; import org.apache.axis.session.Session; import org.apache.axis.session.SimpleSession; import org.apache.axis.transport.local.LocalTransport; import javax.xml.rpc.ServiceException; import javax.xml.rpc.server.ServiceLifecycle; /** * Test the SimpleSession implementation (using SOAP headers for session * maintenance) * * @author Glen Daniels (gdaniels@apache.org) */ public class TestSimpleSession extends TestCase implements ServiceLifecycle { static final String clientWSDD = "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " + "xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" + " <handler type=\"java:org.apache.axis.handlers.SimpleSessionHandler\" " + "name=\"SimpleSessionHandler\"/>\n" + " <service name=\"sessionTest\">\n" + " <requestFlow><handler type=\"SimpleSessionHandler\"/></requestFlow>\n" + " <responseFlow><handler type=\"SimpleSessionHandler\"/></responseFlow>\n" + " </service>\n" + " <transport name=\"local\" " + "pivot=\"java:org.apache.axis.transport.local.LocalSender\"/>\n" + "</deployment>"; static XMLStringProvider clientProvider = new XMLStringProvider(clientWSDD); public void testSessionAPI() { SimpleSession session = new SimpleSession(); Object val = new Float(5.6666); session.set("test", val); assertEquals("\"test\" equals \"" + session.get("test") + "\", not \"" + val + "\" as expected", val, session.get("test")); session.remove("test"); assertNull("Did not remove \"test\" from the session successfully", session.get("test")); } /** * Actually test the session functionality using SOAP headers. * * Deploy a simple RPC service which returns a session-based call * counter. Check it out using local transport. To do this we need to * make sure the SimpleSessionHandler is deployed on the request and * response chains of both the client and the server. * */ public void testSessionService() throws Exception { // Set up the server side SimpleSessionHandler sessionHandler = new SimpleSessionHandler(); // Set a 3-second reap period, and a 3-second timeout sessionHandler.setReapPeriodicity(3); sessionHandler.setDefaultSessionTimeout(3); SOAPService service = new SOAPService(sessionHandler, new RPCProvider(), sessionHandler); service.setName("sessionTestService"); service.setOption("scope", "session"); service.setOption("className", "test.session.TestSimpleSession"); service.setOption("allowedMethods", "counter"); EngineConfiguration defaultConfig = EngineConfigurationFactoryFinder.newFactory().getServerEngineConfig(); SimpleProvider config = new SimpleProvider(defaultConfig); config.deployService("sessionTest", service); AxisServer server = new AxisServer(config); // Set up the client side (using the WSDD above) Service svc = new Service(clientProvider); Call call = (Call)svc.createCall(); svc.setMaintainSession(true); call.setTransport(new LocalTransport(server)); // Try it - first invocation should return 1. Integer count = (Integer)call.invoke("sessionTest", "counter", null); assertNotNull("count was null!", count); assertEquals("count was wrong", 1, count.intValue()); // We should have init()ed a single service object assertEquals("Wrong # of calls to init()!", 1, initCalls); // Next invocation should return 2, assuming the session-based // counter is working. count = (Integer)call.invoke("sessionTest", "counter", null); assertEquals("count was wrong", 2, count.intValue()); // We should still have 1 assertEquals("Wrong # of calls to init()!", 1, initCalls); // Now start fresh and confirm a new session Service svc2 = new Service(clientProvider); Call call2 = (Call)svc2.createCall(); svc2.setMaintainSession(true); call2.setTransport(new LocalTransport(server)); // New session should cause us to return 1 again. count = (Integer)call2.invoke("sessionTest", "counter", null); assertNotNull("count was null on third call!", count); assertEquals("New session count was incorrect", 1, count.intValue()); // We should have init()ed 2 service objects now assertEquals("Wrong # of calls to init()!", 2, initCalls); // And no destroy()s yet... assertEquals("Shouldn't have called destroy() yet!", 0, destroyCalls); // Wait around a few seconds to let the first session time out Thread.sleep(4000); // And now we should get a new session, therefore going back to 1 count = (Integer)call.invoke("sessionTest", "counter", null); assertEquals("count after timeout was incorrect", 1, count.intValue()); // Check init/destroy counts assertEquals("Wrong # of calls to init()!", 3, initCalls); assertEquals("Wrong # of calls to destroy()!", 2, destroyCalls); } /** * This is our service method for testing session data. Simply * increments a session-scoped counter. */ public Integer counter() throws Exception { Session session = MessageContext.getCurrentContext().getSession(); if (session == null) throw new Exception("No session in MessageContext!"); Integer count = (Integer)session.get("counter"); if (count == null) { count = new Integer(0); } count = new Integer(count.intValue() + 1); session.set("counter", count); return count; } private static int initCalls = 0; private static int destroyCalls = 0; /** * After a service endpoint object (an instance of a service * endpoint class) is instantiated, the JAX-RPC runtime system * invokes the init method.The service endpoint class uses the * init method to initialize its configuration and setup access * to any external resources. * @param context Initialization context for a JAX-RPC service endpoint; Carries javax.servlet.ServletContext for the servlet based JAX-RPC endpoints * @throws ServiceException If any error in initialization of the service endpoint; or if any illegal context has been provided in the init method */ public void init(Object context) throws ServiceException { initCalls++; } /** * JAX-RPC runtime system ends the lifecycle of a service endpoint * object by invoking the destroy method. The service endpoint * releases its resourcesin the implementation of the destroy * method. */ public void destroy() { destroyCalls++; } }
7,307
0
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/test/java/org/apache/axis/attachments/TestDimeBodyPart.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.attachments; import junit.framework.TestCase; import org.apache.axiom.testutils.activation.InstrumentedDataSource; import org.apache.axiom.testutils.activation.RandomDataSource; import org.apache.commons.io.output.NullOutputStream; public class TestDimeBodyPart extends TestCase { public void testWriteToWithDynamicContentDataHandlerClosesInputStreams() throws Exception { InstrumentedDataSource ds = new InstrumentedDataSource(new RandomDataSource(1000)); DimeBodyPart bp = new DimeBodyPart(new DynamicContentDataHandler(ds), "1234"); bp.write(new NullOutputStream(), (byte)0); assertEquals(0, ds.getOpenStreamCount()); } }
7,308
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/AxisEngine.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; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.TypeMappingImpl; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.session.Session; import org.apache.axis.session.SimpleSession; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.cache.ClassCache; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.xml.rpc.server.ServiceLifecycle; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; /** * An <code>AxisEngine</code> is the base class for AxisClient and * AxisServer. Handles common functionality like dealing with the * handler/service registries and loading properties. * * @author Glen Daniels (gdaniels@apache.org) * @author Glyn Normington (glyn@apache.org) */ public abstract class AxisEngine extends BasicHandler { /** * The <code>Log</code> for all message logging. */ protected static Log log = LogFactory.getLog(AxisEngine.class.getName()); // Engine property names public static final String PROP_XML_DECL = "sendXMLDeclaration"; public static final String PROP_DEBUG_LEVEL = "debugLevel"; public static final String PROP_DEBUG_FILE = "debugFile"; public static final String PROP_DOMULTIREFS = "sendMultiRefs"; public static final String PROP_DISABLE_PRETTY_XML = "disablePrettyXML"; public static final String PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION = "enableNamespacePrefixOptimization"; public static final String PROP_PASSWORD = "adminPassword"; public static final String PROP_SYNC_CONFIG = "syncConfiguration"; public static final String PROP_SEND_XSI = "sendXsiTypes"; public static final String PROP_ATTACHMENT_DIR = "attachments.Directory"; public static final String PROP_ATTACHMENT_IMPLEMENTATION = "attachments.implementation" ; public static final String PROP_ATTACHMENT_CLEANUP = "attachment.DirectoryCleanUp"; public static final String PROP_DEFAULT_CONFIG_CLASS = "axis.engineConfigClass"; public static final String PROP_SOAP_VERSION = "defaultSOAPVersion"; public static final String PROP_SOAP_ALLOWED_VERSION = "singleSOAPVersion"; public static final String PROP_TWOD_ARRAY_ENCODING = "enable2DArrayEncoding"; public static final String PROP_XML_ENCODING = "axis.xmlEncoding"; public static final String PROP_XML_REUSE_SAX_PARSERS = "axis.xml.reuseParsers"; public static final String PROP_BYTE_BUFFER_BACKING = "axis.byteBuffer.backing"; public static final String PROP_BYTE_BUFFER_CACHE_INCREMENT = "axis.byteBuffer.cacheIncrement"; public static final String PROP_BYTE_BUFFER_RESIDENT_MAX_SIZE = "axis.byteBuffer.residentMaxSize"; public static final String PROP_BYTE_BUFFER_WORK_BUFFER_SIZE = "axis.byteBuffer.workBufferSize"; public static final String PROP_EMIT_ALL_TYPES = "emitAllTypesInWSDL"; /** * Set this property to 'true' when you want Axis to avoid soap encoded * types to work around a .NET problem where it wont accept soap encoded * types for a (soap encoded!) array. */ public static final String PROP_DOTNET_SOAPENC_FIX = "dotNetSoapEncFix"; /** Compliance with WS-I Basic Profile. */ public static final String PROP_BP10_COMPLIANCE = "ws-i.bp10Compliance"; public static final String DEFAULT_ATTACHMENT_IMPL="org.apache.axis.attachments.AttachmentsImpl"; public static final String ENV_ATTACHMENT_DIR = "axis.attachments.Directory"; public static final String ENV_SERVLET_REALPATH = "servlet.realpath"; public static final String ENV_SERVLET_CONTEXT = "servletContext"; // Default admin. password private static final String DEFAULT_ADMIN_PASSWORD = "admin"; /** Our go-to guy for configuration... */ protected EngineConfiguration config; /** Has the user changed the password yet? True if they have. */ protected boolean _hasSafePassword = false; /** * Should we save the engine config each time we modify it? True if we * should. */ protected boolean shouldSaveConfig = false; /** Java class cache. */ protected transient ClassCache classCache = new ClassCache(); /** * This engine's Session. This Session supports "application scope" * in the Apache SOAP sense... if you have a service with "application * scope", have it store things in this Session. */ private Session session = new SimpleSession(); /** * What actor URIs hold for the entire engine? Find them here. */ private ArrayList actorURIs = new ArrayList(); /** * Thread local storage used for locating the active message context. * This information is only valid for the lifetime of this request. */ private static ThreadLocal currentMessageContext = new ThreadLocal(); /** * Set the active message context. * * @param mc - the new active message context. */ protected static void setCurrentMessageContext(MessageContext mc) { currentMessageContext.set(mc); } /** * Get the active message context. * * @return the current active message context */ public static MessageContext getCurrentMessageContext() { return (MessageContext) currentMessageContext.get(); } /** * Construct an AxisEngine using the specified engine configuration. * * @param config the EngineConfiguration for this engine */ public AxisEngine(EngineConfiguration config) { this.config = config; init(); } /** * Initialize the engine. Multiple calls will (may?) return the engine to * the intialized state. */ public void init() { if (log.isDebugEnabled()) { log.debug("Enter: AxisEngine::init"); } // The SOAP/XSD stuff is in the default TypeMapping of the TypeMappingRegistry. //getTypeMappingRegistry().setParent(SOAPTypeMappingRegistry.getSingletonDelegate()); try { config.configureEngine(this); } catch (Exception e) { throw new InternalException(e); } /*Set the default attachment implementation */ setOptionDefault(PROP_ATTACHMENT_IMPLEMENTATION, AxisProperties.getProperty("axis." + PROP_ATTACHMENT_IMPLEMENTATION )); setOptionDefault(PROP_ATTACHMENT_IMPLEMENTATION, DEFAULT_ATTACHMENT_IMPL); // Check for the property "dotnetsoapencfix" which will turn // off soap encoded types to work around a bug in .NET where // it wont accept soap encoded array types. final Object dotnet = getOption(PROP_DOTNET_SOAPENC_FIX); if (JavaUtils.isTrue(dotnet)) { // This is a static property of the type mapping // that will ignore SOAPENC types when looking up // QNames of java types. TypeMappingImpl.dotnet_soapenc_bugfix = true; } if (log.isDebugEnabled()) { log.debug("Exit: AxisEngine::init"); } } /** * Cleanup routine removes application scoped objects. * * There is a small risk of this being called more than once * so the cleanup should be designed to resist that event. */ public void cleanup() { super.cleanup(); // Let any application-scoped service objects know that we're going // away... Enumeration keys = session.getKeys(); if (keys != null) { while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); Object obj = session.get(key); if (obj != null && obj instanceof ServiceLifecycle) { ((ServiceLifecycle)obj).destroy(); } session.remove(key); } } } /** Write out our engine configuration. */ public void saveConfiguration() { if (!shouldSaveConfig) return; try { config.writeEngineConfig(this); } catch (Exception e) { log.error(Messages.getMessage("saveConfigFail00"), e); } } /** * Get the <code>EngineConfiguration</code> used throughout this * <code>AxisEngine</code> instance. * * @return the engine configuration instance */ public EngineConfiguration getConfig() { return config; } /** * Discover if this <code>AxisEngine</code> has a safe password. * * @return true if it is safe, false otherwise */ public boolean hasSafePassword() { return _hasSafePassword; } /** * Set the administration password. * * @param pw the literal value of the password as a <code>String</code> */ public void setAdminPassword(String pw) { setOption(PROP_PASSWORD, pw); _hasSafePassword = true; saveConfiguration(); } /** * Set the flag that controls if the configuration should be saved. * * @param shouldSaveConfig true if the configuration should be changed, * false otherwise */ public void setShouldSaveConfig(boolean shouldSaveConfig) { this.shouldSaveConfig = shouldSaveConfig; } // fixme: could someone who knows double-check I've got the semantics of // this right? /** * Get the <code>Handler</code> for a particular local name. * * @param name the local name of the request type * @return the <code>Handler</code> for this request type * @throws AxisFault */ public Handler getHandler(String name) throws AxisFault { try { return config.getHandler(new QName(null, name)); } catch (ConfigurationException e) { throw new AxisFault(e); } } // fixme: could someone who knows double-check I've got the semantics of // this right? /** * Get the <code>SOAPService</code> for a particular local name. * * @param name the local name of the request type * @return the <code>SOAPService</code> for this request type * @throws AxisFault */ public SOAPService getService(String name) throws AxisFault { try { return config.getService(new QName(null, name)); } catch (ConfigurationException e) { try { return config.getServiceByNamespaceURI(name); } catch (ConfigurationException e1) { throw new AxisFault(e); } } } /** * Get the <code>Handler</code> that implements the transport for a local * name. * * @param name the local name to fetch the transport for * @return a <code>Handler</code> for this local name * @throws AxisFault */ public Handler getTransport(String name) throws AxisFault { try { return config.getTransport(new QName(null, name)); } catch (ConfigurationException e) { throw new AxisFault(e); } } /** * Get the <code>TypeMappingRegistry</code> for this axis engine. * * @return the <code>TypeMappingRegistry</code> if possible, or null if * there is any error resolving it */ public TypeMappingRegistry getTypeMappingRegistry() { TypeMappingRegistry tmr = null; try { tmr = config.getTypeMappingRegistry(); } catch (ConfigurationException e) { log.error(Messages.getMessage("axisConfigurationException00"), e); } return tmr; } /** * Get the global request <code>Handler</code>. * * @return the <code>Handler</code> used for global requests * @throws ConfigurationException */ public Handler getGlobalRequest() throws ConfigurationException { return config.getGlobalRequest(); } /** * Get the global respones <code>Handler</code>. * * @return the <code>Handler</code> used for global responses * @throws ConfigurationException */ public Handler getGlobalResponse() throws ConfigurationException { return config.getGlobalResponse(); } // fixme: publishing this as ArrayList prevents us moving to another // List impl later /** * Get a list of actor URIs that hold for the entire engine. * * @return an <code>ArrayList</code> of all actor URIs as * <code>Strings</code> */ public ArrayList getActorURIs() { return (ArrayList)actorURIs.clone(); } /** * Add an actor by uri that will hold for the entire engine. * * @param uri a <code>String</code> giving the uri of the actor to add */ public void addActorURI(String uri) { actorURIs.add(uri); } /** * Remove an actor by uri that will hold for the entire engine. * * @param uri a <code>String</code> giving the uri of the actor to remove */ public void removeActorURI(String uri) { actorURIs.remove(uri); } /** * Client engine access. * <p> * An AxisEngine may define another specific AxisEngine to be used * by newly created Clients. For instance, a server may * create an AxisClient and allow deployment to it. Then * the server's services may access the AxisClient's deployed * handlers and transports. * * @return an <code>AxisEngine</code> that is the client engine */ public abstract AxisEngine getClientEngine (); /** * Administration and management APIs * * These can get called by various admin adapters, such as JMX MBeans, * our own Admin client, web applications, etc... * */ /** * List of options which should be converted from Strings to Booleans * automatically. Note that these options are common to all XML * web services. */ private static final String [] BOOLEAN_OPTIONS = new String [] { PROP_DOMULTIREFS, PROP_SEND_XSI, PROP_XML_DECL, PROP_DISABLE_PRETTY_XML, PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION }; /** * Normalise the engine's options. * <p> * Convert boolean options from String to Boolean and default * any ommitted boolean options to TRUE. Default the admin. * password. * * @param handler the <code>Handler</code> to normalise; instances of * <code>AxisEngine</code> get extra data normalised */ public static void normaliseOptions(Handler handler) { // Convert boolean options to Booleans so we don't need to use // string comparisons. Default is "true". for (int i = 0; i < BOOLEAN_OPTIONS.length; i++) { Object val = handler.getOption(BOOLEAN_OPTIONS[i]); if (val != null) { if (val instanceof Boolean) continue; if (JavaUtils.isFalse(val)) { handler.setOption(BOOLEAN_OPTIONS[i], Boolean.FALSE); continue; } } else { if (!(handler instanceof AxisEngine)) continue; } // If it was null or not "false"... handler.setOption(BOOLEAN_OPTIONS[i], Boolean.TRUE); } // Deal with admin password's default value. if (handler instanceof AxisEngine) { AxisEngine engine = (AxisEngine)handler; if (!engine.setOptionDefault(PROP_PASSWORD, DEFAULT_ADMIN_PASSWORD)) { engine.setAdminPassword( (String)engine.getOption(PROP_PASSWORD)); } } } /** * (Re-)load the global options from the registry. * * @throws ConfigurationException */ public void refreshGlobalOptions() throws ConfigurationException { Hashtable globalOptions = config.getGlobalOptions(); if (globalOptions != null) setOptions(globalOptions); normaliseOptions(this); // fixme: If we change actorURIs to List, this copy constructor can // go away... actorURIs = new ArrayList(config.getRoles()); } /** * Get the <code>Session</code> object associated with the application * session. * * @return a <code>Session</code> scoped to the application */ public Session getApplicationSession () { return session; } /** * Get the <code>ClassCache</code> associated with this engine. * * @return the class cache */ public ClassCache getClassCache() { return classCache; } }
7,309
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Message.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; import org.apache.axis.attachments.Attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.MimeHeaders; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.Collections; /** * A complete SOAP (and/or XML-RPC, eventually) message. * Includes both the root part (as a SOAPPart), and zero or * more MIME attachments (as AttachmentParts). * <p> * Eventually should be refactored to generalize SOAPPart * for multiple protocols (XML-RPC?). * * @author Rob Jellinghaus (robj@unrealities.com) * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@allaire.com) * @author Rick Rineholt * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class Message extends javax.xml.soap.SOAPMessage implements java.io.Serializable { /** * The <code>Log</code> that this class uses for logging all messages. */ protected static Log log = LogFactory.getLog(Message.class.getName()); /** Message is a request. */ public static final String REQUEST = "request"; /** Message is a a response. */ public static final String RESPONSE = "response"; /** MIME parts defined for messages. */ public static final String MIME_MULTIPART_RELATED = "multipart/related"; /** DIME parts defined for messages. */ public static final String MIME_APPLICATION_DIME = "application/dime"; /** Content Type for MTOM/XOP */ public static final String CONTENT_TYPE_MTOM = "application/xop+xml"; /** Default Attachments Implementation class. */ public static final String DEFAULT_ATTACHMNET_IMPL="org.apache.axis.attachments.AttachmentsImpl"; /** Current Attachment implementation. */ private static String mAttachmentsImplClassName=DEFAULT_ATTACHMNET_IMPL; /** Look at the input stream to find the headers to decide the mime type. */ public static final String MIME_UNKNOWN = " "; // fixme: is this constrained to two values - request/response (e.g. // REQUEST and RESPONSE)? If so, this needs documenting in the get/set // methods and/or converting into a type-safe e-num. Potentially get/set // methods should check these values & throw IllegalArgumentException /** * The messageType indicates whether this is request or response. */ private String messageType; /** * This Message's SOAPPart. Will always be here. */ private SOAPPart mSOAPPart; /** * This Message's Attachments object, which manages the attachments * contained in this Message. */ private Attachments mAttachments = null; private MimeHeaders headers; private boolean saveRequired = true; /** * Returns the name of the class prividing Attachment Implementation. * * @return class name */ public static String getAttachmentImplClassName(){ return mAttachmentsImplClassName; } private MessageContext msgContext; /** * Get the message type. * * @return the message type <code>String</code> */ public String getMessageType() { return messageType; } /** * Set the message type. * * @param messageType the message type <code>String</code> */ public void setMessageType(String messageType) { this.messageType = messageType; } /** * Get the context associated with this message. * * @return the message context for this message */ public MessageContext getMessageContext() { return msgContext; } /** * Set the context associated with this message. * * @param msgContext the message context for this message */ public void setMessageContext(MessageContext msgContext) { this.msgContext = msgContext; } /** * Construct a Message, using the provided initialContents as the * contents of the Message's SOAPPart. * <p> * Eventually, genericize this to * return the RootPart instead, which will have some kind of * EnvelopeFactory to enable support for things other than SOAP. * But that all will come later, with lots of additional refactoring. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault. * @param bodyInStream is true if initialContents is an InputStream * containing just the SOAP body (no SOAP-ENV). */ public Message(Object initialContents, boolean bodyInStream) { setup(initialContents, bodyInStream, null, null, null); } /** * Construct a Message, using the provided initialContents as the * contents of the Message's SOAPPart. * <p> * Eventually, genericize this to * return the RootPart instead, which will have some kind of * EnvelopeFactory to enable support for things other than SOAP. * But that all will come later, with lots of additional refactoring. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault. * @param bodyInStream is true if initialContents is an InputStream * containing just the SOAP body (no SOAP-ENV). * @param headers Mime Headers. */ public Message(Object initialContents, boolean bodyInStream, javax.xml.soap.MimeHeaders headers) { setup(initialContents, bodyInStream, null, null, headers); } /** * Construct a Message, using the provided initialContents as the * contents of the Message's SOAPPart. * <p> * Eventually, genericize this to * return the RootPart instead, which will have some kind of * EnvelopeFactory to enable support for things other than SOAP. * But that all will come later, with lots of additional refactoring. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault. * @param headers Mime Headers. */ public Message(Object initialContents, MimeHeaders headers) { setup(initialContents, true, null, null, headers); } /** * Construct a Message, using the provided initialContents as the * contents of the Message's SOAPPart. * <p> * Eventually, genericize this to * return the RootPart instead, which will have some kind of * EnvelopeFactory to enable support for things other than SOAP. * But that all will come later, with lots of additional refactoring. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault * @param bodyInStream is true if initialContents is an InputStream * containing just the SOAP body (no SOAP-ENV) * @param contentType this if the contentType has been already determined * (as in the case of servlets) * @param contentLocation the location of the content */ public Message(Object initialContents, boolean bodyInStream, String contentType, String contentLocation) { setup(initialContents, bodyInStream, contentType, contentLocation, null); } /** * Construct a Message. An overload of Message(Object, boolean), * defaulting bodyInStream to false. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault */ public Message(Object initialContents) { setup(initialContents, false, null, null, null); } private static Class attachImpl = null; //aviod testing and possibly failing everytime. private static boolean checkForAttachmentSupport = true; private static boolean attachmentSupportEnabled = false; private static synchronized boolean isAttachmentSupportEnabled(MessageContext mc) { if (checkForAttachmentSupport) { //aviod testing and possibly failing everytime. checkForAttachmentSupport = false; try { // Get the default setting from AxisProperties String attachImpName = AxisProperties.getProperty(AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION, AxisEngine.DEFAULT_ATTACHMENT_IMPL); // override the default with any changes specified in the engine configuration if (null != mc) { AxisEngine ae = mc.getAxisEngine(); if (null != ae) { attachImpName = (String) ae.getOption( AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION); } } /** * Attempt to resolve class name, verify that these are present... */ ClassUtils.forName("javax.activation.DataHandler"); ClassUtils.forName("javax.mail.internet.MimeMultipart"); attachImpl = ClassUtils.forName(attachImpName); attachmentSupportEnabled = true; } catch (ClassNotFoundException ex) { // no support for it, leave mAttachments null. } catch (java.lang.NoClassDefFoundError ex) { // no support for it, leave mAttachments null. } catch (java.lang.SecurityException ex) { // no support for it, leave mAttachments null. } log.debug(Messages.getMessage("attachEnabled") + " " + attachmentSupportEnabled); } return attachmentSupportEnabled; } /** * Do the work of construction. * * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, * or AxisFault * @param bodyInStream is true if initialContents is an InputStream * containing just the SOAP body (no SOAP-ENV) * @param contentType this if the contentType has been already determined * (as in the case of servlets) * @param contentLocation the location of the content * @param mimeHeaders mime headers for attachments */ private void setup(Object initialContents, boolean bodyInStream, String contentType, String contentLocation, javax.xml.soap.MimeHeaders mimeHeaders) { if(contentType == null && mimeHeaders != null) { String contentTypes[] = mimeHeaders.getHeader("Content-Type"); contentType = (contentTypes != null)? contentTypes[0] : null; } if(contentLocation == null && mimeHeaders != null) { String contentLocations[] = mimeHeaders.getHeader("Content-Location"); contentLocation = (contentLocations != null)? contentLocations[0] : null; } if (contentType != null) { int delimiterIndex = contentType.lastIndexOf("charset"); if (delimiterIndex > 0) { String charsetPart = contentType.substring(delimiterIndex); int delimiterIndex2 = charsetPart.indexOf(';'); if(delimiterIndex2 != -1){ charsetPart = charsetPart.substring(0, delimiterIndex2); } int charsetIndex = charsetPart.indexOf('='); String charset = charsetPart.substring(charsetIndex + 1).trim(); if ((charset.startsWith("\"") || charset.startsWith("\'"))) { charset = charset.substring(1, charset.length()); } if ((charset.endsWith("\"") || charset.endsWith("\'"))) { charset = charset.substring(0, charset.length()-1); } try { setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charset); } catch (SOAPException e) { } } } // Try to construct an AttachmentsImpl object for attachment // functionality. // If there is no org.apache.axis.attachments.AttachmentsImpl class, // it must mean activation.jar is not present and attachments are not // supported. if (isAttachmentSupportEnabled(getMessageContext())) { // Construct one, and cast to Attachments. // There must be exactly one constructor of AttachmentsImpl, which // must take an org.apache.axis.Message! Constructor attachImplConstr = attachImpl.getConstructors()[0]; try { mAttachments = (Attachments) attachImplConstr.newInstance( new Object[] { initialContents, contentType, contentLocation}); //If it can't support it, it wont have a root part. mSOAPPart = (SOAPPart) mAttachments.getRootPart(); } catch (InvocationTargetException ex) { log.fatal(Messages.getMessage("invocationTargetException00"), ex); throw new RuntimeException(ex.getMessage()); } catch (InstantiationException ex) { log.fatal(Messages.getMessage("instantiationException00"), ex); throw new RuntimeException(ex.getMessage()); } catch (IllegalAccessException ex) { log.fatal(Messages.getMessage("illegalAccessException00"), ex); throw new RuntimeException(ex.getMessage()); } } else if (contentType != null && contentType.startsWith("multipart")){ throw new RuntimeException(Messages.getMessage("noAttachments")); } // text/xml if (null == mSOAPPart) { mSOAPPart = new SOAPPart(this, initialContents, bodyInStream); } else mSOAPPart.setMessage(this); // The stream was not determined by a more complex type so default to if(mAttachments!=null) mAttachments.setRootPart(mSOAPPart); headers = (mimeHeaders == null) ? new MimeHeaders() : new MimeHeaders(mimeHeaders); } /** * Get this message's SOAPPart. * <p> * Eventually, this should be generalized beyond just SOAP, * but it's hard to know how to do that without necessitating * a lot of casts in client code. Refactoring keeps getting * easier anyhow. * * @return the soap part of this message */ public javax.xml.soap.SOAPPart getSOAPPart() { return mSOAPPart; } // fixme: do we realy need this? Can client code not just call // getSOAPPart().getAsString() or is there some future optimization that // could be hooked in here? /** * Get a string representation of this message's SOAPPart. * * @return the soap part of this message as a <code>String</code> * @throws org.apache.axis.AxisFault if the stringification failed */ public String getSOAPPartAsString() throws org.apache.axis.AxisFault { return mSOAPPart.getAsString(); } // fixme: do we realy need this? Can client code not just call // getSOAPPart().getAsBytes() or is there some future optimization that // could be hooked in here? /** * Get a byte array representation of this message's SOAPPart. * * @return the soap part of this message as a <code>byte[]</code> * @throws org.apache.axis.AxisFault if creating the byte[] failed */ public byte[] getSOAPPartAsBytes() throws org.apache.axis.AxisFault { return mSOAPPart.getAsBytes(); } /** * Get this message's SOAPPart as a SOAPEnvelope. * * @return a SOAPEnvelope containing this message's SOAPPart * @throws AxisFault if this failed */ public SOAPEnvelope getSOAPEnvelope() throws AxisFault { return mSOAPPart.getAsSOAPEnvelope(); } /** * Get the Attachments of this Message. * <p> * If this returns null, then NO ATTACHMENT SUPPORT EXISTS in this * configuration of Axis, and no attachment operations may be * performed. * * @return the <code>Attachments</code> if attachments are supported, null * otherwise */ public Attachments getAttachmentsImpl() { return mAttachments; } /** * Get the content type of the attachments. * * @param sc provides the default content type * @return a <code>String</code> giving the content type of the * attachment * @throws AxisFault if there was an error deducing the content type from * this message */ public String getContentType(SOAPConstants sc) throws AxisFault { boolean soap12 = false; if(sc != null) { if(sc == SOAPConstants.SOAP12_CONSTANTS) { soap12 = true; } } else { // Support of SOAP 1.2 HTTP binding SOAPEnvelope envelope = getSOAPEnvelope(); if (envelope != null) { if (envelope.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { soap12 = true; } } } String encoding = XMLUtils.getEncoding(this, msgContext);; String ret = sc.getContentType() + "; charset=" + encoding.toLowerCase(); // Support of SOAP 1.2 HTTP binding if (soap12) { ret = HTTPConstants.HEADER_ACCEPT_APPL_SOAP +"; charset=" + encoding; } if (getSendType() != Attachments.SEND_TYPE_NONE && mAttachments != null && 0 != mAttachments.getAttachmentCount()) { ret = mAttachments.getContentType(); } return ret; } private int getSendType() { int sendType = Attachments.SEND_TYPE_NOTSET; if ((msgContext != null) && (msgContext.getService() != null)) { sendType = msgContext.getService().getSendType(); } return sendType; } //This will have to give way someday to HTTP Chunking but for now kludge. /** * Get the content length, including both soap and any attachments. * * @return the total length of this message in bytes * @throws org.apache.axis.AxisFault if there was a problem that prevented * the length being calculated */ public long getContentLength() throws org.apache.axis.AxisFault { long ret = mSOAPPart.getContentLength(); if (mAttachments != null && 0 < mAttachments.getAttachmentCount()) { ret = mAttachments.getContentLength(); } return ret; } /** * Writes this <CODE>SOAPMessage</CODE> object to the given * output stream. The externalization format is as defined by * the SOAP 1.1 with Attachments specification. * * <P>If there are no attachments, just an XML stream is * written out. For those messages that have attachments, * <CODE>writeTo</CODE> writes a MIME-encoded byte stream.</P> * @param os the <CODE>OutputStream</CODE> * object to which this <CODE>SOAPMessage</CODE> object will * be written * @throws SOAPException if there was a problem in * externalizing this SOAP message * @throws IOException if an I/O error * occurs */ public void writeTo(java.io.OutputStream os) throws SOAPException, IOException { //Do it the old fashion way. if (getSendType() == Attachments.SEND_TYPE_NONE || mAttachments == null || 0 == mAttachments.getAttachmentCount()) { try { String charEncoding = XMLUtils.getEncoding(this, msgContext);; mSOAPPart.setEncoding(charEncoding); mSOAPPart.writeTo(os); } catch (java.io.IOException e) { log.error(Messages.getMessage("javaIOException00"), e); } } else { try { mAttachments.writeContentToStream(os); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } } } private java.util.Hashtable mProps = new java.util.Hashtable(); public SOAPBody getSOAPBody() throws SOAPException { return mSOAPPart.getEnvelope().getBody(); } public SOAPHeader getSOAPHeader() throws SOAPException { return mSOAPPart.getEnvelope().getHeader(); } public void setProperty(String property, Object value) throws SOAPException { mProps.put(property, value); } public Object getProperty(String property) throws SOAPException { return mProps.get(property); } /** * Retrieves a description of this <CODE>SOAPMessage</CODE> * object's content. * @return a <CODE>String</CODE> describing the content of this * message or <CODE>null</CODE> if no description has been * set * @see #setContentDescription(java.lang.String) setContentDescription(java.lang.String) */ public String getContentDescription() { String values[] = headers.getHeader(HTTPConstants.HEADER_CONTENT_DESCRIPTION); if(values != null && values.length > 0) return values[0]; return null; } /** * Sets the description of this <CODE>SOAPMessage</CODE> * object's content with the given description. * @param description a <CODE>String</CODE> * describing the content of this message * @see #getContentDescription() getContentDescription() */ public void setContentDescription(String description) { headers.setHeader(HTTPConstants.HEADER_CONTENT_DESCRIPTION, description); } /** * Updates this <CODE>SOAPMessage</CODE> object with all the * changes that have been made to it. This method is called * automatically when a message is sent or written to by the * methods <CODE>ProviderConnection.send</CODE>, <CODE> * SOAPConnection.call</CODE>, or <CODE> * SOAPMessage.writeTo</CODE>. However, if changes are made to * a message that was received or to one that has already been * sent, the method <CODE>saveChanges</CODE> needs to be * called explicitly in order to save the changes. The method * <CODE>saveChanges</CODE> also generates any changes that * can be read back (for example, a MessageId in profiles that * support a message id). All MIME headers in a message that * is created for sending purposes are guaranteed to have * valid values only after <CODE>saveChanges</CODE> has been * called. * * <P>In addition, this method marks the point at which the * data from all constituent <CODE>AttachmentPart</CODE> * objects are pulled into the message.</P> * @throws SOAPException if there * was a problem saving changes to this message. */ public void saveChanges() throws SOAPException { headers.removeHeader("Content-Length"); if (mAttachments != null && 0 < mAttachments.getAttachmentCount()) { try { headers.setHeader("Content-Type",mAttachments.getContentType()); } catch (AxisFault af){ log.error(Messages.getMessage("exception00"), af); } } saveRequired = false; try { /* Fix for Bug 16418 - Start from scratch */ mSOAPPart.saveChanges(); } catch (AxisFault axisFault) { log.error(Messages.getMessage("exception00"), axisFault); } } /** * Indicates whether this <CODE>SOAPMessage</CODE> object * has had the method <CODE>saveChanges</CODE> called on * it. * @return <CODE>true</CODE> if <CODE>saveChanges</CODE> has * been called on this message at least once; <CODE> * false</CODE> otherwise. */ public boolean saveRequired() { return saveRequired; } /** * Returns all the transport-specific MIME headers for this * <CODE>SOAPMessage</CODE> object in a transport-independent * fashion. * @return a <CODE>MimeHeaders</CODE> object containing the * <CODE>MimeHeader</CODE> objects */ public javax.xml.soap.MimeHeaders getMimeHeaders() { return headers; } /** * Removes all <CODE>AttachmentPart</CODE> objects that have * been added to this <CODE>SOAPMessage</CODE> object. * * <P>This method does not touch the SOAP part.</P> */ public void removeAllAttachments(){ mAttachments.removeAllAttachments(); } /** * Gets a count of the number of attachments in this * message. This count does not include the SOAP part. * @return the number of <CODE>AttachmentPart</CODE> objects * that are part of this <CODE>SOAPMessage</CODE> * object */ public int countAttachments(){ return mAttachments == null ? 0 : mAttachments.getAttachmentCount(); } /** * Retrieves all the <CODE>AttachmentPart</CODE> objects * that are part of this <CODE>SOAPMessage</CODE> object. * @return an iterator over all the attachments in this * message */ public Iterator getAttachments(){ try { if (mAttachments != null && 0 != mAttachments.getAttachmentCount()) { return mAttachments.getAttachments().iterator(); } } catch (AxisFault af){ log.error(Messages.getMessage("exception00"), af); } return Collections.EMPTY_LIST.iterator(); } /** * Retrieves all the <CODE>AttachmentPart</CODE> objects * that have header entries that match the specified headers. * Note that a returned attachment could have headers in * addition to those specified. * @param headers a <CODE>MimeHeaders</CODE> * object containing the MIME headers for which to * search * @return an iterator over all attachments that have a header * that matches one of the given headers */ public Iterator getAttachments(javax.xml.soap.MimeHeaders headers){ return mAttachments.getAttachments(headers); } /** * Adds the given <CODE>AttachmentPart</CODE> object to this * <CODE>SOAPMessage</CODE> object. An <CODE> * AttachmentPart</CODE> object must be created before it can be * added to a message. * @param attachmentpart an <CODE> * AttachmentPart</CODE> object that is to become part of * this <CODE>SOAPMessage</CODE> object * @throws java.lang.IllegalArgumentException */ public void addAttachmentPart(AttachmentPart attachmentpart){ try { mAttachments.addAttachmentPart((org.apache.axis.Part)attachmentpart); } catch (AxisFault af){ log.error(Messages.getMessage("exception00"), af); } } /** * Creates a new empty <CODE>AttachmentPart</CODE> object. * Note that the method <CODE>addAttachmentPart</CODE> must be * called with this new <CODE>AttachmentPart</CODE> object as * the parameter in order for it to become an attachment to this * <CODE>SOAPMessage</CODE> object. * @return a new <CODE>AttachmentPart</CODE> object that can be * populated and added to this <CODE>SOAPMessage</CODE> * object */ public AttachmentPart createAttachmentPart() { if (!isAttachmentSupportEnabled(getMessageContext())) { throw new RuntimeException(Messages.getMessage("noAttachments")); } try { return (AttachmentPart) mAttachments.createAttachmentPart(); } catch (AxisFault af){ log.error(Messages.getMessage("exception00"), af); } return null; } /** * Dispose of attachments. */ public void dispose() { if(mAttachments!=null) { mAttachments.dispose(); } } }
7,310
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/AxisFault.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 ; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.Vector; import java.io.PrintWriter; import java.io.StringWriter; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; import javax.xml.rpc.soap.SOAPFaultException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPFault; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.XMLUtils; import org.apache.axis.utils.NetworkUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * An exception which maps cleanly to a SOAP fault. * This is a base class for exceptions which are mapped to faults. * SOAP faults contain * <ol> * <li>A fault string * <li>A fault code * <li>A fault actor * <li>Fault details; an xml tree of fault specific stuff * </ol> * @author Doug Davis (dug@us.ibm.com) * @author James Snell (jasnell@us.ibm.com) * @author Steve Loughran */ public class AxisFault extends java.rmi.RemoteException { /** * The <code>Log</code> used by this class for all logging. */ protected static Log log = LogFactory.getLog(AxisFault.class.getName()); protected QName faultCode ; /** SOAP1.2 addition: subcodes of faults; a Vector of QNames */ protected Vector faultSubCode ; protected String faultString = ""; protected String faultActor ; protected Vector faultDetails ; // vector of Element's protected String faultNode ; /** SOAP headers which should be serialized with the Fault. */ protected ArrayList faultHeaders = null; /** * Make an AxisFault based on a passed Exception. If the Exception is * already an AxisFault, simply use that. Otherwise, wrap it in an * AxisFault. If the Exception is an InvocationTargetException (which * already wraps another Exception), get the wrapped Exception out from * there and use that instead of the passed one. * * @param e the <code>Exception</code> to build a fault for * @return an <code>AxisFault</code> representing <code>e</code> */ public static AxisFault makeFault(Exception e) { if (e instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException)e).getTargetException(); if (t instanceof Exception) { e = (Exception)t; } } if (e instanceof AxisFault) { return (AxisFault)e; } return new AxisFault(e); } /** * Make a fault in the <code>Constants.NS_URI_AXIS</code> namespace. * * @param code fault code which will be passed into the Axis namespace * @param faultString fault string * @param actor fault actor * @param details details; if null the current stack trace and classname is * inserted into the details. */ public AxisFault(String code, String faultString, String actor, Element[] details) { this(new QName(Constants.NS_URI_AXIS, code), faultString, actor, details); } /** * Make a fault in any namespace. * * @param code fault code which will be passed into the Axis namespace * @param faultString fault string * @param actor fault actor * @param details details; if null the current stack trace and classname is * inserted into the details. */ public AxisFault(QName code, String faultString, String actor, Element[] details) { super (faultString); setFaultCode( code ); setFaultString( faultString ); setFaultActor( actor ); setFaultDetail( details ); if (details == null) { initFromException(this); } } /** * Make a fault in any namespace. * * @param code fault code which will be passed into the Axis namespace * @param subcodes fault subcodes which will be pased into the Axis namespace * @param faultString fault string * @param actor fault actor, same as fault role in SOAP 1.2 * @param node which node caused the fault on the SOAP path * @param details details; if null the current stack trace and classname is * inserted into the details. * @since axis1.1 */ public AxisFault(QName code, QName[] subcodes, String faultString, String actor, String node, Element[] details) { super (faultString); setFaultCode( code ); if (subcodes != null) { for (int i = 0; i < subcodes.length; i++) { addFaultSubCode( subcodes[i] ); } } setFaultString( faultString ); setFaultActor( actor ); setFaultNode( node ); setFaultDetail( details ); if (details == null) { initFromException(this); } } // fixme: docs says private, access says protected /** * Wrap an AxisFault around an existing Exception. This is private * to force everyone to use makeFault() above, which sanity-checks us. * * @param target the target <code>Exception</code> */ protected AxisFault(Exception target) { super ("", target); // ? SOAP 1.2 or 1.1 ? setFaultCodeAsString( Constants.FAULT_SERVER_USER ); initFromException(target); // if the target is a JAX-RPC SOAPFaultException init // AxisFault with the values from the SOAPFaultException if ( target instanceof SOAPFaultException ) { //strip out the hostname as we want any new one removeHostname(); initFromSOAPFaultException((SOAPFaultException) target); //but if they left it out, add it addHostnameIfNeeded(); } } /** * create a simple axis fault from the message. Classname and stack trace * go into the fault details. * @param message */ public AxisFault(String message) { super (message); setFaultCodeAsString(Constants.FAULT_SERVER_GENERAL); setFaultString(message); initFromException(this); } /** * No-arg constructor for building one from an XML stream. */ public AxisFault() { super(); setFaultCodeAsString(Constants.FAULT_SERVER_GENERAL); initFromException(this); } /** * create a fault from any throwable; * When faulting a throwable (as opposed to an exception), * stack trace information does not go into the fault. * @param message any extra text to with the fault * @param t whatever is to be turned into a fault */ public AxisFault (String message, Throwable t) { super (message, t); setFaultCodeAsString(Constants.FAULT_SERVER_GENERAL); setFaultString(getMessage()); addHostnameIfNeeded(); } /** * fill in soap fault details from the exception, unless * this object already has a stack trace in its details. Which, given * the way this private method is invoked, is a pretty hard situation to ever achieve. * This method adds classname of the exception and the stack trace. * @param target what went wrong */ private void initFromException(Exception target) { //look for old stack trace Element oldStackTrace = lookupFaultDetail(Constants.QNAME_FAULTDETAIL_STACKTRACE); if (oldStackTrace != null) { // todo: Should we replace it or just let it be? return; } // Set the exception message (if any) as the fault string setFaultString( target.toString() ); // Put the exception class into the AXIS SPECIFIC HACK // "exceptionName" element in the details. This allows // us to get back a correct Java Exception class on the other side // (assuming they have it available). // NOTE: This hack is obsolete! We now serialize exception data // and the other side uses *that* QName to figure out what exception // to use, because the class name may be completly different on the // client. if ((target instanceof AxisFault) && (target.getClass() != AxisFault.class)) { addFaultDetail(Constants.QNAME_FAULTDETAIL_EXCEPTIONNAME, target.getClass().getName()); } //add stack trace if (target == this) { // only add stack trace. JavaUtils.stackToString() call would // include dumpToString() info which is already sent as different // elements of this fault. addFaultDetail(Constants.QNAME_FAULTDETAIL_STACKTRACE, getPlainStackTrace()); } else { addFaultDetail(Constants.QNAME_FAULTDETAIL_STACKTRACE, JavaUtils.stackToString(target)); } //add the hostname addHostnameIfNeeded(); } /** * Initiates the AxisFault with the values from a SOAPFaultException * @param fault SOAPFaultException */ private void initFromSOAPFaultException(SOAPFaultException fault) { // faultcode if ( fault.getFaultCode() != null ) { setFaultCode(fault.getFaultCode()); } // faultstring if ( fault.getFaultString() != null ) { setFaultString(fault.getFaultString()); } // actor if ( fault.getFaultActor() != null ) { setFaultActor(fault.getFaultActor()); } if ( null == fault.getDetail() ) { return; } // We get an Iterator but we need a List Vector details = new Vector(); Iterator detailIter = fault.getDetail().getChildElements(); while (detailIter.hasNext()) { details.add( detailIter.next()); } // Convert the List in an Array an return the array setFaultDetail( XMLUtils.asElementArray(details)); } /** * Init the fault details data structure; does nothing * if this exists already. */ private void initFaultDetails() { if (faultDetails == null) { faultDetails = new Vector(); } } /** * Clear the fault details list. */ public void clearFaultDetails() { faultDetails=null; } /** * Dump the fault info to the log at debug level. */ public void dump() { log.debug(dumpToString()); } /** * turn the fault and details into a string, with XML escaping. * subclassers: for security (cross-site-scripting) reasons, * escape everything that could contain caller-supplied data. * @return stringified fault details */ public String dumpToString() { StringBuffer buf = new StringBuffer("AxisFault"); buf.append(JavaUtils.LS); buf.append(" faultCode: "); buf.append(XMLUtils.xmlEncodeString(faultCode.toString())); buf.append(JavaUtils.LS); buf.append(" faultSubcode: "); if (faultSubCode != null) { for (int i = 0; i < faultSubCode.size(); i++) { buf.append(JavaUtils.LS); buf.append(faultSubCode.elementAt(i).toString()); } } buf.append(JavaUtils.LS); buf.append(" faultString: "); try { buf.append(XMLUtils.xmlEncodeString(faultString)); } catch (RuntimeException re) { buf.append(re.getMessage()); } buf.append(JavaUtils.LS); buf.append(" faultActor: "); buf.append(XMLUtils.xmlEncodeString(faultActor)); buf.append(JavaUtils.LS); buf.append(" faultNode: "); buf.append(XMLUtils.xmlEncodeString(faultNode)); buf.append(JavaUtils.LS); buf.append(" faultDetail: "); if (faultDetails != null) { for (int i=0; i < faultDetails.size(); i++) { Element e = (Element) faultDetails.get(i); buf.append(JavaUtils.LS); buf.append("\t{"); buf.append(null == e.getNamespaceURI() ? "" : e.getNamespaceURI()); buf.append("}"); buf.append(null == e.getLocalName() ? "" : e.getLocalName()); buf.append(":"); buf.append(XMLUtils.getInnerXMLString(e)); } } buf.append(JavaUtils.LS); return buf.toString(); } /** * Set the fault code. * * @param code a new fault code */ public void setFaultCode(QName code) { faultCode = code ; } /** * Set the fault code (as a String). * * @param code a new fault code * @deprecated expect to see this go away after 1.1, use * setFaultCodeAsString instead! */ public void setFaultCode(String code) { setFaultCodeAsString(code); } /** * set a fault code string that is turned into a qname * in the SOAP 1.1 or 1.2 namespace, depending on the current context * @param code fault code */ public void setFaultCodeAsString(String code) { SOAPConstants soapConstants = MessageContext.getCurrentContext() == null ? SOAPConstants.SOAP11_CONSTANTS : MessageContext.getCurrentContext().getSOAPConstants(); faultCode = new QName(soapConstants.getEnvelopeURI(), code); } /** * Get the fault code <code>QName</code>. * * @return fault code QName or null if there is none yet. */ public QName getFaultCode() { return( faultCode ); } /** * Add a fault sub-code with the local name <code>code</code> and namespace * <code>Constants.NS_URI_AXIS</code>. * This is new in SOAP 1.2, ignored in SOAP 1.1 * * @param code the local name of the code to add * @since axis1.1 */ public void addFaultSubCodeAsString(String code) { initFaultSubCodes(); faultSubCode.add(new QName(Constants.NS_URI_AXIS, code)); } /** * Do whatever is needed to create the fault subcodes * data structure, if it is needed. */ protected void initFaultSubCodes() { if (faultSubCode == null) { faultSubCode = new Vector(); } } /** * Add a fault sub-code. * This is new in SOAP 1.2, ignored in SOAP 1.1. * * @param code the <code>QName</code> of the fault sub-code to add * @since axis1.1 */ public void addFaultSubCode(QName code) { initFaultSubCodes(); faultSubCode.add(code); } /** * Clear all fault sub-codes. * This is new in SOAP 1.2, ignored in SOAP 1.1. * * @since axis1.1 */ public void clearFaultSubCodes() { faultSubCode = null; } /** * get the fault subcode list; only used in SOAP 1.2 * @since axis1.1 * @return null for no subcodes, or a QName array */ public QName[] getFaultSubCodes() { if (faultSubCode == null) { return null; } QName[] q = new QName[faultSubCode.size()]; return (QName[])faultSubCode.toArray(q); } /** * Set a fault string. * @param str new fault string; null is turned into "" */ public void setFaultString(String str) { if (str != null) { faultString = str ; } else { faultString = ""; } } /** * Get the fault string; this will never be null but may be the * empty string. * * @return a fault string */ public String getFaultString() { return( faultString ); } /** * This is SOAP 1.2 equivalent of {@link #setFaultString(java.lang.String)}. * * @param str the fault reason as a <code>String</code> * @since axis1.1 */ public void setFaultReason(String str) { setFaultString(str); } /** * This is SOAP 1.2 equivalent of {@link #getFaultString()}. * @since axis1.1 * @return the fault <code>String</code> */ public String getFaultReason() { return getFaultString(); } /** * Set the fault actor. * * @param actor fault actor */ public void setFaultActor(String actor) { faultActor = actor ; } /** * get the fault actor * @return actor or null */ public String getFaultActor() { return( faultActor ); } /** * This is SOAP 1.2 equivalent of {@link #getFaultActor()}. * @since axis1.1 * @return the name of the fault actor */ public String getFaultRole() { return getFaultActor(); } // fixme: both faultRole and faultActor refer to the other one - can we // break the circularity here? /** * This is SOAP 1.2 equivalent of {@link #setFaultActor(java.lang.String)}. * @since axis1.1 */ public void setFaultRole(String role) { setFaultActor(role); } /** * Get the fault node. * * This is new in SOAP 1.2 * @since axis1.1 * @return */ public String getFaultNode() { return( faultNode ); } /** * Set the fault node. * * This is new in SOAP 1.2. * * @param node a <code>String</code> representing the fault node * @since axis1.1 */ public void setFaultNode(String node) { faultNode = node; } /** * Set the fault detail element to the arrary of details. * * @param details list of detail elements, can be null */ public void setFaultDetail(Element[] details) { if ( details == null ) { faultDetails=null; return ; } faultDetails = new Vector( details.length ); for ( int loop = 0 ; loop < details.length ; loop++ ) { faultDetails.add( details[loop] ); } } /** * set the fault details to a string element. * @param details XML fragment */ public void setFaultDetailString(String details) { clearFaultDetails(); addFaultDetailString(details); } /** * add a string tag to the fault details. * @param detail XML fragment */ public void addFaultDetailString(String detail) { initFaultDetails(); try { Document doc = XMLUtils.newDocument(); Element element = doc.createElement("string"); Text text = doc.createTextNode(detail); element.appendChild(text); faultDetails.add(element); } catch (ParserConfigurationException e) { // This should not occur throw new InternalException(e); } } /** * Append an element to the fault detail list. * * @param detail the new element to add * @since Axis1.1 */ public void addFaultDetail(Element detail) { initFaultDetails(); faultDetails.add(detail); } /** * Create an element of the given qname and add it to the details. * * @param qname qname of the element * @param body string to use as body */ public void addFaultDetail(QName qname,String body) { Element detail = XMLUtils.StringToElement(qname.getNamespaceURI(), qname.getLocalPart(), body); addFaultDetail(detail); } // fixme: should we be returning null for none or a zero length array? /** * Get all the fault details. * * @return an array of fault details, or null for none */ public Element[] getFaultDetails() { if (faultDetails == null) { return null; } Element result[] = new Element[faultDetails.size()]; for (int i=0; i<result.length; i++) { result[i] = (Element) faultDetails.elementAt(i); } return result; } /** * Find a fault detail element by its qname. * @param qname name of the node to look for * @return the matching element or null * @since axis1.1 */ public Element lookupFaultDetail(QName qname) { if (faultDetails != null) { //extract details from the qname. the empty namespace is represented //by the empty string String searchNamespace = qname.getNamespaceURI(); String searchLocalpart = qname.getLocalPart(); //now spin through the elements, seeking a match Iterator it=faultDetails.iterator(); while (it.hasNext()) { Element e = (Element) it.next(); String localpart= e.getLocalName(); if(localpart==null) { localpart=e.getNodeName(); } String namespace= e.getNamespaceURI(); if(namespace==null) { namespace=""; } //we match on matching namespace and local part; empty namespace //in an element may be null, which matches QName's "" if(searchNamespace.equals(namespace) && searchLocalpart.equals(localpart)) { return e; } } } return null; } /** * Find and remove a specified fault detail element. * * @param qname qualified name of detail * @return true if it was found and removed, false otherwise * @since axis1.1 */ public boolean removeFaultDetail(QName qname) { Element elt=lookupFaultDetail(qname); if(elt==null) { return false; } else { return faultDetails.remove(elt); } } /** * Add this fault and any needed headers to the output context. * * @param context * @throws Exception */ public void output(SerializationContext context) throws Exception { SOAPConstants soapConstants = Constants.DEFAULT_SOAP_VERSION; if (context.getMessageContext() != null) { soapConstants = context.getMessageContext().getSOAPConstants(); } SOAPEnvelope envelope = new SOAPEnvelope(soapConstants); SOAPFault fault = new SOAPFault(this); envelope.addBodyElement(fault); // add any headers we need if (faultHeaders != null) { for (Iterator i = faultHeaders.iterator(); i.hasNext();) { SOAPHeaderElement header = (SOAPHeaderElement) i.next(); envelope.addHeader(header); } } envelope.output(context); } /** * Stringify this fault as the current fault string. * * @return the fault string, possibly the empty string, but never null */ public String toString() { return faultString; } /** * Gets the stack trace as a string. */ private String getPlainStackTrace() { StringWriter sw = new StringWriter(512); PrintWriter pw = new PrintWriter(sw); super.printStackTrace(pw); pw.close(); return sw.toString(); } /** * The override of the base class method prints out the * fault info before the stack trace. * * @param ps where to print */ public void printStackTrace(PrintStream ps) { ps.println(dumpToString()); super.printStackTrace(ps); } /** * The override of the base class method prints out the * fault info before the stack trace. * * @param pw where to print */ public void printStackTrace(java.io.PrintWriter pw) { pw.println(dumpToString()); super.printStackTrace(pw); } /** * Add a SOAP header which should be serialized along with the * fault. * * @param header a SOAPHeaderElement containing some fault-relevant stuff */ public void addHeader(SOAPHeaderElement header) { if (faultHeaders == null) { faultHeaders = new ArrayList(); } faultHeaders.add(header); } /** * Get the SOAP headers associated with this fault. * * @return an ArrayList containing any headers associated with this fault */ public ArrayList getHeaders() { return faultHeaders; } /** * Clear all fault headers. */ public void clearHeaders() { faultHeaders = null; } /** * Writes any exception data to the faultDetails. * * This can be overridden (and is) by emitted exception clases. * The base implementation will attempt to serialize exception data the * fault was created from an Exception and a type mapping is found for it. * * @param qname the <code>QName</code> to write this under * @param context the <code>SerializationContext</code> to write this fault * to * @throws java.io.IOException if we can't write ourselves for any reason */ public void writeDetails(QName qname, SerializationContext context) throws java.io.IOException { Object detailObject = this.detail; if (detailObject == null) { return; } boolean haveSerializer = false; try { if (context.getTypeMapping().getSerializer(detailObject.getClass()) != null) { haveSerializer = true; } } catch (Exception e) { // swallow this exception, it means that we don't know how to serialize // the details. } if (haveSerializer) { boolean oldMR = context.getDoMultiRefs(); context.setDoMultiRefs(false); context.serialize(qname, null, detailObject); context.setDoMultiRefs(oldMR); } } /** * add the hostname of the current system. This is very useful for * locating faults on a cluster. * @since Axis1.2 */ public void addHostnameIfNeeded() { //look for an existing declaration if(lookupFaultDetail(Constants.QNAME_FAULTDETAIL_HOSTNAME)!=null) { //and do nothing if it exists return; } addHostname(NetworkUtils.getLocalHostname()); } /** * add the hostname string. If one already exists, remove it. * @param hostname string name of a host * @since Axis1.2 */ public void addHostname(String hostname) { //add the hostname removeHostname(); addFaultDetail(Constants.QNAME_FAULTDETAIL_HOSTNAME, hostname); } /** * strip out the hostname on a message. This * is useful for security reasons. */ public void removeHostname() { removeFaultDetail(Constants.QNAME_FAULTDETAIL_HOSTNAME); } }
7,311
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/ConfigurationException.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; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.JavaUtils; import org.apache.commons.logging.Log; import java.io.IOException; /** * ConfigurationException is thrown when an error occurs trying to * use an EngineConfiguration. * * @author Glyn Normington (glyn@apache.org) */ public class ConfigurationException extends IOException { /** * The contained exception if present. */ private Exception containedException=null; private String stackTrace=""; /** * Flag wether to copy the orginal exception by default. */ protected static boolean copyStackByDefault= true; /** * The <code>Log</code> used by this class for logging all messages. */ protected static Log log = LogFactory.getLog(ConfigurationException.class.getName()); /** * Construct a ConfigurationException from a String. The string is wrapped * in an exception, enabling a stack traceback to be obtained. * @param message String form of the error */ public ConfigurationException(String message) { super(message); if(copyStackByDefault) { stackTrace= JavaUtils.stackToString(this); } logException( this); } /** * Construct a ConfigurationException from an Exception. * @param exception original exception which was unexpected */ public ConfigurationException(Exception exception) { this(exception,copyStackByDefault); } /** * Stringify, including stack trace. * * @return a <code>String</code> view of this object */ public String toString() { String stack; if(stackTrace.length()== 0) { stack = ""; } else { stack="\n"+stackTrace; } return super.toString()+stack; } /** * Construct a ConfigurationException from an Exception. * @param exception original exception which was unexpected * @param copyStack set to true to copy the orginal exception's stack */ public ConfigurationException(Exception exception, final boolean copyStack) { super(exception.toString() + (copyStack ? "\n" + JavaUtils.stackToString(exception) : "" )); containedException = exception; if(copyStack) { stackTrace = JavaUtils.stackToString(this); } // Log the exception the first time it appears. if (!(exception instanceof ConfigurationException)) { logException(exception); } } /** * single point for logging exceptions. * @param exception */ private void logException(Exception exception) { log.debug("Exception: ", exception); } /** * Get any contained exception. * * @return base exception or null * @since axis1.1 */ public Exception getContainedException() { return containedException; } }
7,312
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/SimpleChain.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 ; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.strategies.InvocationStrategy; import org.apache.axis.strategies.WSDLGenStrategy; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.Enumeration; import java.util.Vector; /** * A Simple Chain is a 'composite' Handler in that it aggregates a collection * of Handlers and also acts as a Handler which delegates its operations to * the collection. * <p> * A Simple Chain initially has no Handlers. Handlers may be added until the * chain is invoke()d after which Handlers may not be added (and any attempt * to do so will throw an exception). * * @author Doug Davis (dug@us.ibm.com) * @author Glyn Normington (norm@uk.ibm.com) */ public class SimpleChain extends BasicHandler implements Chain { private static Log log = LogFactory.getLog(SimpleChain.class.getName()); protected Vector handlers = new Vector(); protected boolean invoked = false; private String CAUGHTFAULT_PROPERTY = "org.apache.axis.SimpleChain.caughtFaultInResponse"; public void init() { for ( int i = 0 ; i < handlers.size() ; i++ ) ((Handler) handlers.elementAt( i )).init(); } public void cleanup() { for ( int i = 0 ; i < handlers.size() ; i++ ) ((Handler) handlers.elementAt( i )).cleanup(); } private static final HandlerIterationStrategy iVisitor = new InvocationStrategy(); private static final HandlerIterationStrategy wsdlVisitor = new WSDLGenStrategy(); /** * Iterate over the chain invoking each handler. If there's a fault * then call 'onFault' for each completed handler in reverse order, then * rethrow the exception. * * @throws AxisFault if there was a fault with any of the handlers */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SimpleChain::invoke"); } invoked = true; doVisiting(msgContext, iVisitor); if (log.isDebugEnabled()) { log.debug("Exit: SimpleChain::invoke"); } } /** * Iterate over the chain letting each handler have a crack at * contributing to a WSDL description. * * @param msgContext the <code>MessageContext</code> to write the WSDL * out to * @throws AxisFault if there was a problem writing the WSDL */ public void generateWSDL(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SimpleChain::generateWSDL"); } invoked = true; doVisiting(msgContext, wsdlVisitor); if (log.isDebugEnabled()) { log.debug("Exit: SimpleChain::generateWSDL"); } } private void doVisiting(MessageContext msgContext, HandlerIterationStrategy visitor) throws AxisFault { int i = 0 ; try { Enumeration enumeration = handlers.elements(); while (enumeration.hasMoreElements()) { Handler h = (Handler)enumeration.nextElement(); visitor.visit(h, msgContext); i++; } } catch( AxisFault f ) { // Something went wrong. If we haven't already put this fault // into the MessageContext's response message, do so and make sure // we only do it once. This allows onFault() methods to safely // set headers and such in the response message without them // getting stomped. if (!msgContext.isPropertyTrue(CAUGHTFAULT_PROPERTY)) { // Attach the fault to the response message; enabling access to the // fault details while inside the handler onFault methods. Message respMsg = new Message(f); msgContext.setResponseMessage(respMsg); msgContext.setProperty(CAUGHTFAULT_PROPERTY, Boolean.TRUE); } while( --i >= 0 ) ((Handler) handlers.elementAt( i )).onFault( msgContext ); throw f; } } /** * Notify the handlers in this chain because some handler * later on has faulted - in reverse order. If any handlers * have been added since we visited the chain, they will get * notified too! * * @param msgContext the context to process */ public void onFault(MessageContext msgContext) { if (log.isDebugEnabled()) { log.debug("Enter: SimpleChain::onFault"); } for ( int i = handlers.size()-1 ; i >= 0 ; i-- ) ((Handler) handlers.elementAt( i )).onFault( msgContext ); if (log.isDebugEnabled()) { log.debug("Exit: SimpleChain::onFault"); } } public boolean canHandleBlock(QName qname) { for ( int i = 0 ; i < handlers.size() ; i++ ) if ( ((Handler) handlers.elementAt( i )).canHandleBlock(qname) ) return( true ); return( false ); } public void addHandler(Handler handler) { if (handler == null) throw new InternalException( Messages.getMessage("nullHandler00", "SimpleChain::addHandler")); if (invoked) throw new InternalException( Messages.getMessage("addAfterInvoke00", "SimpleChain::addHandler")); handlers.add( handler ); } public boolean contains(Handler handler) { return( handlers.contains( handler )); } public Handler[] getHandlers() { if (handlers.size() == 0) return null; Handler [] ret = new Handler[handlers.size()]; return( (Handler[]) handlers.toArray(ret) ); } public Element getDeploymentData(Document doc) { if (log.isDebugEnabled()) { log.debug( Messages.getMessage("enter00", "SimpleChain::getDeploymentData") ); } Element root = doc.createElementNS("", "chain" ); StringBuffer str = new StringBuffer(); int i = 0; while (i < handlers.size()) { if ( i != 0 ) str.append(","); Handler h = (Handler) handlers.elementAt(i); str.append( h.getName() ); i++; } if (i > 0) { root.setAttribute( "flow", str.toString() ); } if ( options != null ) { Enumeration e = options.keys(); while ( e.hasMoreElements() ) { String k = (String) e.nextElement(); Object v = options.get(k); Element e1 = doc.createElementNS("", "option"); e1.setAttribute( "name", k ); e1.setAttribute( "value", v.toString() ); root.appendChild( e1 ); } } if (log.isDebugEnabled()) { log.debug("Exit: SimpleChain::getDeploymentData"); } return( root ); } }
7,313
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/SimpleTargetedChain.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 ; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.commons.logging.Log; /** * A SimpleTargetedChain has a request handler, a pivot handler, and a response * handler (any of which may themselves be chains). * * @author Doug Davis (dug@us.ibm.com) * @author Glyn Normington (norm@uk.ibm.com) */ public class SimpleTargetedChain extends SimpleChain implements TargetedChain { protected static Log log = LogFactory.getLog(SimpleTargetedChain.class.getName()); protected Handler requestHandler ; protected Handler pivotHandler ; protected Handler responseHandler ; /** * Pivot indicator sets "past pivot point" before the response handler * runs. This avoids having to reimplement SimpleChain.invoke and * SimpleChain.generateWSDL. */ private class PivotIndicator extends BasicHandler { public PivotIndicator() {} public void invoke(MessageContext msgContext) throws AxisFault { msgContext.setPastPivot(true); } } /** * Default no-arg constructor. */ public SimpleTargetedChain() {} /** * Constructor for an instance with effectively only a pivot handler. * * @param handler the <code>Handler</code> to use */ public SimpleTargetedChain(Handler handler) { pivotHandler = handler; if (pivotHandler != null) { addHandler(pivotHandler); addHandler(new PivotIndicator()); } } /** * Constructor which takes real or null request, pivot, and response * handlers. */ public SimpleTargetedChain(Handler reqHandler, Handler pivHandler, Handler respHandler) { init(reqHandler, null, pivHandler, null, respHandler); } /** * Initialiser which takes real or null request, pivot, and response * handlers and which allows for special request and response * handlers to be inserted just before and after any pivot handler. * * @param reqHandler the request <code>Handler</code> * @param specialReqHandler the special request <code>Handler</code> * @param pivHandler the pivot <code>Handler</code> * @param specialRespHandler the special response <code>Handler</code> * @param respHandler the response <code>Handler</code> */ protected void init(Handler reqHandler, Handler specialReqHandler, Handler pivHandler, Handler specialRespHandler, Handler respHandler) { requestHandler = reqHandler; if (requestHandler != null) addHandler(requestHandler); if (specialReqHandler != null) addHandler(specialReqHandler); pivotHandler = pivHandler; if (pivotHandler != null) { addHandler(pivotHandler); addHandler(new PivotIndicator()); } if (specialRespHandler != null) addHandler(specialRespHandler); responseHandler = respHandler; if (responseHandler != null) addHandler(responseHandler); } public Handler getRequestHandler() { return( requestHandler ); } public Handler getPivotHandler() { return( pivotHandler ); } public Handler getResponseHandler() { return( responseHandler ); } };
7,314
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/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 org.apache.axis ; import org.apache.axis.attachments.Attachments; import org.apache.axis.client.AxisClient; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.schema.SchemaVersion; import org.apache.axis.session.Session; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.LockableHashtable; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.xml.rpc.Call; import javax.xml.rpc.handler.soap.SOAPMessageContext; import java.io.File; import java.util.ArrayList; import java.util.Hashtable; // fixme: fields are declared throughout this class, some at the top, and some // near to where they are used. We should move all field declarations into a // single block - it makes it easier to see what is decalred in this class and // what is inherited. It also makes it easier to find them. /** * A MessageContext is the Axis implementation of the javax * SOAPMessageContext class, and is core to message processing * in handlers and other parts of the system. * * This class also contains constants for accessing some * well-known properties. Using a hierarchical namespace is * strongly suggested in order to lower the chance for * conflicts. * * (These constants should be viewed as an explicit list of well * known and widely used context keys, there's nothing wrong * with directly using the key strings. This is the reason for * the hierarchical constant namespace. * * Actually I think we might just list the keys in the docs and * provide no such constants since they create yet another * namespace, but we'd have no compile-time checks then. * * Whaddya think? - todo by Jacek) * * * @author Doug Davis (dug@us.ibm.com) * @author Jacek Kopecky (jacek@idoox.com) */ public class MessageContext implements SOAPMessageContext { /** The <code>Log</code> used for logging all messages. */ protected static Log log = LogFactory.getLog(MessageContext.class.getName()); /** * The request message. If we're on the client, this is the outgoing * message heading to the server. If we're on the server, this is the * incoming message we've received from the client. */ private Message requestMessage; /** * The response message. If we're on the server, this is the outgoing * message heading back to the client. If we're on the client, this is the * incoming message we've received from the server. */ private Message responseMessage; /** * That unique key/name that the next router/dispatch handler should use * to determine what to do next. */ private String targetService; /** * The name of the Transport which this message was received on (or is * headed to, for the client). */ private String transportName; /** * The default <code>ClassLoader</code> that this service should use. */ private ClassLoader classLoader; /** * The AxisEngine which this context is involved with. */ private AxisEngine axisEngine; /** * A Session associated with this request. */ private Session session; /** * Should we track session state, or not? * default is not. * Could potentially refactor this so that * maintainSession iff session != null... */ private boolean maintainSession = false; // fixme: ambiguity here due to lac of docs - havePassedPivot vs // request/response, vs sending/processing & recieving/responding // I may have just missed the key bit of text /** * Are we doing request stuff, or response stuff? True if processing * response (I think). */ private boolean havePassedPivot = false; /** * Maximum amount of time to wait on a request, in milliseconds. */ private int timeout = Constants.DEFAULT_MESSAGE_TIMEOUT; /** * An indication of whether we require "high fidelity" recording of * deserialized messages for this interaction. Defaults to true for * now, and can be set to false, usually at service-dispatch time. */ private boolean highFidelity = true; /** * Storage for an arbitrary bag of properties associated with this * MessageContext. */ private LockableHashtable bag = new LockableHashtable(); /* * These variables are logically part of the bag, but are separated * because they are used often and the Hashtable is more expensive. * * fixme: this may be fixed by moving to a plain Map impl like HashMap. * Alternatively, we could hide all this magic behind a custom Map impl - * is synchronization on the map needed? these properties aren't * synchronized so I'm guessing not. */ private String username = null; private String password = null; private String encodingStyle = Use.ENCODED.getEncoding(); private boolean useSOAPAction = false; private String SOAPActionURI = null; /** * SOAP Actor roles. */ private String[] roles; /** Our SOAP namespaces and such. */ private SOAPConstants soapConstants = Constants.DEFAULT_SOAP_VERSION; /** Schema version information - defaults to 2001. */ private SchemaVersion schemaVersion = SchemaVersion.SCHEMA_2001; /** Our current operation. */ private OperationDesc currentOperation = null; /** * The current operation. * * @return the current operation; may be <code>null</code> */ public OperationDesc getOperation() { return currentOperation; } /** * Set the current operation. * * @param operation the <code>Operation</code> this context is executing */ public void setOperation(OperationDesc operation) { currentOperation = operation; } /** * Returns a list of operation descriptors that could may * possibly match a body containing an element of the given QName. * For non-DOCUMENT, the list of operation descriptors that match * the name is returned. For DOCUMENT, all the operations that have * qname as a parameter are returned * * @param qname of the first element in the body * @return list of operation descriptions * @throws AxisFault if the operation names could not be looked up */ public OperationDesc [] getPossibleOperationsByQName(QName qname) throws AxisFault { if (currentOperation != null) { return new OperationDesc [] { currentOperation }; } OperationDesc [] possibleOperations = null; if (serviceHandler == null) { try { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("dispatching00", qname.getNamespaceURI())); } // Try looking this QName up in our mapping table... setService(axisEngine.getConfig(). getServiceByNamespaceURI(qname.getNamespaceURI())); } catch (ConfigurationException e) { // Didn't find one... } } if (serviceHandler != null) { ServiceDesc desc = serviceHandler.getInitializedServiceDesc(this); if (desc != null) { if (desc.getStyle() != Style.DOCUMENT) { possibleOperations = desc.getOperationsByQName(qname); } else { // DOCUMENT Style // Get all of the operations that have qname as // a possible parameter QName ArrayList allOperations = desc.getOperations(); ArrayList foundOperations = new ArrayList(); for (int i=0; i < allOperations.size(); i++ ) { OperationDesc tryOp = (OperationDesc) allOperations.get(i); if (tryOp.getParamByQName(qname) != null) { foundOperations.add(tryOp); } } if (foundOperations.size() > 0) { possibleOperations = (OperationDesc[]) JavaUtils.convert(foundOperations, OperationDesc[].class); } } } } return possibleOperations; } /** * get the first possible operation that could match a * body containing an element of the given QName. Sets the currentOperation * field in the process; if that field is already set then its value * is returned instead * @param qname name of the message body * @return an operation or null * @throws AxisFault */ public OperationDesc getOperationByQName(QName qname) throws AxisFault { if (currentOperation == null) { OperationDesc [] possibleOperations = getPossibleOperationsByQName(qname); if (possibleOperations != null && possibleOperations.length > 0) { currentOperation = possibleOperations[0]; } } return currentOperation; } /** * Get the active message context. * * @return the current active message context */ public static MessageContext getCurrentContext() { return AxisEngine.getCurrentMessageContext(); } /** * Temporary directory to store attachments. */ protected static String systemTempDir= null; /** * set the temp dir * TODO: move this piece of code out of this class and into a utilities * class. */ static { try { //get the temp dir from the engine systemTempDir=AxisProperties.getProperty(AxisEngine.ENV_ATTACHMENT_DIR); } catch(Throwable t) { systemTempDir= null; } if(systemTempDir== null) { try { //or create and delete a file in the temp dir to make //sure we have write access to it. File tf= File.createTempFile("Axis", ".tmp"); File dir= tf.getParentFile(); if (tf.exists()) { tf.delete(); } if (dir != null) { systemTempDir= dir.getCanonicalPath(); } } catch(Throwable t) { log.debug("Unable to find a temp dir with write access"); systemTempDir= null; } } } /** * Create a message context. * @param engine the controlling axis engine. Null is actually accepted here, * though passing a null engine in is strongly discouraged as many of the methods * assume that it is in fact defined. */ public MessageContext(AxisEngine engine) { this.axisEngine = engine; if(null != engine){ java.util.Hashtable opts= engine.getOptions(); String attachmentsdir= null; if(null!=opts) { attachmentsdir= (String) opts.get(AxisEngine.PROP_ATTACHMENT_DIR); } if(null == attachmentsdir) { attachmentsdir= systemTempDir; } if(attachmentsdir != null){ setProperty(ATTACHMENTS_DIR, attachmentsdir); } // If SOAP 1.2 has been specified as the default for the engine, // switch the constants over. String defaultSOAPVersion = (String)engine.getOption( AxisEngine.PROP_SOAP_VERSION); if (defaultSOAPVersion != null && "1.2".equals(defaultSOAPVersion)) { setSOAPConstants(SOAPConstants.SOAP12_CONSTANTS); } String singleSOAPVersion = (String)engine.getOption( AxisEngine.PROP_SOAP_ALLOWED_VERSION); if (singleSOAPVersion != null) { if ("1.2".equals(singleSOAPVersion)) { setProperty(Constants.MC_SINGLE_SOAP_VERSION, SOAPConstants.SOAP12_CONSTANTS); } else if ("1.1".equals(singleSOAPVersion)) { setProperty(Constants.MC_SINGLE_SOAP_VERSION, SOAPConstants.SOAP11_CONSTANTS); } } } } /** * during finalization, the dispose() method is called. * @see #dispose() */ protected void finalize() { dispose(); } /** * Mappings of QNames to serializers/deserializers (and therfore * to Java types). */ private TypeMappingRegistry mappingRegistry = null; /** * Replace the engine's type mapping registry with a local one. This will * have no effect on any type mappings obtained before this call. * * @param reg the new <code>TypeMappingRegistry</code> */ public void setTypeMappingRegistry(TypeMappingRegistry reg) { mappingRegistry = reg; } /** * Get the currently in-scope type mapping registry. * * By default, will return a reference to the AxisEngine's TMR until * someone sets our local one (usually as a result of setting the * serviceHandler). * * @return the type mapping registry to use for this request. */ public TypeMappingRegistry getTypeMappingRegistry() { if (mappingRegistry == null) { return axisEngine.getTypeMappingRegistry(); } return mappingRegistry; } /** * Return the type mapping currently in scope for our encoding style. * * @return the type mapping */ public TypeMapping getTypeMapping() { return (TypeMapping)getTypeMappingRegistry(). getTypeMapping(encodingStyle); } /** * The name of the transport for this context. * * @return the transport name */ public String getTransportName() { return transportName; } // fixme: the transport names should be a type-safe e-num, or the range // of legal values should be specified in the documentation and validated // in the method (raising IllegalArgumentException) /** * Set the transport name for this context. * * @param transportName the name of the transport */ public void setTransportName(String transportName) { this.transportName = transportName; } /** * Get the <code>SOAPConstants</code> used by this message context. * * @return the soap constants */ public SOAPConstants getSOAPConstants() { return soapConstants; } /** * Set the <code>SOAPConstants</code> used by this message context. * This may also affect the encoding style. * * @param soapConstants the new soap constants to use */ public void setSOAPConstants(SOAPConstants soapConstants) { // when changing SOAP versions, remember to keep the encodingURI // in synch. if (this.soapConstants.getEncodingURI().equals(encodingStyle)) { encodingStyle = soapConstants.getEncodingURI(); } this.soapConstants = soapConstants; } /** * Get the XML schema version information. * * @return the <code>SchemaVersion</code> in use */ public SchemaVersion getSchemaVersion() { return schemaVersion; } /** * Set the XML schema version this message context will use. * * @param schemaVersion the new <code>SchemaVersion</code> */ public void setSchemaVersion(SchemaVersion schemaVersion) { this.schemaVersion = schemaVersion; } /** * Get the current session. * * @return the <code>Session</code> this message context is within */ public Session getSession() { return session; } /** * Set the current session. * * @param session the new <code>Session</code> */ public void setSession(Session session) { this.session = session; } /** * Indicates if the opration is encoded. * * @return <code>true</code> if it is encoded, <code>false</code> otherwise */ public boolean isEncoded() { return (getOperationUse() == Use.ENCODED); //return soapConstants.getEncodingURI().equals(encodingStyle); } /** * Set whether we are maintaining session state. * * @param yesno flag to set to <code>true</code> to maintain sessions */ public void setMaintainSession (boolean yesno) { maintainSession = yesno; } /** * Discover if we are maintaining session state. * * @return <code>true</code> if we are maintaining state, <code>false</code> * otherwise */ public boolean getMaintainSession () { return maintainSession; } /** * Get the request message. * * @return the request message (may be null). */ public Message getRequestMessage() { return requestMessage ; } /** * Set the request message, and make sure that message is associated * with this MessageContext. * * @param reqMsg the new request Message. */ public void setRequestMessage(Message reqMsg) { requestMessage = reqMsg ; if (requestMessage != null) { requestMessage.setMessageContext(this); } } /** * Get the response message. * * @return the response message (may be null). */ public Message getResponseMessage() { return responseMessage ; } /** * Set the response message, and make sure that message is associated * with this MessageContext. * * @param respMsg the new response Message. */ public void setResponseMessage(Message respMsg) { responseMessage = respMsg; if (responseMessage != null) { responseMessage.setMessageContext(this); //if we have received attachments of a particular type // than that should be the default type to send. Message reqMsg = getRequestMessage(); if (null != reqMsg) { Attachments reqAttch = reqMsg.getAttachmentsImpl(); Attachments respAttch = respMsg.getAttachmentsImpl(); if (null != reqAttch && null != respAttch) { if (respAttch.getSendType() == Attachments.SEND_TYPE_NOTSET) //only if not explicity set. respAttch.setSendType(reqAttch.getSendType()); } } } } /** * Return the current (i.e. request before the pivot, response after) * message. * * @return the current <code>Message</code> */ public Message getCurrentMessage() { return (havePassedPivot ? responseMessage : requestMessage); } /** * 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 javax.xml.soap.SOAPMessage getMessage() { return getCurrentMessage(); } /** * Set the current message. This will set the request before the pivot, * and the response afterwards, as guaged by the passedPivod property. * * @param curMsg the <code>Message</code> to assign */ public void setCurrentMessage(Message curMsg) { if ( curMsg != null ) curMsg.setMessageContext(this); if (havePassedPivot) { responseMessage = curMsg; } else { requestMessage = curMsg; } } /** * Sets the SOAPMessage for this message context. * This is equivalent to casting <code>message</code> to * <code>Message</code> and then passing it on to * <code>setCurrentMessage()</code>. * * @param message the <code>SOAPMessage</code> this context is for */ public void setMessage(javax.xml.soap.SOAPMessage message) { setCurrentMessage((Message)message); } /** * Determine when we've passed the pivot. * * @return <code>true</code> if we have, <code>false</code> otherwise */ public boolean getPastPivot() { return havePassedPivot; } // fixme: is there any legitimate case where we could pass the pivot and // then go back again? Is there documentation about the life-cycle of a // MessageContext, and in particular the re-use of instances that would be // relevant? /** * Indicate when we've passed the pivot. * * @param pastPivot true if we are past the pivot point, false otherwise */ public void setPastPivot(boolean pastPivot) { havePassedPivot = pastPivot; } /** * Set timeout in our MessageContext. * * @param value the maximum amount of time, in milliseconds */ public void setTimeout (int value) { timeout = value; } /** * Get timeout from our MessageContext. * * @return value the maximum amount of time, in milliseconds */ public int getTimeout () { return timeout; } /** * Get the classloader, implicitly binding to the thread context * classloader if an override has not been supplied. * * @return the class loader */ public ClassLoader getClassLoader() { if ( classLoader == null ) { classLoader = Thread.currentThread().getContextClassLoader(); } return( classLoader ); } /** * Set a new classloader. Setting to null will result in getClassLoader() * binding back to the thread context class loader. * * @param cl the new <code>ClassLoader</code> or <code>null</code> */ public void setClassLoader(ClassLoader cl ) { classLoader = cl ; } /** * Get the name of the targed service for this message. * * @return the target service */ public String getTargetService() { return targetService; } /** * Get the axis engine. This will be <code>null</code> if the message was * created outside an engine * * @return the current axis engine */ public AxisEngine getAxisEngine() { return axisEngine; } /** * Set the target service for this message. * <p> * This looks up the named service in the registry, and has * the side effect of setting our TypeMappingRegistry to the * service's. * * @param tServ the name of the target service * @throws AxisFault if anything goes wrong in resolving or setting the * service */ public void setTargetService(String tServ) throws AxisFault { log.debug("MessageContext: setTargetService(" + tServ+")"); if (tServ == null) { setService(null); } else { try { setService(getAxisEngine().getService(tServ)); } catch (AxisFault fault) { // If we're on the client, don't throw this fault... if (!isClient()) { throw fault; } } } targetService = tServ; } /** ServiceHandler is the handler that is the "service". This handler * can (and probably will actually be a chain that contains the * service specific request/response/pivot point handlers */ private SOAPService serviceHandler ; /** * Get the <code>SOAPService</code> used to handle services in this * context. * * @return the service handler */ public SOAPService getService() { return serviceHandler; } /** * Set the <code>SOAPService</code> used to handle services in this * context. This method configures a wide range of * <code>MessageContext</code> properties to suit the handler. * * @param sh the new service handler * @throws AxisFault if the service could not be set */ public void setService(SOAPService sh) throws AxisFault { log.debug("MessageContext: setServiceHandler("+sh+")"); serviceHandler = sh; if (sh != null) { if(!sh.isRunning()) { throw new AxisFault(Messages.getMessage("disabled00")); } targetService = sh.getName(); SOAPService service = sh; TypeMappingRegistry tmr = service.getTypeMappingRegistry(); setTypeMappingRegistry(tmr); // styles are not "soap version aware" so compensate... setEncodingStyle(service.getUse().getEncoding()); // This MessageContext should now defer properties it can't find // to the Service's options. bag.setParent(sh.getOptions()); // Note that we need (or don't need) high-fidelity SAX recording // of deserialized messages according to the setting on the // new service. highFidelity = service.needsHighFidelityRecording(); service.getInitializedServiceDesc(this); } } /** * Let us know whether this is the client or the server. * * @return true if we are a client */ public boolean isClient() { return (axisEngine instanceof AxisClient); } // fixme: public final statics tend to go in a block at the top of the // class deffinition, not marooned in the middle // fixme: chose public static final /or/ public final static /** Contains an instance of Handler, which is the * ServiceContext and the entrypoint of this service. * * (if it has been so configured - will our deployment * tool do this by default? - todo by Jacek) */ public static final String ENGINE_HANDLER = "engine.handler"; /** This String is the URL that the message came to. */ public static final String TRANS_URL = "transport.url"; /** Has a quit been requested? Hackish... but useful... -- RobJ */ public static final String QUIT_REQUESTED = "quit.requested"; /** Place to store an AuthenticatedUser. */ public static final String AUTHUSER = "authenticatedUser"; /** If on the client - this is the Call object. */ public static final String CALL = "call_object" ; /** Are we doing Msg vs RPC? - For Java Binding. */ public static final String IS_MSG = "isMsg" ; /** The directory where in coming attachments are created. */ public static final String ATTACHMENTS_DIR = "attachments.directory" ; /** A boolean param, to control whether we accept missing parameters * as nulls or refuse to acknowledge them. */ public final static String ACCEPTMISSINGPARAMS = "acceptMissingParams"; /** The value of the property is used by service WSDL generation (aka ?WSDL) * For the service's interface namespace if not set TRANS_URL property is used. */ public static final String WSDLGEN_INTFNAMESPACE = "axis.wsdlgen.intfnamespace"; /** The value of the property is used by service WSDL generation (aka ?WSDL). * For the service's location if not set TRANS_URL property is used. * (helps provide support through proxies. */ public static final String WSDLGEN_SERV_LOC_URL = "axis.wsdlgen.serv.loc.url"; // fixme: should this be a type-safe e-num? /** The value of the property is used by service WSDL generation (aka ?WSDL). * Set this property to request a certain level of HTTP. * The values MUST use org.apache.axis.transport.http.HTTPConstants.HEADER_PROTOCOL_10 * for HTTP 1.0 * The values MUST use org.apache.axis.transport.http.HTTPConstants.HEADER_PROTOCOL_11 * for HTTP 1.1 */ public static final String HTTP_TRANSPORT_VERSION = "axis.transport.version"; // fixme: is this the name of a security provider, or the name of a security // provider class, or the actualy class of a security provider, or // something else? /** * The security provider. */ public static final String SECURITY_PROVIDER = "securityProvider"; /* * IMPORTANT. * If adding any new constants to this class. Make them final. The * ones above are left non-final for compatibility reasons. */ /** * Get a <code>String</code> property by name. * * @param propName the name of the property to fetch * @return the value of the named property * @throws ClassCastException if the property named does not have a * <code>String</code> value */ public String getStrProp(String propName) { return (String) getProperty(propName); } /** * Tests to see if the named property is set in the 'bag', returning * <code>false</code> if it is not present at all. * This is equivalent to <code>isPropertyTrue(propName, false)</code>. * * @param propName the name of the property to check * @return true or false, depending on the value of the property */ public boolean isPropertyTrue(String propName) { return isPropertyTrue(propName, false); } /** * Test if a property is set to something we consider to be true in the * 'bag'. * <ul> * <li>If not there then <code>defaultVal</code> is returned.</li> * <li>If there, then...<ul> * <li>if its a <code>Boolean</code>, we'll return booleanValue()</li> * <li>if its an <code>Integer</code>, we'll return <code>false</code> * if its <code>0</code> else <code>true</code></li> * <li>if its a <code>String</code> we'll return <code>false</code> if its * <code>"false"</code>" or <code>"0"</code> else <code>true</code></li> * <li>All other types return <code>true</code></li> * </ul></li> * </ul> * * @param propName the name of the property to check * @param defaultVal the default value * @return true or false, depending on the value of the property */ public boolean isPropertyTrue(String propName, boolean defaultVal) { return JavaUtils.isTrue(getProperty(propName), defaultVal); } /** * Allows you to set a named property to the passed in value. * There are a few known properties (like username, password, etc) * that are variables in Call. The rest of the properties are * stored in a Hashtable. These common properties should be * accessed via the accessors for speed/type safety, but they may * still be obtained via this method. It's up to one of the * Handlers (or the Axis engine itself) to go looking for * one of them. * * @param name Name of the property * @param value Value of the property */ public void setProperty(String name, Object value) { if (name == null || value == null) { return; // Is this right? Shouldn't we throw an exception like: // throw new IllegalArgumentException(msg); } else if (name.equals(Call.USERNAME_PROPERTY)) { if (!(value instanceof String)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] { name, "java.lang.String", value.getClass().getName()})); } setUsername((String) value); } else if (name.equals(Call.PASSWORD_PROPERTY)) { if (!(value instanceof String)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] { name, "java.lang.String", value.getClass().getName()})); } setPassword((String) value); } else if (name.equals(Call.SESSION_MAINTAIN_PROPERTY)) { if (!(value instanceof Boolean)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] {name, "java.lang.Boolean", value.getClass().getName()})); } setMaintainSession(((Boolean) value).booleanValue()); } else if (name.equals(Call.SOAPACTION_USE_PROPERTY)) { if (!(value instanceof Boolean)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] {name, "java.lang.Boolean", value.getClass().getName()})); } setUseSOAPAction(((Boolean) value).booleanValue()); } else if (name.equals(Call.SOAPACTION_URI_PROPERTY)) { if (!(value instanceof String)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] {name, "java.lang.String", value.getClass().getName()})); } setSOAPActionURI((String) value); } else if (name.equals(Call.ENCODINGSTYLE_URI_PROPERTY)) { if (!(value instanceof String)) { throw new IllegalArgumentException( Messages.getMessage("badProp00", new String[] {name, "java.lang.String", value.getClass().getName()})); } setEncodingStyle((String) value); } else { bag.put(name, value); } } // setProperty /** * Returns true if the MessageContext 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 boolean containsProperty(String name) { Object propertyValue = getProperty(name); return (propertyValue != null); } /** * Returns an <code>Iterator</code> view of the names of the properties in * this <code>MessageContext</code>. * * @return an <code>Iterator</code> over all property names */ public java.util.Iterator getPropertyNames() { // fixme: this is potentially unsafe for the caller - changing the // properties will kill the iterator. Consider iterating over a copy: // return new HashSet(bag.keySet()).iterator(); return bag.keySet().iterator(); } /** * Returns an Iterator view of the names of the properties * in this MessageContext and any parents of the LockableHashtable * @return Iterator for the property names */ public java.util.Iterator getAllPropertyNames() { return bag.getAllKeys().iterator(); } /** * Returns the value associated with the named property - or null if not * defined/set. * * @param name the property name * @return Object value of the property - or null */ public Object getProperty(String name) { if (name != null) { if (name.equals(Call.USERNAME_PROPERTY)) { return getUsername(); } else if (name.equals(Call.PASSWORD_PROPERTY)) { return getPassword(); } else if (name.equals(Call.SESSION_MAINTAIN_PROPERTY)) { return getMaintainSession() ? Boolean.TRUE : Boolean.FALSE; } else if (name.equals(Call.OPERATION_STYLE_PROPERTY)) { return (getOperationStyle() == null) ? null : getOperationStyle().getName(); } else if (name.equals(Call.SOAPACTION_USE_PROPERTY)) { return useSOAPAction() ? Boolean.TRUE : Boolean.FALSE; } else if (name.equals(Call.SOAPACTION_URI_PROPERTY)) { return getSOAPActionURI(); } else if (name.equals(Call.ENCODINGSTYLE_URI_PROPERTY)) { return getEncodingStyle(); } else if (bag == null) { return null; } else { return bag.get(name); } } else { return null; } } // fixme: this makes no copy of parent, so later modifications to parent // can alter this context - is this intended? If so, it needs documenting. // If not, it needs fixing. /** * Set the Hashtable that contains the default values for our * properties. * * @param parent */ public void setPropertyParent(Hashtable parent) { bag.setParent(parent); } /** * Set the username. * * @param username the new user name */ public void setUsername(String username) { this.username = username; } // setUsername /** * Get the user name. * * @return the user name as a <code>String</code> */ public String getUsername() { return username; } // getUsername /** * Set the password. * * @param password a <code>String</code> containing the new password */ public void setPassword(String password) { this.password = password; } // setPassword /** * Get the password. * * @return the current password <code>String</code> */ public String getPassword() { return password; } // getPassword /** * Get the operation style. This is either the style of the current * operation or if that is not set, the style of the service handler, or * if that is not set, <code>Style.RPC</code>. * * @return the <code>Style</code> of this message */ public Style getOperationStyle() { if (currentOperation != null) { return currentOperation.getStyle(); } if (serviceHandler != null) { return serviceHandler.getStyle(); } return Style.RPC; } // getOperationStyle /** * Get the operation use. * * @return the operation <code>Use</code> */ public Use getOperationUse() { if (currentOperation != null) { return currentOperation.getUse(); } if (serviceHandler != null) { return serviceHandler.getUse(); } return Use.ENCODED; } // getOperationUse /** * Enable or dissable the use of soap action information. When enabled, * the message context will attempt to use the soap action URI * information during binding of soap messages to service methods. When * dissabled, it will make no such attempt. * * @param useSOAPAction <code>true</code> if soap action URI information * should be used, <code>false</code> otherwise */ public void setUseSOAPAction(boolean useSOAPAction) { this.useSOAPAction = useSOAPAction; } // setUseSOAPAction // fixme: this doesn't follow beany naming conventions - should be // isUseSOAPActions or getUseSOAPActions or something prettier /** * Indicates wether the soap action URI is being used or not. * * @return <code>true</code> if it is, <code>false</code> otherwise */ public boolean useSOAPAction() { return useSOAPAction; } // useSOAPAction // fixme: this throws IllegalArgumentException but never raises it - // perhaps in a sub-class? // fixme: IllegalArgumentException is unchecked. Best practice says you // should document unchecked exceptions, but not list them in throws /** * Set the soapAction URI. * * @param SOAPActionURI a <code>String</code> giving the new soap action * URI * @throws IllegalArgumentException if the URI is not liked */ public void setSOAPActionURI(String SOAPActionURI) throws IllegalArgumentException { this.SOAPActionURI = SOAPActionURI; } // setSOAPActionURI /** * Get the soapAction URI. * * @return the URI of this soap action */ public String getSOAPActionURI() { return SOAPActionURI; } // getSOAPActionURI /** * Sets the encoding style to the URI passed in. * * @param namespaceURI URI of the encoding to use. */ public void setEncodingStyle(String namespaceURI) { if (namespaceURI == null) { namespaceURI = Constants.URI_LITERAL_ENC; } else if (Constants.isSOAP_ENC(namespaceURI)) { namespaceURI = soapConstants.getEncodingURI(); } encodingStyle = namespaceURI; } // setEncodingStype /** * Returns the encoding style as a URI that should be used for the SOAP * message. * * @return String URI of the encoding style to use */ public String getEncodingStyle() { return encodingStyle; } // getEncodingStyle public void removeProperty(String propName) { if (bag != null) { bag.remove(propName); } } /** * Return this context to a clean state. */ public void reset() { if (bag != null) { bag.clear(); } serviceHandler = null; havePassedPivot = false; currentOperation = null; } /** * Read the high fidelity property. * <p> * Some behavior may be apropreate for high fidelity contexts that is not * relevant for low fidelity ones or vica-versa. * * @return <code>true</code> if the context is high fidelity, * <code>false</code> otherwise */ public boolean isHighFidelity() { return highFidelity; } /** * Set the high fidelity propert. * <p> * Users of the context may be changing what they do based upon this flag. * * @param highFidelity the new value of the highFidelity property */ public void setHighFidelity(boolean highFidelity) { this.highFidelity = highFidelity; } /** * Gets the SOAP actor roles associated with an execution of the * <code>HandlerChain</code> and its contained <code>Handler</code> * instances. * <p> * <i>Not (yet) implemented method in the SOAPMessageContext interface</i>. * <p> * <b>Note:</b> 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 * <code>HandlerChain</code> 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 * <code>HandlerChain</code>. * * @return an 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 String[] getRoles() { //TODO: Flesh this out. return roles; } /** * Set the SOAP actor roles associated with an executioni of * <code>CodeHandlerChain</code> and its contained <code>Handler</code> * instances. * * @param roles an array of <code>String</code> instances, each representing * the URI for a SOAP actor role */ public void setRoles( String[] roles) { this.roles = roles; } /** * if a message (or subclass) has any disposal needs, this method * is where it goes. Subclasses *must* call super.dispose(), and * be prepared to be called from the finalizer as well as earlier */ public synchronized void dispose() { log.debug("disposing of message context"); if(requestMessage!=null) { requestMessage.dispose(); requestMessage=null; } if(responseMessage!=null) { responseMessage.dispose(); responseMessage=null; } } }
7,315
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Handler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis ; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.io.Serializable; import java.util.Hashtable; import java.util.List; /** * An AXIS handler. * * @author Doug Davis (dug@us.ibm.com) */ public interface Handler extends Serializable { /** * Init is called when the chain containing this Handler object * is instantiated. */ public void init(); /** * Cleanup is called when the chain containing this Handler object * is done processing the chain. */ public void cleanup(); /** * Invoke is called to do the actual work of the Handler object. * If there is a fault during the processing of this method it is * invoke's job to catch the exception and undo any partial work * that has been completed. Once we leave 'invoke' if a fault * is thrown, this classes 'onFault' method will be called. * Invoke should rethrow any exceptions it catches, wrapped in * an AxisFault. * * @param msgContext the <code>MessageContext</code> to process with this * <code>Handler</code>. * @throws AxisFault if the handler encounters an error */ public void invoke(MessageContext msgContext) throws AxisFault ; /** * Called when a subsequent handler throws a fault. * * @param msgContext the <code>MessageContext</code> to process the fault * to */ public void onFault(MessageContext msgContext); /** * Indicate if this handler can process <code>qname</code>. * * @param qname the <code>QName</code> to check * @return true if this <code>Handler</code> can handle <code>qname</code>, * false otherwise */ public boolean canHandleBlock(QName qname); // fixme: will modifications to this List be reflected in the state of this // handler? /** * Return a list of QNames which this Handler understands. By returning * a particular QName here, we are committing to fulfilling any contracts * defined in the specification of the SOAP header with that QName. * * @return a List of <code>QName</code> instances */ public List getUnderstoodHeaders(); // fixme: doesn't specify what happens when an option is re-defined /** * Add the given option (name/value) to this handler's bag of options. * * @param name the name of the option * @param value the new value of the option */ public void setOption(String name, Object value); /** * Returns the option corresponding to the 'name' given. * * @param name the name of the option * @return the value of the option */ public Object getOption(String name); /** * Set the name (i.e. registry key) of this Handler. * * @param name the new name */ public void setName(String name); /** * Return the name (i.e. registry key) for this <code>Handler</code>. * * @return the name for this <code>Handler</code> */ public String getName(); // fixme: doesn't tell us if modifying this Hashset will modify this Handler // fixme: do we mean to use a Hahset, or will Map do? /** * Return the entire list of options. * * @return a <code>Hashset</code> containing all name/value pairs */ public Hashtable getOptions(); // fixme: this doesn't indicate if opts becomes the new value of // getOptions(), or if it is merged into it. Also doesn't specify if // modifications to opts after calling this method will affect this handler /** * Sets a whole list of options. * * @param opts a <code>Hashtable</code> of name-value pairs to use */ public void setOptions(Hashtable opts); // fixme: presumably doc is used as the factory & host for Element, and // Element should not be grafted into doc by getDeploymentData, but will // potentially be grafted in by code calling this - could we clarify this? /** * This will return the root element of an XML doc that describes the * deployment information about this handler. This is NOT the WSDL, * this is all of the static internal data use by Axis - WSDL takes into * account run-time information (like which service we're talking about) * this is just the data that's stored in the registry. Used by the * 'list' Admin function. * * @param doc a <code>Document</code> within which to build the deployment * data * @return an Element representing the deployment data */ public Element getDeploymentData(Document doc); /** * Obtain WSDL information. Some Handlers will implement this by * merely setting properties in the MessageContext, others (providers) * will take responsibility for doing the "real work" of generating * WSDL for a given service. * * @param msgContext the <code>MessageContext</code> to generate the WSDL * to * @throws AxisFault if there was a problem generating the WSDL */ public void generateWSDL(MessageContext msgContext) throws AxisFault; };
7,316
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/TargetedChain.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; // fixme: this interface needs a propper description of what it is, who uses // it and how to use it /** * @author James Snell (jasnell@us.ibm.com) */ public interface TargetedChain extends Chain { /** * Returns the Request handler. * * @return the request <code>Handler</code> */ public Handler getRequestHandler(); /** * Returns the Pivot Handler. * * @return the pivot <code>Handler</code> */ public Handler getPivotHandler(); /** * Returns the Response Handler. * * @return the response <code>Handler</code> */ public Handler getResponseHandler(); }
7,317
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/InternalException.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; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * Encapsulates exceptions for "should never occur" situations. Extends * RuntimeException so it need not explicitly be caught. Logs the exception * as a fatal error, and if debug is enabled, includes the full stack trace. * * @author Sam Ruby (rubys@us.ibm.com) * @author Glyn Normington (glyn_normington@uk.ibm.com) */ public class InternalException extends RuntimeException { /** * The <code>Log</code> used by this class to log messages. */ protected static Log log = LogFactory.getLog(InternalException.class.getName()); /** * Attribute which controls whether or not logging of such events should * occur. Default is true and is recommended. Sometimes this may be * turned off in unit tests when internal errors are intentionally * provoked. */ private static boolean shouldLog = true; /** * Enable or dissable logging. * * @param logging true if you wish logging to be enabled, false otherwise */ public static void setLogging(boolean logging) { shouldLog = logging; } /** * Discover whether the logging flag is set. * * @return true if we are logging, false otherwise */ public static boolean getLogging() { return shouldLog; } /** * Construct an Internal Exception from a String. The string is wrapped * in an exception, enabling a stack traceback to be obtained. * @param message String form of the error */ public InternalException(String message) { this(new Exception(message)); } /** * Construct an Internal Exception from an Exception. * * @param e original exception which was unexpected */ public InternalException(Exception e) { super(e.toString()); if (shouldLog) { // if the exception is merely bubbling up the stack, only log the // event if debug is turned on. if (e instanceof InternalException) { log.debug("InternalException: ", e); } else { log.fatal(Messages.getMessage("exception00"), e); } } } }
7,318
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Part.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; /** * A part of a MIME message. Typically, in a MIME message there will be one * <code>SOAPPart</code> containing the SOAP message, and 0 or more * <code>AttachmentParts</code> instances containing each of the attachments. */ public interface Part extends java.io.Serializable { /** * Gets all the values of the <CODE>MimeHeader</CODE> object * in this <CODE>SOAPPart</CODE> object that is identified by * the given <CODE>String</CODE>. * @param name the name of the header; example: * "Content-Type" * @return a <CODE>String</CODE> array giving all the values for * the specified header */ public String[] getMimeHeader(String name); // fixme: no explicit method to get the value associated with a header e.g. // String getMimeHeader(header) /** * Add the specified MIME header, as per JAXM. * * @param header the MIME header name * @param value the value associated with the header */ public void addMimeHeader (String header, String value); // fixme: what do we mean by location? Is this a URL, a locator in a stream, // a place in the xml? something else? /** * Get the content location. * * @return a <code>String</code> giving the location */ public String getContentLocation(); /** * Set content location. * * @param loc the new location */ public void setContentLocation(String loc); // fixme: confusing docs - what's going on here? /** * Sets Content-Id of this part. * already defined. * @param newCid new Content-Id */ public void setContentId(String newCid); /** * Get the content ID. * * @return the content ID */ public String getContentId(); // for these 2 methods... // fixme: is this an iterator over mime header names or values? // fixme: why this API rather than just exposing the header names, and // a method to fetch the value for a name? /** * Get an <code>Iterator</code> over all headers that match any item in * <code>match</code>. */ public java.util.Iterator getMatchingMimeHeaders( final String[] match); /** * Get all headers that do not match. */ public java.util.Iterator getNonMatchingMimeHeaders( final String[] match); // fixke: are content types MIME types or something else, or what? /** * Get the content type. * * @return the content type <code>String</code> */ public String getContentType(); /** * Content ID. * * @return the contentId reference value that should be used directly * as an href in a SOAP element to reference this attachment. * <B>Not part of JAX-RPC, JAX-M, SAAJ, etc. </B> */ public String getContentIdRef(); }
7,319
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Chain.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 ; /** * A <code>Handler</code> that executes a 'chain' of child handlers in order. * * @author Doug Davis (dug@us.ibm.com.com) */ public interface Chain extends Handler { // fixme: if this can't be called after invoke, what exception should we // document as being thrown if someone tries it? /** * Adds a handler to the end of the chain. May not be called after invoke. * * @param handler the <code>Handler</code> to be added */ public void addHandler(Handler handler); /** * Discover if a handler is in this chain. * * @param handler the <code>Handler</code> to check * @return <code>true</code> if it is in this chain, <code>false</code> * otherwise */ public boolean contains(Handler handler); // fixme: do we want to use an array here, or a List? the addHandler method // kind of indicates that the chain is dynamic // fixme: there's nothing in this contract about whether modifying this // list of handlers will modify the chain or not - seems like a bad idea to // expose the stoorage as we have addHandler and contains methods. // fixme: would adding an iterator, size and remove method mean we could // drop this entirely? /** * Get the list of handlers in the chain. Is Handler[] the right form? * * @return an array of <code>Handler</code>s that have been added */ public Handler[] getHandlers(); // How many do we want to force people to implement? };
7,320
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/NoEndPointException.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; import org.apache.axis.utils.Messages; /** * An exception to indicate that there is no end point. * * @author Russell Butek (butek@us.ibm.com) */ public class NoEndPointException extends AxisFault { /** * Create a new exception with the default message and other details. */ public NoEndPointException () { super("Server.NoEndpoint", Messages.getMessage("noEndpoint"), null, null); } // ctor } // class NoEndPointException
7,321
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/FaultableHandler.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 ; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import java.util.Enumeration; import java.util.Hashtable; /** * A <code>FaultableHandler</code> is essentially a wrapper for any other * Handler which provides flexible fault handling semantics. * * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) */ public class FaultableHandler extends BasicHandler { /** * The <code>Log</code> used to log all events that would be of general * interest. */ protected static Log log = LogFactory.getLog(FaultableHandler.class.getName()); /** * The <code>Log</code> used for enterprise-centric logging. * * The enterprise category is for stuff that an enterprise product might * want to track, but in a simple environment (like the AXIS build) would * be nothing more than a nuisance. */ protected static Log entLog = LogFactory.getLog(Constants.ENTERPRISE_LOG_CATEGORY); /** * The <code>Handler</code> that will do the actual work of handeling the * fault. */ protected Handler workHandler ; /** * Create a new FaultHandler. * * @param workHandler the Handler we're going to wrap with Fault semantics. */ public FaultableHandler(Handler workHandler) { this.workHandler = workHandler; } public void init() { workHandler.init(); } public void cleanup() { workHandler.cleanup(); } /** * Invokes the specified handler. If there's a fault the appropriate * key will be calculated and used to find the fault chain to be * invoked. This assumes that the workHandler has caught the exception * and already done its fault processing - as needed. * * @param msgContext the <code>MessageContext</code> to process * @throws AxisFault if anything goes terminally wrong */ public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: FaultableHandler::invoke"); try { workHandler.invoke( msgContext ); } catch( Exception e ) { entLog.info(Messages.getMessage("toAxisFault00"), e ); AxisFault fault = AxisFault.makeFault(e); // AxisEngine engine = msgContext.getAxisEngine(); /** Index off fault code. * * !!! TODO: This needs to be able to handle searching by faultcode * hierarchy, i.e. "Server.General.*" or "Server.*", with the * most specific match winning. */ /* QFault key = fault.getFaultCode() ; Handler faultHandler = (Handler) faultHandlers.get( key ); */ Handler faultHandler = null; Hashtable options = getOptions(); if (options != null) { Enumeration enumeration = options.keys(); while (enumeration.hasMoreElements()) { String s = (String) enumeration.nextElement(); if (s.equals("fault-" + fault.getFaultCode().getLocalPart())) { faultHandler = (Handler)options.get(s); } } } if ( faultHandler != null ) { /** faultHandler will (re)throw if it's appropriate, but it * might also eat the fault. Which brings up another issue - * should we have a way to pass the Fault directly to the * faultHandler? Maybe another well-known MessageContext * property? */ faultHandler.invoke( msgContext ); } else { throw fault; } } log.debug("Exit: FaultableHandler::invoke"); } /** * Some handler later on has faulted so we need to process the fault. * * @param msgContext the context to process */ public void onFault(MessageContext msgContext) { log.debug("Enter: FaultableHandler::onFault"); workHandler.onFault( msgContext ); log.debug("Exit: FaultableHandler::onFault"); } public boolean canHandleBlock(QName qname) { return( workHandler.canHandleBlock(qname) ); } };
7,322
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/EngineConfigurationFactory.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; /** * EngineConfigurationFactory is an interface used to construct * concrete EngineConfiguration instances. * * Each EngineConfigurationFactory must also (directly) implement * the following static method: * * //Creates and returns a new EngineConfigurationFactory. * //If a factory cannot be created, return 'null'. * // * //The factory may return non-NULL only if: * // - it knows what to do with the param (check type &amp; process value) * // - it can find it's configuration information * // * //@see org.apache.axis.configuration.EngineConfigurationFactoryFinder * * public static EngineConfigurationFactory newFactory(Object param); * * This is checked at runtime and a warning generated for * factories found that do NOT implement this. * * @author Richard A. Sitze * @author Glyn Normington (glyn@apache.org) */ public interface EngineConfigurationFactory { /** * Property name used for setting an EngineConfiguration to be used * in creating engines. */ public static final String SYSTEM_PROPERTY_NAME = "axis.EngineConfigFactory"; /** * Get a default client engine configuration. * * @return a client EngineConfiguration */ public EngineConfiguration getClientEngineConfig(); /** * Get a default server engine configuration. * * @return a server EngineConfiguration */ public EngineConfiguration getServerEngineConfig(); }
7,323
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/WSDDEngineConfiguration.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; import org.apache.axis.deployment.wsdd.WSDDDeployment; /** * Extends EngineConfiguration interface to provide hook to * internal WSDD deployment info. * * @author Richard Sitze (rsitze@apache.org) * @author Glyn Normington (glyn@apache.org) * @author Glen Daniels (gdaniels@apache.org) */ public interface WSDDEngineConfiguration extends EngineConfiguration { /** * Get the WSDDDeployment for this engine configuration. * * @return the WSDDDeployment */ public WSDDDeployment getDeployment(); }
7,324
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/EngineConfiguration.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; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.handlers.soap.SOAPService; import javax.xml.namespace.QName; import java.util.Hashtable; import java.util.Iterator; import java.util.List; /** * EngineConfiguration is an interface that the Message Flow subsystem * provides so that engine configuration can be provided in a pluggable * way. An instance of EngineConfiguration provides configuration * for a particular engine instance. * <p> * Concrete implementations of this interface will obtain configuration * information from some source (examples might be files, Strings, or * databases) and are responsible for writing it into an AxisEngine, and * writing an AxisEngine's state back out to whatever storage medium is in use. * * @author Glyn Normington (glyn@apache.org) * @author Glen Daniels (gdaniels@apache.org) */ public interface EngineConfiguration { /** * Property name used for setting an EngineConfiguration to be used * in creating engines. */ static final String PROPERTY_NAME = "engineConfig"; /** * Configure this AxisEngine using whatever data source we have. * * @param engine the AxisEngine we'll deploy state to * @throws ConfigurationException if there was a problem */ void configureEngine(AxisEngine engine) throws ConfigurationException; /** * Read the configuration from an engine, and store it somehow. * * @param engine the AxisEngine from which to read state. * @throws ConfigurationException if there was a problem */ void writeEngineConfig(AxisEngine engine) throws ConfigurationException; // fixme: if no handler is found, do we return null, or throw a // ConfigurationException, or throw another exception? IMHO returning // null is nearly always evil /** * Retrieve an instance of the named handler. * * @param qname the <code>QName</code> identifying the * <code>Handler</code> * @return the <code>Handler</code> associated with <code>qname</code> * @throws ConfigurationException if there was a failure in resolving * <code>qname</code> */ Handler getHandler(QName qname) throws ConfigurationException; /** * Retrieve an instance of the named service. * * @param qname the <code>QName</code> identifying the * <code>Service</code> * @return the <code>Service</code> associated with <code>qname</code> * @throws ConfigurationException if there was an error resolving the * qname */ SOAPService getService(QName qname) throws ConfigurationException; /** * Get a service which has been mapped to a particular namespace. * * @param namespace a namespace URI * @return an instance of the appropriate Service, or null * @throws ConfigurationException if there was an error resolving the * namespace */ SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException; /** * Retrieve an instance of the named transport. * * @param qname the <code>QName</code> of the transport * @return a <code>Handler</code> implementing the transport * @throws ConfigurationException if there was an error resolving the * transport */ Handler getTransport(QName qname) throws ConfigurationException; /** * Retrieve the TypeMappingRegistry for this engine. * * @return the type mapping registry * @throws ConfigurationException if there was an error resolving the * registry */ TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException; /** * Returns a global request handler. * * @return the <code>Handler</code> that globally handles requests * @throws ConfigurationException if there was some error fetching the * handler */ Handler getGlobalRequest() throws ConfigurationException; /** * Returns a global response handler. * * @return the <code>Handler</code> that globally handles responses * @throws ConfigurationException if there was some error fetching the * handler */ Handler getGlobalResponse() throws ConfigurationException; // fixme: where is the contract for what can be in this Hashtable? // fixme: did we intend to use Hashtable? Will Map do? Do we need // synchronization? If so, will one of the Collections synchronized // wrappers do fine? /** * Returns the global configuration options. * * @return the global options as a <code>Hashtable</code> * @throws ConfigurationException if the global options could not be * returned */ Hashtable getGlobalOptions() throws ConfigurationException; /** * Get an enumeration of the services deployed to this engine. * Each service is represented as <code>ServiceDesc</code> object. * * @see org.apache.axis.description.ServiceDesc * @return an <code>Iterator</code> over the <code>ServiceDesc</code> * objects * @throws ConfigurationException if the deployed services could not be * returned */ Iterator getDeployedServices() throws ConfigurationException; /** * Get a list of roles that this engine plays globally. Services * within the engine configuration may also add additional roles. * * @return a <code>List</code> of the roles for this engine */ List getRoles(); }
7,325
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/AxisServiceConfig.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; /** If a Java class which acts as the target for an Axis service * implements this interface, it may convey metadata about its * configuration to the Axis engine. * * @author Glen Daniels (gdaniels@apache.org) */ public interface AxisServiceConfig { /** Get the allowed method names. * * @return a space-delimited list of method names which may be called * via SOAP. */ public String getAllowedMethods(); }
7,326
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/SOAPPart.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 ; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.message.InputStreamBody; import org.apache.axis.message.MimeHeaders; import org.apache.axis.message.SOAPDocumentImpl; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.ByteArray; import org.apache.axis.utils.Messages; import org.apache.axis.utils.SessionUtils; import org.apache.axis.utils.XMLUtils; import org.apache.axis.handlers.HandlerChainImpl; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.Iterator; import java.util.Vector; /** * The SOAPPart provides access to the root part of the Message which * contains the envelope. * <p> * SOAPPart implements Part, providing common MIME operations. * <p> * SOAPPart also allows access to its envelope, * as a string, byte[], InputStream, or SOAPEnvelope. (This functionality * used to be in Message, and has been moved here more or less verbatim * pending further cleanup.) * * @author Rob Jellinghaus (robj@unrealities.com) * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@allaire.com) * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class SOAPPart extends javax.xml.soap.SOAPPart implements Part { protected static Log log = LogFactory.getLog(SOAPPart.class.getName()); public static final int FORM_STRING = 1; public static final int FORM_INPUTSTREAM = 2; public static final int FORM_SOAPENVELOPE = 3; public static final int FORM_BYTES = 4; public static final int FORM_BODYINSTREAM = 5; public static final int FORM_FAULT = 6; public static final int FORM_OPTIMIZED = 7; private int currentForm; /** * property used to set SOAPEnvelope as default form */ public static final String ALLOW_FORM_OPTIMIZATION = "axis.form.optimization"; //private Hashtable headers = new Hashtable(); private MimeHeaders mimeHeaders = new MimeHeaders(); private static final String[] formNames = { "", "FORM_STRING", "FORM_INPUTSTREAM", "FORM_SOAPENVELOPE", "FORM_BYTES", "FORM_BODYINSTREAM", "FORM_FAULT", "FORM_OPTIMIZED" }; /** * The current representation of the SOAP contents of this part. * May be a String, byte[], InputStream, or SOAPEnvelope, depending * on whatever was last asked for. (ack) * <p> * currentForm must have the corresponding value. * <p> * As someone once said: "Just a placeholder until we figure out what the actual Message * object is." */ private Object currentMessage ; /** * default message encoding charset */ private String currentEncoding = "UTF-8"; // These two fields are used for caching in getAsString and getAsBytes private String currentMessageAsString = null; private byte[] currentMessageAsBytes = null; private org.apache.axis.message.SOAPEnvelope currentMessageAsEnvelope= null; /** * Message object this part is tied to. Used for serialization settings. */ private Message msgObject; /** Field contentSource. */ private Source contentSource = null; /** * The original message. Again, may be String, byte[], InputStream, * or SOAPEnvelope. */ // private Object originalMessage ; //free up reference this is not in use. /** * Create a new SOAPPart. * <p> * Do not call this directly! Should only be called by Message. * * @param parent the parent <code>Message</code> * @param initialContents the initial contens <code>Object</code> * @param isBodyStream if the body is in a stream */ public SOAPPart(Message parent, Object initialContents, boolean isBodyStream) { setMimeHeader(HTTPConstants.HEADER_CONTENT_ID , SessionUtils.generateSessionId()); setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE , "text/xml"); msgObject=parent; // originalMessage = initialContents; int form = FORM_STRING; if (initialContents instanceof SOAPEnvelope) { form = FORM_SOAPENVELOPE; ((SOAPEnvelope)initialContents).setOwnerDocument(this); } else if (initialContents instanceof InputStream) { form = isBodyStream ? FORM_BODYINSTREAM : FORM_INPUTSTREAM; } else if (initialContents instanceof byte[]) { form = FORM_BYTES; } else if (initialContents instanceof AxisFault) { form = FORM_FAULT; } if (log.isDebugEnabled()) { log.debug("Enter: SOAPPart ctor(" + formNames[form] + ")"); } setCurrentMessage(initialContents, form); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart ctor()"); } } /** * Get the <code>Message</code> for this <code>Part</code>. * * @return the <code>Message</code> for this <code>Part</code> */ public Message getMessage(){ return msgObject; } /** * Set the Message for this Part. * Do not call this Directly. Called by Message. * * @param msg the <code>Message</code> for this part */ public void setMessage (Message msg) { this.msgObject= msg; } /** * Content type is always "text/xml" for SOAPParts. * * @return the content type */ public String getContentType() { return "text/xml"; } /** * Get the content length for this SOAPPart. * This will force buffering of the SOAPPart, but it will * also cache the byte[] form of the SOAPPart. * * @return the content length in bytes */ public long getContentLength() throws AxisFault { saveChanges(); if (currentForm == FORM_OPTIMIZED) { return ((ByteArray) currentMessage).size(); } else if (currentForm == FORM_BYTES) { return ((byte[]) currentMessage).length; } byte[] bytes = this.getAsBytes(); return bytes.length; } /** * This set the SOAP Envelope for this part. * <p> * Note: It breaks the chicken/egg created. * I need a message to create an attachment... * From the attachment I should be able to get a reference... * I now want to edit elements in the envelope in order to * place the attachment reference to it. * How do I now update the SOAP envelope with what I've changed? * * @param env the <code>SOAPEnvelope</CODE> for this <code>SOAPPart</code> */ public void setSOAPEnvelope(org.apache.axis.message.SOAPEnvelope env){ setCurrentMessage(env, FORM_SOAPENVELOPE) ; } /** * Write the contents to the specified stream. * * @param os the <code>java.io.OutputStream</code> to write to */ public void writeTo(java.io.OutputStream os) throws IOException { if ( currentForm == FORM_BYTES ) { os.write((byte[])currentMessage); } else if ( currentForm == FORM_OPTIMIZED ) { ((ByteArray) currentMessage).writeTo(os); } else { Writer writer = new OutputStreamWriter(os, currentEncoding); writer = new BufferedWriter(new PrintWriter(writer)); writeTo(writer); writer.flush(); } } /** * Write the contents to the specified writer. * * @param writer the <code>Writer</code> to write to */ public void writeTo(Writer writer) throws IOException { boolean inclXmlDecl = false; if (msgObject.getMessageContext() != null) { // if we have message context (JAX-RPC), write xml decl always. inclXmlDecl = true; } else { // if we have no message context (SAAJ), write xml decl according to property. try { String xmlDecl = (String)msgObject.getProperty(SOAPMessage.WRITE_XML_DECLARATION); if (xmlDecl != null && xmlDecl.equals("true")) { inclXmlDecl = true; } } catch (SOAPException e) { throw new IOException(e.getMessage()); } } if ( currentForm == FORM_FAULT ) { AxisFault env = (AxisFault)currentMessage; try { SerializationContext serContext = new SerializationContext(writer, getMessage().getMessageContext()); serContext.setSendDecl(inclXmlDecl); serContext.setEncoding(currentEncoding); env.output(serContext); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw env; } return; } if ( currentForm == FORM_SOAPENVELOPE ) { SOAPEnvelope env = (SOAPEnvelope)currentMessage; try { SerializationContext serContext = new SerializationContext(writer, getMessage().getMessageContext()); serContext.setSendDecl(inclXmlDecl); serContext.setEncoding(currentEncoding); env.output(serContext); } catch (Exception e) { throw AxisFault.makeFault(e); } return; } String xml = this.getAsString(); if(inclXmlDecl){ if(!xml.startsWith("<?xml")){ writer.write("<?xml version=\"1.0\" encoding=\""); writer.write(currentEncoding); writer.write("\"?>"); } } writer.write(xml); } /** * Get the current message, in whatever form it happens to be right now. * Will return a String, byte[], InputStream, or SOAPEnvelope, depending * on circumstances. * <p> * The method name is historical. * TODO: rename this for clarity; should be more like getContents. * * @return the current content */ public Object getCurrentMessage() { return currentMessage; } /** * Set the current message * @param currMsg * @param form */ public void setCurrentMessage(Object currMsg, int form) { currentMessageAsString = null; //Get rid of any cached stuff this is new. currentMessageAsBytes = null; currentMessageAsEnvelope= null; setCurrentForm(currMsg, form); } /** * Set the current contents of this Part. * The method name is historical. * TODO: rename this for clarity to something more like setContents??? * * @param currMsg the new content of this part * @param form the form of the message */ private void setCurrentForm(Object currMsg, int form) { if (log.isDebugEnabled()) { String msgStr; if (currMsg instanceof String) { msgStr = (String)currMsg; } else { msgStr = currMsg.getClass().getName(); } log.debug(Messages.getMessage("setMsgForm", formNames[form], "" + msgStr)); } // only change form if allowed if (isFormOptimizationAllowed()) { currentMessage = currMsg; currentForm = form; if (currentForm == FORM_SOAPENVELOPE) { currentMessageAsEnvelope = (org.apache.axis.message.SOAPEnvelope) currMsg; } } } /** * check if the allow optimization flag is on * @return form optimization flag */ private boolean isFormOptimizationAllowed() { boolean allowFormOptimization = true; Message msg = getMessage(); if (msg != null) { MessageContext ctx = msg.getMessageContext(); if (ctx != null) { Boolean propFormOptimization = (Boolean)ctx.getProperty(ALLOW_FORM_OPTIMIZATION); if (propFormOptimization != null) { allowFormOptimization = propFormOptimization.booleanValue(); } } } return allowFormOptimization; } public int getCurrentForm() { return currentForm; } /** * Get the contents of this Part (not the headers!), as a byte * array. This will force buffering of the message. * * @return an array of bytes containing a byte representation of this Part * @throws AxisFault if this Part can't be serialized to the byte array */ public byte[] getAsBytes() throws AxisFault { log.debug("Enter: SOAPPart::getAsBytes"); if ( currentForm == FORM_OPTIMIZED ) { log.debug("Exit: SOAPPart::getAsBytes"); try { return ((ByteArray) currentMessage).toByteArray(); } catch (IOException e) { throw AxisFault.makeFault(e); } } if ( currentForm == FORM_BYTES ) { log.debug("Exit: SOAPPart::getAsBytes"); return (byte[])currentMessage; } if ( currentForm == FORM_BODYINSTREAM ) { try { getAsSOAPEnvelope(); } catch (Exception e) { log.fatal(Messages.getMessage("makeEnvFail00"), e); log.debug("Exit: SOAPPart::getAsBytes"); return null; } } if ( currentForm == FORM_INPUTSTREAM ) { // Assumes we don't need a content length try { InputStream inp = null; byte[] buf = null; try{ inp = (InputStream) currentMessage ; ByteArrayOutputStream baos = new ByteArrayOutputStream(); buf = new byte[4096]; int len ; while ( (len = inp.read(buf,0,4096)) != -1 ) baos.write( buf, 0, len ); buf = baos.toByteArray(); }finally{ if(inp != null && currentMessage instanceof org.apache.axis.transport.http.SocketInputStream ) inp.close(); } setCurrentForm( buf, FORM_BYTES ); log.debug("Exit: SOAPPart::getAsBytes"); return (byte[])currentMessage; } catch( Exception e ) { log.error(Messages.getMessage("exception00"), e); } log.debug("Exit: SOAPPart::getAsBytes"); return null; } if ( currentForm == FORM_SOAPENVELOPE || currentForm == FORM_FAULT ){ currentEncoding = XMLUtils.getEncoding(msgObject, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream os = new BufferedOutputStream(baos); try { this.writeTo(os); os.flush(); } catch (Exception e) { throw AxisFault.makeFault(e); } setCurrentForm(baos.toByteArray(), FORM_BYTES); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsBytes(): " + currentMessage); } return (byte[]) currentMessage; } if ( currentForm == FORM_STRING ) { // If the current message was already converted from // a byte[] to String, return the byte[] representation // (this is done to avoid unnecessary conversions) if (currentMessage == currentMessageAsString && currentMessageAsBytes != null) { if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsBytes()"); } return currentMessageAsBytes; } // Save this message in case it is requested later in getAsString currentMessageAsString = (String) currentMessage; try{ currentEncoding = XMLUtils.getEncoding(msgObject, null); setCurrentForm( ((String)currentMessage).getBytes(currentEncoding), FORM_BYTES ); }catch(UnsupportedEncodingException ue){ setCurrentForm( ((String)currentMessage).getBytes(), FORM_BYTES ); } currentMessageAsBytes = (byte[]) currentMessage; log.debug("Exit: SOAPPart::getAsBytes"); return (byte[])currentMessage; } log.error(Messages.getMessage("cantConvert00", ""+currentForm)); log.debug("Exit: SOAPPart::getAsBytes"); return null; } public void saveChanges() throws AxisFault { log.debug("Enter: SOAPPart::saveChanges"); if ( currentForm == FORM_SOAPENVELOPE || currentForm == FORM_FAULT ){ currentEncoding = XMLUtils.getEncoding(msgObject, null); ByteArray array = new ByteArray(); try { writeTo(array); array.flush(); } catch (Exception e) { throw AxisFault.makeFault(e); } setCurrentForm( array, FORM_OPTIMIZED ); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::saveChanges(): " + currentMessage); } } } /** * Get the contents of this Part (not the headers!), as a String. * This will force buffering of the message. * * @return a <code>String</code> containing the content of this message * @throws AxisFault if there is an error serializing this part */ public String getAsString() throws AxisFault { log.debug("Enter: SOAPPart::getAsString"); if ( currentForm == FORM_STRING ) { if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessage); } return (String)currentMessage; } if ( currentForm == FORM_INPUTSTREAM || currentForm == FORM_BODYINSTREAM ) { getAsBytes(); // Fall thru to "Bytes" } if ( currentForm == FORM_OPTIMIZED) { try { currentMessageAsBytes = ((ByteArray) currentMessage).toByteArray(); } catch (IOException e) { throw AxisFault.makeFault(e); } try{ setCurrentForm(new String((byte[])currentMessageAsBytes, currentEncoding), FORM_STRING); }catch(UnsupportedEncodingException ue){ setCurrentForm( new String((byte[]) currentMessageAsBytes), FORM_STRING ); } if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessage); } return (String)currentMessage; } if ( currentForm == FORM_BYTES ) { // If the current message was already converted from // a String to byte[], return the String representation // (this is done to avoid unnecessary conversions) if (currentMessage == currentMessageAsBytes && currentMessageAsString != null) { if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessageAsString); } return currentMessageAsString; } // Save this message in case it is requested later in getAsBytes currentMessageAsBytes = (byte[]) currentMessage; try{ setCurrentForm(new String((byte[])currentMessage, currentEncoding), FORM_STRING); }catch(UnsupportedEncodingException ue){ setCurrentForm( new String((byte[]) currentMessage), FORM_STRING ); } currentMessageAsString = (String) currentMessage; if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessage); } return (String)currentMessage; } if ( currentForm == FORM_FAULT ) { StringWriter writer = new StringWriter(); try { this.writeTo(writer); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); return null; } setCurrentForm(writer.getBuffer().toString(), FORM_STRING); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessage); } return (String)currentMessage; } if ( currentForm == FORM_SOAPENVELOPE ) { StringWriter writer = new StringWriter(); try { this.writeTo(writer); } catch (Exception e) { throw AxisFault.makeFault(e); } setCurrentForm(writer.getBuffer().toString(), FORM_STRING); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsString(): " + currentMessage); } return (String)currentMessage; } log.error( Messages.getMessage("cantConvert01", ""+currentForm)); log.debug("Exit: SOAPPart::getAsString()"); return null; } /** * Get the contents of this Part (not the MIME headers!), as a * SOAPEnvelope. This will force a complete parse of the * message. * * @return a <code>SOAPEnvelope</code> containing the message content * @throws AxisFault if the envelope could not be constructed */ public SOAPEnvelope getAsSOAPEnvelope() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SOAPPart::getAsSOAPEnvelope()"); log.debug(Messages.getMessage("currForm", formNames[currentForm])); } if ( currentForm == FORM_SOAPENVELOPE ) return (SOAPEnvelope)currentMessage; if (currentForm == FORM_BODYINSTREAM) { InputStreamBody bodyEl = new InputStreamBody((InputStream)currentMessage); SOAPEnvelope env = new SOAPEnvelope(); env.setOwnerDocument(this); env.addBodyElement(bodyEl); setCurrentForm(env, FORM_SOAPENVELOPE); return env; } InputSource is; if ( currentForm == FORM_INPUTSTREAM ) { is = new InputSource( (InputStream) currentMessage ); String encoding = XMLUtils.getEncoding(msgObject, null, null); if (encoding != null) { currentEncoding = encoding; is.setEncoding(currentEncoding); } } else { is = new InputSource(new StringReader(getAsString())); } DeserializationContext dser = new DeserializationContext(is, getMessage().getMessageContext(), getMessage().getMessageType()); dser.getEnvelope().setOwnerDocument(this); // This may throw a SAXException try { dser.parse(); } catch (SAXException e) { Exception real = e.getException(); if (real == null) real = e; throw AxisFault.makeFault(real); } SOAPEnvelope nse= dser.getEnvelope(); if(currentMessageAsEnvelope != null){ //Need to synchronize back processed header info. Vector newHeaders= nse.getHeaders(); Vector oldHeaders= currentMessageAsEnvelope.getHeaders(); if( null != newHeaders && null != oldHeaders){ Iterator ohi= oldHeaders.iterator(); Iterator nhi= newHeaders.iterator(); while( ohi.hasNext() && nhi.hasNext()){ SOAPHeaderElement nhe= (SOAPHeaderElement)nhi.next(); SOAPHeaderElement ohe= (SOAPHeaderElement)ohi.next(); if(ohe.isProcessed()) nhe.setProcessed(true); } } } setCurrentForm(nse, FORM_SOAPENVELOPE); log.debug("Exit: SOAPPart::getAsSOAPEnvelope"); SOAPEnvelope env = (SOAPEnvelope)currentMessage; env.setOwnerDocument(this); return env; } /** * Add the specified MIME header, as per JAXM. * * @param header the header to add * @param value the value of that header */ public void addMimeHeader (String header, String value) { mimeHeaders.addHeader(header, value); } /** * Get the specified MIME header. * * @param header the name of a MIME header * @return the value of the first header named <code>header</code> */ private String getFirstMimeHeader (String header) { String[] values = mimeHeaders.getHeader(header); if(values != null && values.length>0) return values[0]; return null; } /** * Total size in bytes (of all content and headers, as encoded). public abstract int getSize(); */ /** * Content location. * * @return the content location */ public String getContentLocation() { return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION); } /** * Set content location. * * @param loc the content location */ public void setContentLocation(String loc) { setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, loc); } /** * Sets Content-Id of this part. * already defined. * @param newCid new Content-Id */ public void setContentId(String newCid){ setMimeHeader(HTTPConstants.HEADER_CONTENT_ID,newCid); } /** * Content ID. * * @return the content ID */ public String getContentId() { return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_ID); } /** * Content ID. * * @return the contentId reference value that should be used directly * as an href in a SOAP element to reference this attachment. * <B>Not part of JAX-RPC, JAX-M, SAAJ, etc. </B> */ public String getContentIdRef() { return org.apache.axis.attachments.Attachments.CIDprefix + getContentId(); } /** * Get all headers that match. * * @param match an array of <code>String</code>s giving mime header names * @return an <code>Iterator</code> over all values matching these headers */ public java.util.Iterator getMatchingMimeHeaders( final String[] match){ return mimeHeaders.getMatchingHeaders(match); } /** * Get all headers that do not match. * * @param match an array of <code>String</code>s giving mime header names * @return an <code>Iterator</code> over all values not matching these * headers */ public java.util.Iterator getNonMatchingMimeHeaders( final String[] match){ return mimeHeaders.getNonMatchingHeaders(match); } /** * Sets the content of the <CODE>SOAPEnvelope</CODE> object * with the data from the given <CODE>Source</CODE> object. * @param source <CODE>javax.xml.transform.Source</CODE> object with the data to * be set * @throws SOAPException if there is a problem in * setting the source * @see #getContent() getContent() */ public void setContent(Source source) throws SOAPException { if(source == null) throw new SOAPException(Messages.getMessage("illegalArgumentException00")); // override the checks in HandlerChainImpl for JAXRPCHandler kludge MessageContext ctx = getMessage().getMessageContext(); if (ctx != null) { ctx.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.TRUE); } contentSource = source; InputSource in = org.apache.axis.utils.XMLUtils.sourceToInputSource(contentSource); InputStream is = in.getByteStream(); if(is != null) { setCurrentMessage(is, FORM_INPUTSTREAM); } else { Reader r = in.getCharacterStream(); if(r == null) { throw new SOAPException(Messages.getMessage("noCharacterOrByteStream")); } BufferedReader br = new BufferedReader(r); String line = null; StringBuffer sb = new StringBuffer(); try { while((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new SOAPException(Messages.getMessage("couldNotReadFromCharStream"), e); } setCurrentMessage(sb.toString(), FORM_STRING); } } /** * Returns the content of the SOAPEnvelope as a JAXP <CODE> * Source</CODE> object. * @return the content as a <CODE> * javax.xml.transform.Source</CODE> object * @throws SOAPException if the implementation cannot * convert the specified <CODE>Source</CODE> object * @see #setContent(javax.xml.transform.Source) setContent(javax.xml.transform.Source) */ public Source getContent() throws SOAPException { if(contentSource == null) { switch(currentForm) { case FORM_STRING: String s = (String) currentMessage; contentSource = new StreamSource(new StringReader(s)); break; case FORM_INPUTSTREAM: contentSource = new StreamSource((InputStream) currentMessage); break; case FORM_SOAPENVELOPE: SOAPEnvelope se = (SOAPEnvelope) currentMessage; try { contentSource = new DOMSource(se.getAsDocument()); } catch (Exception e) { throw new SOAPException(Messages.getMessage("errorGetDocFromSOAPEnvelope"), e); } break; case FORM_OPTIMIZED: try { ByteArrayInputStream baos = new ByteArrayInputStream(((ByteArray) currentMessage).toByteArray()); contentSource = new StreamSource(baos); } catch (IOException e) { throw new SOAPException(Messages.getMessage("errorGetDocFromSOAPEnvelope"), e); } break; case FORM_BYTES: byte[] bytes = (byte[]) currentMessage; contentSource = new StreamSource(new ByteArrayInputStream(bytes)); break; case FORM_BODYINSTREAM: contentSource = new StreamSource((InputStream) currentMessage); break; } } return contentSource; } /** * Retrieves all the headers for this <CODE>SOAPPart</CODE> * object as an iterator over the <CODE>MimeHeader</CODE> * objects. * @return an <CODE>Iterator</CODE> object with all of the Mime * headers for this <CODE>SOAPPart</CODE> object */ public Iterator getAllMimeHeaders() { return mimeHeaders.getAllHeaders(); } /** * Changes the first header entry that matches the given * header name so that its value is the given value, adding a * new header with the given name and value if no existing * header is a match. If there is a match, this method clears * all existing values for the first header that matches and * sets the given value instead. If more than one header has * the given name, this method removes all of the matching * headers after the first one. * * <P>Note that RFC822 headers can contain only US-ASCII * characters.</P> * @param name a <CODE>String</CODE> giving the * header name for which to search * @param value a <CODE>String</CODE> giving the * value to be set. This value will be substituted for the * current value(s) of the first header that is a match if * there is one. If there is no match, this value will be * the value for a new <CODE>MimeHeader</CODE> object. * @throws java.lang.IllegalArgumentException if * there was a problem with the specified mime header name * or value * @see #getMimeHeader(java.lang.String) getMimeHeader(java.lang.String) */ public void setMimeHeader(String name, String value) { mimeHeaders.setHeader(name,value); } /** * Gets all the values of the <CODE>MimeHeader</CODE> object * in this <CODE>SOAPPart</CODE> object that is identified by * the given <CODE>String</CODE>. * @param name the name of the header; example: * "Content-Type" * @return a <CODE>String</CODE> array giving all the values for * the specified header * @see #setMimeHeader(java.lang.String, java.lang.String) setMimeHeader(java.lang.String, java.lang.String) */ public String[] getMimeHeader(String name) { return mimeHeaders.getHeader(name); } /** * Removes all the <CODE>MimeHeader</CODE> objects for this * <CODE>SOAPEnvelope</CODE> object. */ public void removeAllMimeHeaders() { mimeHeaders.removeAllHeaders(); } /** * Removes all MIME headers that match the given name. * @param header a <CODE>String</CODE> giving * the name of the MIME header(s) to be removed */ public void removeMimeHeader(String header) { mimeHeaders.removeHeader(header); } /** * Gets the <CODE>SOAPEnvelope</CODE> object associated with * this <CODE>SOAPPart</CODE> object. Once the SOAP envelope is * obtained, it can be used to get its contents. * @return the <CODE>SOAPEnvelope</CODE> object for this <CODE> * SOAPPart</CODE> object * @throws SOAPException if there is a SOAP error */ public javax.xml.soap.SOAPEnvelope getEnvelope() throws SOAPException { try { return getAsSOAPEnvelope(); } catch (AxisFault af) { throw new SOAPException(af); } } /** * Implementation of org.w3c.Document * Most of methods will be implemented using the delgate * instance of SOAPDocumentImpl * This is for two reasons: * - possible change of message classes, by extenstion of xerces implementation * - we cannot extends SOAPPart (multiple inheritance), * since it is defined as Abstract class * *********************************************************** */ private Document document = new SOAPDocumentImpl(this); /** * @since SAAJ 1.2 */ public Document getSOAPDocument(){ if(document == null){ document = new SOAPDocumentImpl(this); } return document; } /** * @return */ public DocumentType getDoctype(){ return document.getDoctype(); } /** * @return */ public DOMImplementation getImplementation(){ return document.getImplementation(); } /** * SOAPEnvelope is the Document Elements of this XML docuement */ protected Document mDocument; public Element getDocumentElement() { try{ return getEnvelope(); }catch(SOAPException se){ return null; } } /** * * @param tagName * @return * @throws DOMException */ public Element createElement(String tagName) throws DOMException { return document.createElement(tagName); } public DocumentFragment createDocumentFragment() { return document.createDocumentFragment(); } public Text createTextNode(String data) { return document.createTextNode(data); } public Comment createComment(String data){ return document.createComment(data); } public CDATASection createCDATASection(String data) throws DOMException { return document.createCDATASection(data); } public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException { return document.createProcessingInstruction(target,data); } public Attr createAttribute(String name)throws DOMException { return document.createAttribute(name); } public EntityReference createEntityReference(String name) throws DOMException { return document.createEntityReference(name); } public NodeList getElementsByTagName(String tagname) { return document.getElementsByTagName(tagname); } public Node importNode(Node importedNode, boolean deep) throws DOMException { return document.importNode(importedNode, deep); } public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { return document.createElementNS(namespaceURI, qualifiedName); } public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { return document.createAttributeNS(namespaceURI, qualifiedName); } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { return document.getElementsByTagNameNS(namespaceURI,localName); } public Element getElementById(String elementId){ return document.getElementById(elementId); } ///////////////////////////////////////////////////////////// public String getEncoding() { return currentEncoding; } public void setEncoding(String s) { currentEncoding = s; } public boolean getStandalone() { throw new UnsupportedOperationException("Not yet implemented.71"); } public void setStandalone(boolean flag) { throw new UnsupportedOperationException("Not yet implemented.72"); } public boolean getStrictErrorChecking() { throw new UnsupportedOperationException("Not yet implemented.73"); } public void setStrictErrorChecking(boolean flag) { throw new UnsupportedOperationException("Not yet implemented. 74"); } public String getVersion() { throw new UnsupportedOperationException("Not yet implemented. 75"); } public void setVersion(String s) { throw new UnsupportedOperationException("Not yet implemented.76"); } public Node adoptNode(Node node) throws DOMException { throw new UnsupportedOperationException("Not yet implemented.77"); } /** * Node Implementation */ public String getNodeName(){ return document.getNodeName(); } public String getNodeValue() throws DOMException { return document.getNodeValue(); } public void setNodeValue(String nodeValue) throws DOMException{ document.setNodeValue(nodeValue); } public short getNodeType() { return document.getNodeType(); } public Node getParentNode(){ return document.getParentNode(); } public NodeList getChildNodes() { return document.getChildNodes(); } public Node getFirstChild() { return document.getFirstChild(); } public Node getLastChild(){ return document.getLastChild(); } public Node getPreviousSibling(){ return document.getPreviousSibling(); } public Node getNextSibling(){ return document.getNextSibling(); } public NamedNodeMap getAttributes(){ return document.getAttributes(); } public Document getOwnerDocument(){ return document.getOwnerDocument(); } public Node insertBefore(Node newChild, Node refChild) throws DOMException { return document.insertBefore(newChild, refChild); } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { return document.replaceChild(newChild, oldChild); } public Node removeChild(Node oldChild) throws DOMException { return document.removeChild(oldChild); } public Node appendChild(Node newChild) throws DOMException { return document.appendChild(newChild); } public boolean hasChildNodes(){ return document.hasChildNodes(); } public Node cloneNode(boolean deep) { return document.cloneNode(deep); } public void normalize(){ document.normalize(); } public boolean isSupported(String feature, String version){ return document.isSupported(feature, version); } public String getNamespaceURI() { return document.getNamespaceURI(); } public String getPrefix() { return document.getPrefix(); } public void setPrefix(String prefix) throws DOMException { document.setPrefix(prefix); } public String getLocalName() { return document.getLocalName(); } public boolean hasAttributes(){ return document.hasAttributes(); } public boolean isBodyStream() { return (currentForm == SOAPPart.FORM_INPUTSTREAM || currentForm == SOAPPart.FORM_BODYINSTREAM); } }
7,327
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/AxisServiceConfigImpl.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; /** * A simple implementation of AxisServiceConfig. * * @author Glen Daniels (gdaniels@apache.org) */ public class AxisServiceConfigImpl implements AxisServiceConfig { // fixme: do we realy want these all held in a single string? should we be // splitting this here, or in code that uses the config? private String methods; /** * Set the allowed method names. * * @param methods a <code>String</code> containing a list of all allowed * methods */ public void setAllowedMethods(String methods) { this.methods = methods; } /** Get the allowed method names. * * @return a space-delimited list of method names which may be called * via SOAP. */ public String getAllowedMethods() { return methods; } }
7,328
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/HandlerIterationStrategy.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; /** * Base interface for doing an action to Handlers with a MessageContext. * * @author Glen Daniels (gdaniels@apache.org) */ public interface HandlerIterationStrategy { /** * Visit a handler with a message context. * * @param handler the <code>Handler</code> to apply to the context * @param msgContext the <code>MessageContext</code> used * @throws AxisFault if this visit encountered an error */ public void visit(Handler handler, MessageContext msgContext) throws AxisFault; }
7,329
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Version.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; import org.apache.axis.client.Call; import org.apache.axis.utils.Messages; /** * Little utility to get the version and build date of the axis.jar. * * The messages referenced here are automatically kept up-to-date by the * build.xml. * * @author Glen Daniels (gdaniels@apache.org) */ public class Version { /** * Get the version of this AXIS. * * @return the version of this axis */ public static String getVersion() { return Messages.getMessage("axisVersion") + "\n" + Messages.getMessage("builtOn"); } /** * Returns the Axis Version number and build date. * <p> * Example output: 1.1 Jul 08, 2003 (09:00:12 EDT) * * @return the full version of this axis **/ public static String getVersionText() { return Messages.getMessage("axisVersionRaw") + " " + Messages.getMessage("axisBuiltOnRaw"); } /** * Entry point. * <p> * Calling this with no arguments returns the version of the client-side * axis.jar. Passing a URL which points to a remote Axis server will * attempt to retrieve the version of the server via a SOAP call. */ public static void main(String[] args) { if (args.length != 1) System.out.println(getVersion()); else try { Call call = new Call(args[0]); String result = (String)call.invoke("Version", "getVersion", null); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } }
7,330
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/AxisProperties.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; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.discovery.ResourceClassIterator; import org.apache.commons.discovery.ResourceNameDiscover; import org.apache.commons.discovery.ResourceNameIterator; import org.apache.commons.discovery.resource.ClassLoaders; import org.apache.commons.discovery.resource.classes.DiscoverClasses; import org.apache.commons.discovery.resource.names.DiscoverMappedNames; import org.apache.commons.discovery.resource.names.DiscoverNamesInAlternateManagedProperties; import org.apache.commons.discovery.resource.names.DiscoverNamesInManagedProperties; import org.apache.commons.discovery.resource.names.DiscoverServiceNames; import org.apache.commons.discovery.resource.names.NameDiscoverers; import org.apache.commons.discovery.tools.ClassUtils; import org.apache.commons.discovery.tools.DefaultClassHolder; import org.apache.commons.discovery.tools.DiscoverClass; import org.apache.commons.discovery.tools.ManagedProperties; import org.apache.commons.discovery.tools.PropertiesHolder; import org.apache.commons.discovery.tools.SPInterface; import org.apache.commons.logging.Log; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.Map; import java.util.Properties; /** * Configuration properties for AXIS. * * <p>Manage configuration properties according to a secure * scheme similar to that used by classloaders: * <ul> * <li><code>ClassLoader</code>s are organized in a tree hierarchy.</li> * <li>each <code>ClassLoader</code> has a reference * to a parent <code>ClassLoader</code>.</li> * <li>the root of the tree is the bootstrap <code>ClassLoader</code>er.</li> * <li>the youngest decendent is the thread context class loader.</li> * <li>properties are bound to a <code>ClassLoader</code> instance * <ul> * <li><i>non-default</i> properties bound to a parent <code>ClassLoader</code> * instance take precedence over all properties of the same name bound * to any decendent. * Just to confuse the issue, this is the default case.</li> * <li><i>default</i> properties bound to a parent <code>ClassLoader</code> * instance may be overriden by (default or non-default) properties of * the same name bound to any decendent. * </li> * </ul> * </li> * <li>System properties take precedence over all other properties</li> * </ul> * * @author Richard A. Sitze */ public class AxisProperties { /** The <code>Log</code> for all interesting events in this class. */ protected static Log log = LogFactory.getLog(AxisProperties.class.getName()); private static DiscoverNamesInAlternateManagedProperties altNameDiscoverer; private static DiscoverMappedNames mappedNames; private static NameDiscoverers nameDiscoverer; private static ClassLoaders loaders; public static void setClassOverrideProperty(Class clazz, String propertyName) { getAlternatePropertyNameDiscoverer() .addClassToPropertyNameMapping(clazz.getName(), propertyName); } public static void setClassDefault(Class clazz, String defaultName) { getMappedNames().map(clazz.getName(), defaultName); } public static void setClassDefaults(Class clazz, String[] defaultNames) { getMappedNames().map(clazz.getName(), defaultNames); } public static synchronized ResourceNameDiscover getNameDiscoverer() { if (nameDiscoverer == null) { nameDiscoverer = new NameDiscoverers(); nameDiscoverer.addResourceNameDiscover(getAlternatePropertyNameDiscoverer()); nameDiscoverer.addResourceNameDiscover(new DiscoverNamesInManagedProperties()); nameDiscoverer.addResourceNameDiscover(new DiscoverServiceNames(getClassLoaders())); nameDiscoverer.addResourceNameDiscover(getMappedNames()); } return nameDiscoverer; } public static ResourceClassIterator getResourceClassIterator(Class spi) { ResourceNameIterator it = getNameDiscoverer().findResourceNames(spi.getName()); return new DiscoverClasses(loaders).findResourceClasses(it); } private static synchronized ClassLoaders getClassLoaders() { if (loaders == null) { loaders = ClassLoaders.getAppLoaders(AxisProperties.class, null, true); } return loaders; } private static synchronized DiscoverMappedNames getMappedNames() { if (mappedNames == null) { mappedNames = new DiscoverMappedNames(); } return mappedNames; } private static synchronized DiscoverNamesInAlternateManagedProperties getAlternatePropertyNameDiscoverer() { if (altNameDiscoverer == null) { altNameDiscoverer = new DiscoverNamesInAlternateManagedProperties(); } return altNameDiscoverer; } /** * Create a new instance of a service provider class. * * !WARNING! * SECURITY issue. * * See bug 11874 * * The solution to both is to move doPrivilege UP within AXIS to a * class that is either private (cannot be reached by code outside * AXIS) or that represents a secure public interface... * * This is going to require analysis and (probably) rearchitecting. * So, I'm taking taking the easy way out until we are at a point * where we can reasonably rearchitect for security. * * @param spiClass the service provider class to instantiate * @return a new instance of this class */ public static Object newInstance(Class spiClass) { return newInstance(spiClass, null, null); } public static Object newInstance(final Class spiClass, final Class constructorParamTypes[], final Object constructorParams[]) { return AccessController.doPrivileged( new PrivilegedAction() { public Object run() { ResourceClassIterator services = getResourceClassIterator(spiClass); Object obj = null; while (obj == null && services.hasNext()) { Class service = services.nextResourceClass().loadClass(); /* service == null * if class resource wasn't loadable */ if (service != null) { /* OK, class loaded.. attempt to instantiate it. */ try { ClassUtils.verifyAncestory(spiClass, service); obj = ClassUtils.newInstance(service, constructorParamTypes, constructorParams); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof java.lang.NoClassDefFoundError) { log.debug(Messages.getMessage("exception00"), e); } else { log.warn(Messages.getMessage("exception00"), e); } } catch (Exception e) { log.warn(Messages.getMessage("exception00"), e); } } } return obj; } }); } /** * Get value for property bound to the current thread context class loader. * * @param propertyName property name. * @return property value if found, otherwise default. */ public static String getProperty(String propertyName) { return ManagedProperties.getProperty(propertyName); } /** * Get value for property bound to the current thread context class loader. * If not found, then return default. * * @param propertyName property name. * @param dephault default value. * @return property value if found, otherwise default. */ public static String getProperty(String propertyName, String dephault) { return ManagedProperties.getProperty(propertyName, dephault); } /** * Set value for property bound to the current thread context class loader. * @param propertyName property name * @param value property value (non-default) If null, remove the property. */ public static void setProperty(String propertyName, String value) { ManagedProperties.setProperty(propertyName, value); } /** * Set value for property bound to the current thread context class loader. * @param propertyName property name * @param value property value. If null, remove the property. * @param isDefault determines if property is default or not. * A non-default property cannot be overriden. * A default property can be overriden by a property * (default or non-default) of the same name bound to * a decendent class loader. */ public static void setProperty(String propertyName, String value, boolean isDefault) { ManagedProperties.setProperty(propertyName, value, isDefault); } /** * Set property values for <code>Properties</code> bound to the * current thread context class loader. * * @param newProperties name/value pairs to be bound */ public static void setProperties(Map newProperties) { ManagedProperties.setProperties(newProperties); } /** * Set property values for <code>Properties</code> bound to the * current thread context class loader. * * @param newProperties name/value pairs to be bound * @param isDefault determines if properties are default or not. * A non-default property cannot be overriden. * A default property can be overriden by a property * (default or non-default) of the same name bound to * a decendent class loader. */ public static void setProperties(Map newProperties, boolean isDefault) { ManagedProperties.setProperties(newProperties, isDefault); } public static Enumeration propertyNames() { return ManagedProperties.propertyNames(); } /** * This is an expensive operation. * * @return Returns a <code>java.util.Properties</code> instance * that is equivalent to the current state of the scoped * properties, in that getProperty() will return the same value. * However, this is a copy, so setProperty on the * returned value will not effect the scoped properties. */ public static Properties getProperties() { return ManagedProperties.getProperties(); } public static Object newInstance(Class spiClass, Class defaultClass) { return newInstance(new SPInterface(spiClass), new DefaultClassHolder(defaultClass)); } /** * !WARNING! * SECURITY issue. * * See bug 11874 * * The solution to both is to move doPrivilege UP within AXIS to a * class that is either private (cannot be reached by code outside * AXIS) or that represents a secure public interface... * * This is going to require analysis and (probably) rearchitecting. * So, I'm taking taking the easy way out until we are at a point * where we can reasonably rearchitect for security. */ private static Object newInstance(final SPInterface spi, final DefaultClassHolder defaultClass) { return AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { return DiscoverClass.newInstance(null, spi, (PropertiesHolder)null, defaultClass); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } return null; } }); } }
7,331
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/Constants.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; import org.apache.axis.schema.SchemaVersion1999; import org.apache.axis.schema.SchemaVersion2000; import org.apache.axis.schema.SchemaVersion2001; import org.apache.axis.soap.SOAPConstants; import org.xml.sax.Attributes; import javax.xml.namespace.QName; public class Constants { // Some common Constants that should be used in local handler options // (Not all implementations will have these concepts - for example // not all Engines will have notion of registries but defining these // here should allow people to ask if they exist) ////////////////////////////////////////////////////////////////////////// // Namespace Prefix Constants ////////////////////////////////////////////////////////////////////////// public static final String NS_PREFIX_SOAP_ENV = "soapenv"; public static final String NS_PREFIX_SOAP_ENC = "soapenc"; public static final String NS_PREFIX_SCHEMA_XSI = "xsi" ; public static final String NS_PREFIX_SCHEMA_XSD = "xsd" ; public static final String NS_PREFIX_WSDL = "wsdl" ; public static final String NS_PREFIX_WSDL_SOAP = "wsdlsoap"; public static final String NS_PREFIX_XMLSOAP = "apachesoap"; public static final String NS_PREFIX_XML = "xml"; public static final String NS_PREFIX_XOP = "xop"; // Axis Namespaces public static final String NS_URI_AXIS = "http://xml.apache.org/axis/"; public static final String NS_URI_XMLSOAP = "http://xml.apache.org/xml-soap"; // Special namespace URI to indicate an "automatically" serialized Java // type. This allows us to use types without needing explicit mappings, // such that Java classes like "org.foo.Bar" map to QNames like // {http://xml.apache.org/axis/java}org.foo.Bar public static final String NS_URI_JAVA = "http://xml.apache.org/axis/java"; // // Default SOAP version // public static final SOAPConstants DEFAULT_SOAP_VERSION = SOAPConstants.SOAP11_CONSTANTS; // // SOAP-ENV Namespaces // public static final String URI_SOAP11_ENV = "http://schemas.xmlsoap.org/soap/envelope/" ; public static final String URI_SOAP12_ENV = "http://www.w3.org/2003/05/soap-envelope"; public static final String URI_DEFAULT_SOAP_ENV = DEFAULT_SOAP_VERSION.getEnvelopeURI(); // fixme: this is unsafe - a client can (accidentaly or on purpose) // over-write the elemnts of this array. This pattern is used throughout // this file. public static final String[] URIS_SOAP_ENV = { URI_SOAP11_ENV, URI_SOAP12_ENV, }; // Constant name of the enterprise-style logging category. // The enterprise category is for stuff that an enterprise product might // want to track, but in a simple environment (like the AXIS build) would // be nothing more than a nuisance. public static final String ENTERPRISE_LOG_CATEGORY = "org.apache.axis.enterprise"; /** * time logged stuff. */ public static final String TIME_LOG_CATEGORY = "org.apache.axis.TIME"; /** * Servlet exceptions. Axis faults are logged at debug level here. */ public static final String EXCEPTION_LOG_CATEGORY = "org.apache.axis.EXCEPTIONS"; /** The name of the field which accepts xsd:any content in Beans. */ public static final String ANYCONTENT = "_any"; /** * The size of the buffer size for. */ public static final int HTTP_TXR_BUFFER_SIZE = 8 * 1024; /** Basic Profile 1.1 compatibility flag */ public static final String WSIBP11_COMPAT_PROPERTY = "axis.ws-i.bp11.compatibility"; /** * Returns true if the string is the SOAP_ENV Namespace. * * @param s the string representation of a URI * @return <code>true</code> if s represents any of the supported soap * envelope URI strings */ public static boolean isSOAP_ENV(String s) { for (int i=0; i<URIS_SOAP_ENV.length; i++) { if (URIS_SOAP_ENV[i].equals(s)) { return true; } } return false; } public static final String URI_LITERAL_ENC = ""; // // SOAP-ENC Namespaces // public static final String URI_SOAP11_ENC = "http://schemas.xmlsoap.org/soap/encoding/" ; public static final String URI_SOAP12_ENC = "http://www.w3.org/2003/05/soap-encoding"; public static final String URI_SOAP12_NOENC = "http://www.w3.org/2003/05/soap-envelope/encoding/none"; public static final String URI_DEFAULT_SOAP_ENC = DEFAULT_SOAP_VERSION.getEncodingURI(); public static final String[] URIS_SOAP_ENC = { URI_SOAP12_ENC, URI_SOAP11_ENC, }; /** * Returns true if SOAP_ENC Namespace. * * @param s a string representing the URI to check * @return true if <code>s</code> matches a SOAP ENCODING namespace URI, * false otherwise */ public static boolean isSOAP_ENC(String s) { for (int i=0; i<URIS_SOAP_ENC.length; i++) { if (URIS_SOAP_ENC[i].equals(s)) { return true; } } return false; } /** * This utility routine returns the value of an attribute which might * be in one of several namespaces. * * @param attributes the attributes to search * @param search an array of namespace URI strings to search * @param localPart is the local part of the attribute name * @return the value of the attribute or null */ public static String getValue(Attributes attributes, String [] search, String localPart) { if (attributes == null || search == null || localPart == null) { return null; } int len = attributes.getLength(); if (len == 0) { return null; } for (int i=0; i < len; i++) { if (attributes.getLocalName(i).equals(localPart)) { String uri = attributes.getURI(i); for (int j=0; j<search.length; j++) { if (search[j].equals(uri)) return attributes.getValue(i); } } } return null; } /** * Search an attribute collection for a list of QNames, returning * the value of the first one found, or null if none were found. * * @param attributes * @param search * @return the value of the attribute */ public static String getValue(Attributes attributes, QName [] search) { if (attributes == null || search == null) return null; if (attributes.getLength() == 0) return null; String value = null; for (int i=0; (value == null) && (i < search.length); i++) { value = attributes.getValue(search[i].getNamespaceURI(), search[i].getLocalPart()); } return value; } /** * equals * The first QName is the current version of the name. The second qname is compared * with the first considering all namespace uri versions. * @param first Currently supported QName * @param second any qname * @return true if the qnames represent the same qname (paster namespace uri versions considered */ public static boolean equals(QName first, QName second) { if (first == second) { return true; } if (first==null || second==null) { return false; } if (first.equals(second)) { return true; } if (!first.getLocalPart().equals(second.getLocalPart())) { return false; } String namespaceURI = first.getNamespaceURI(); String[] search = null; if (namespaceURI.equals(URI_DEFAULT_SOAP_ENC)) search = URIS_SOAP_ENC; else if (namespaceURI.equals(URI_DEFAULT_SOAP_ENV)) search = URIS_SOAP_ENV; else if (namespaceURI.equals(URI_DEFAULT_SCHEMA_XSD)) search = URIS_SCHEMA_XSD; else if (namespaceURI.equals(URI_DEFAULT_SCHEMA_XSI)) search = URIS_SCHEMA_XSI; else search = new String[] {namespaceURI}; for (int i=0; i < search.length; i++) { if (search[i].equals(second.getNamespaceURI())) { return true; } } return false; } // Misc SOAP Namespaces / URIs public static final String URI_SOAP11_NEXT_ACTOR = "http://schemas.xmlsoap.org/soap/actor/next" ; public static final String URI_SOAP12_NEXT_ROLE = "http://www.w3.org/2003/05/soap-envelope/role/next"; /** @deprecated use URI_SOAP12_NEXT_ROLE */ public static final String URI_SOAP12_NEXT_ACTOR = URI_SOAP12_NEXT_ROLE; public static final String URI_SOAP12_RPC = "http://www.w3.org/2003/05/soap-rpc"; public static final String URI_SOAP12_NONE_ROLE = "http://www.w3.org/2003/05/soap-envelope/role/none"; public static final String URI_SOAP12_ULTIMATE_ROLE = "http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver"; public static final String URI_SOAP11_HTTP = "http://schemas.xmlsoap.org/soap/http"; public static final String URI_SOAP12_HTTP = "http://www.w3.org/2003/05/http"; public static final String NS_URI_XMLNS = "http://www.w3.org/2000/xmlns/"; public static final String NS_URI_XML = "http://www.w3.org/XML/1998/namespace"; // // Schema XSD Namespaces // public static final String URI_1999_SCHEMA_XSD = "http://www.w3.org/1999/XMLSchema"; public static final String URI_2000_SCHEMA_XSD = "http://www.w3.org/2000/10/XMLSchema"; public static final String URI_2001_SCHEMA_XSD = "http://www.w3.org/2001/XMLSchema"; public static final String URI_DEFAULT_SCHEMA_XSD = URI_2001_SCHEMA_XSD; public static final String[] URIS_SCHEMA_XSD = { URI_1999_SCHEMA_XSD, URI_2000_SCHEMA_XSD, URI_2001_SCHEMA_XSD }; public static final QName [] QNAMES_NIL = { SchemaVersion2001.QNAME_NIL, SchemaVersion2000.QNAME_NIL, SchemaVersion1999.QNAME_NIL }; /** * Returns true if SchemaXSD Namespace. * * @param s the string representing the URI to check * @return true if s represents the Schema XSD namespace, false otherwise */ public static boolean isSchemaXSD(String s) { for (int i=0; i<URIS_SCHEMA_XSD.length; i++) { if (URIS_SCHEMA_XSD[i].equals(s)) { return true; } } return false; } // // Schema XSI Namespaces // public static final String URI_1999_SCHEMA_XSI = "http://www.w3.org/1999/XMLSchema-instance"; public static final String URI_2000_SCHEMA_XSI = "http://www.w3.org/2000/10/XMLSchema-instance"; public static final String URI_2001_SCHEMA_XSI = "http://www.w3.org/2001/XMLSchema-instance"; public static final String URI_DEFAULT_SCHEMA_XSI = URI_2001_SCHEMA_XSI; public static final String[] URIS_SCHEMA_XSI = { URI_1999_SCHEMA_XSI, URI_2000_SCHEMA_XSI, URI_2001_SCHEMA_XSI, }; /** * Returns true if SchemaXSI Namespace. * * @param s the string of the URI to check * @return true if <code>s</code> is a Schema XSI URI, false otherwise */ public static boolean isSchemaXSI(String s) { for (int i=0; i<URIS_SCHEMA_XSI.length; i++) { if (URIS_SCHEMA_XSI[i].equals(s)) { return true; } } return false; } /** * WSDL Namespace. */ public static final String NS_URI_WSDL11 = "http://schemas.xmlsoap.org/wsdl/"; public static final String[] NS_URIS_WSDL = { NS_URI_WSDL11, }; /** * Returns true if this is a WSDL Namespace. * * @param s a string of a URI to check * @return true if <code>s</code> is a WSDL namespace URI, false otherwise */ public static boolean isWSDL(String s) { for (int i=0; i<NS_URIS_WSDL.length; i++) { if (NS_URIS_WSDL[i].equals(s)) { return true; } } return false; } // // WSDL extensions for SOAP in DIME // (http://gotdotnet.com/team/xml_wsspecs/dime/WSDL-Extension-for-DIME.htm) // public static final String URI_DIME_WSDL = "http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"; public static final String URI_DIME_CONTENT = "http://schemas.xmlsoap.org/ws/2002/04/content-type/"; public static final String URI_DIME_REFERENCE= "http://schemas.xmlsoap.org/ws/2002/04/reference/"; public static final String URI_DIME_CLOSED_LAYOUT= "http://schemas.xmlsoap.org/ws/2002/04/dime/closed-layout"; public static final String URI_DIME_OPEN_LAYOUT= "http://schemas.xmlsoap.org/ws/2002/04/dime/open-layout"; // XOP/MTOM public static final String URI_XOP_INCLUDE = "http://www.w3.org/2004/08/xop/include"; public static final String ELEM_XOP_INCLUDE = "Include" ; // // WSDL SOAP Namespace // public static final String URI_WSDL11_SOAP = "http://schemas.xmlsoap.org/wsdl/soap/"; public static final String URI_WSDL12_SOAP = "http://schemas.xmlsoap.org/wsdl/soap12/"; public static final String[] NS_URIS_WSDL_SOAP = { URI_WSDL11_SOAP, URI_WSDL12_SOAP }; /** * Returns true if s is a WSDL SOAP Namespace. * * @param s a string of a URI to check * @return true if <code>s</code> matches any of the WSDL SOAP namepace * URIs, false otherwise */ public static boolean isWSDLSOAP(String s) { for (int i=0; i<NS_URIS_WSDL_SOAP.length; i++) { if (NS_URIS_WSDL_SOAP[i].equals(s)) { return true; } } return false; } // Axis Mechanism Type public static final String AXIS_SAX = "Axis SAX Mechanism"; public static final String ELEM_ENVELOPE = "Envelope" ; public static final String ELEM_HEADER = "Header" ; public static final String ELEM_BODY = "Body" ; public static final String ELEM_FAULT = "Fault" ; public static final String ELEM_NOTUNDERSTOOD = "NotUnderstood"; public static final String ELEM_UPGRADE = "Upgrade"; public static final String ELEM_SUPPORTEDENVELOPE = "SupportedEnvelope"; public static final String ELEM_FAULT_CODE = "faultcode" ; public static final String ELEM_FAULT_STRING = "faultstring" ; public static final String ELEM_FAULT_DETAIL = "detail" ; public static final String ELEM_FAULT_ACTOR = "faultactor" ; public static final String ELEM_FAULT_CODE_SOAP12 = "Code" ; public static final String ELEM_FAULT_VALUE_SOAP12 = "Value" ; public static final String ELEM_FAULT_SUBCODE_SOAP12 = "Subcode" ; public static final String ELEM_FAULT_REASON_SOAP12 = "Reason" ; public static final String ELEM_FAULT_NODE_SOAP12 = "Node" ; public static final String ELEM_FAULT_ROLE_SOAP12 = "Role" ; public static final String ELEM_FAULT_DETAIL_SOAP12 = "Detail" ; public static final String ELEM_TEXT_SOAP12 = "Text" ; public static final String ATTR_MUST_UNDERSTAND = "mustUnderstand" ; public static final String ATTR_ENCODING_STYLE = "encodingStyle" ; public static final String ATTR_ACTOR = "actor" ; public static final String ATTR_ROLE = "role" ; public static final String ATTR_RELAY = "relay" ; public static final String ATTR_ROOT = "root" ; public static final String ATTR_ID = "id" ; public static final String ATTR_HREF = "href" ; public static final String ATTR_REF = "ref" ; public static final String ATTR_QNAME = "qname"; public static final String ATTR_ARRAY_TYPE = "arrayType"; public static final String ATTR_ITEM_TYPE = "itemType"; public static final String ATTR_ARRAY_SIZE = "arraySize"; public static final String ATTR_OFFSET = "offset"; public static final String ATTR_POSITION = "position"; public static final String ATTR_TYPE = "type"; public static final String ATTR_HANDLERINFOCHAIN = "handlerInfoChain"; // Fault Codes ////////////////////////////////////////////////////////////////////////// public static final String FAULT_CLIENT = "Client"; public static final String FAULT_SERVER_GENERAL = "Server.generalException"; public static final String FAULT_SERVER_USER = "Server.userException"; public static final QName FAULT_VERSIONMISMATCH = new QName(URI_SOAP11_ENV, "VersionMismatch"); public static final QName FAULT_MUSTUNDERSTAND = new QName(URI_SOAP11_ENV, "MustUnderstand"); public static final QName FAULT_SOAP12_MUSTUNDERSTAND = new QName(URI_SOAP12_ENV, "MustUnderstand"); public static final QName FAULT_SOAP12_VERSIONMISMATCH = new QName(URI_SOAP12_ENV, "VersionMismatch"); public static final QName FAULT_SOAP12_DATAENCODINGUNKNOWN = new QName(URI_SOAP12_ENV, "DataEncodingUnknown"); public static final QName FAULT_SOAP12_SENDER = new QName(URI_SOAP12_ENV, "Sender"); public static final QName FAULT_SOAP12_RECEIVER = new QName(URI_SOAP12_ENV, "Receiver"); // SOAP 1.2 Fault subcodes public static final QName FAULT_SUBCODE_BADARGS = new QName(URI_SOAP12_RPC, "BadArguments"); public static final QName FAULT_SUBCODE_PROC_NOT_PRESENT = new QName(URI_SOAP12_RPC, "ProcedureNotPresent"); // QNames ////////////////////////////////////////////////////////////////////////// public static final QName QNAME_FAULTCODE = new QName("", ELEM_FAULT_CODE); public static final QName QNAME_FAULTSTRING = new QName("", ELEM_FAULT_STRING); public static final QName QNAME_FAULTACTOR = new QName("", ELEM_FAULT_ACTOR); public static final QName QNAME_FAULTDETAILS = new QName("", ELEM_FAULT_DETAIL); public static final QName QNAME_FAULTCODE_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_CODE_SOAP12); public static final QName QNAME_FAULTVALUE_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_VALUE_SOAP12); public static final QName QNAME_FAULTSUBCODE_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_SUBCODE_SOAP12); public static final QName QNAME_FAULTREASON_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_REASON_SOAP12); public static final QName QNAME_TEXT_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_TEXT_SOAP12); public static final QName QNAME_FAULTNODE_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_NODE_SOAP12); public static final QName QNAME_FAULTROLE_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_ROLE_SOAP12); public static final QName QNAME_FAULTDETAIL_SOAP12 = new QName(URI_SOAP12_ENV, ELEM_FAULT_DETAIL_SOAP12); public static final QName QNAME_NOTUNDERSTOOD = new QName(URI_SOAP12_ENV, ELEM_NOTUNDERSTOOD); // Define qnames for the all of the XSD and SOAP-ENC encodings public static final QName XSD_STRING = new QName(URI_DEFAULT_SCHEMA_XSD, "string"); public static final QName XSD_BOOLEAN = new QName(URI_DEFAULT_SCHEMA_XSD, "boolean"); public static final QName XSD_DOUBLE = new QName(URI_DEFAULT_SCHEMA_XSD, "double"); public static final QName XSD_FLOAT = new QName(URI_DEFAULT_SCHEMA_XSD, "float"); public static final QName XSD_INT = new QName(URI_DEFAULT_SCHEMA_XSD, "int"); public static final QName XSD_INTEGER = new QName(URI_DEFAULT_SCHEMA_XSD, "integer"); public static final QName XSD_LONG = new QName(URI_DEFAULT_SCHEMA_XSD, "long"); public static final QName XSD_SHORT = new QName(URI_DEFAULT_SCHEMA_XSD, "short"); public static final QName XSD_BYTE = new QName(URI_DEFAULT_SCHEMA_XSD, "byte"); public static final QName XSD_DECIMAL = new QName(URI_DEFAULT_SCHEMA_XSD, "decimal"); public static final QName XSD_BASE64 = new QName(URI_DEFAULT_SCHEMA_XSD, "base64Binary"); public static final QName XSD_HEXBIN = new QName(URI_DEFAULT_SCHEMA_XSD, "hexBinary"); public static final QName XSD_ANYSIMPLETYPE = new QName(URI_DEFAULT_SCHEMA_XSD, "anySimpleType"); public static final QName XSD_ANYTYPE = new QName(URI_DEFAULT_SCHEMA_XSD, "anyType"); public static final QName XSD_ANY = new QName(URI_DEFAULT_SCHEMA_XSD, "any"); public static final QName XSD_QNAME = new QName(URI_DEFAULT_SCHEMA_XSD, "QName"); public static final QName XSD_DATETIME = new QName(URI_DEFAULT_SCHEMA_XSD, "dateTime"); public static final QName XSD_DATE = new QName(URI_DEFAULT_SCHEMA_XSD, "date"); public static final QName XSD_TIME = new QName(URI_DEFAULT_SCHEMA_XSD, "time"); public static final QName XSD_TIMEINSTANT1999 = new QName(URI_1999_SCHEMA_XSD, "timeInstant"); public static final QName XSD_TIMEINSTANT2000 = new QName(URI_2000_SCHEMA_XSD, "timeInstant"); public static final QName XSD_NORMALIZEDSTRING = new QName(URI_2001_SCHEMA_XSD, "normalizedString"); public static final QName XSD_TOKEN = new QName(URI_2001_SCHEMA_XSD, "token"); public static final QName XSD_UNSIGNEDLONG = new QName(URI_2001_SCHEMA_XSD, "unsignedLong"); public static final QName XSD_UNSIGNEDINT = new QName(URI_2001_SCHEMA_XSD, "unsignedInt"); public static final QName XSD_UNSIGNEDSHORT = new QName(URI_2001_SCHEMA_XSD, "unsignedShort"); public static final QName XSD_UNSIGNEDBYTE = new QName(URI_2001_SCHEMA_XSD, "unsignedByte"); public static final QName XSD_POSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "positiveInteger"); public static final QName XSD_NEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "negativeInteger"); public static final QName XSD_NONNEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonNegativeInteger"); public static final QName XSD_NONPOSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonPositiveInteger"); public static final QName XSD_YEARMONTH = new QName(URI_2001_SCHEMA_XSD, "gYearMonth"); public static final QName XSD_MONTHDAY = new QName(URI_2001_SCHEMA_XSD, "gMonthDay"); public static final QName XSD_YEAR = new QName(URI_2001_SCHEMA_XSD, "gYear"); public static final QName XSD_MONTH = new QName(URI_2001_SCHEMA_XSD, "gMonth"); public static final QName XSD_DAY = new QName(URI_2001_SCHEMA_XSD, "gDay"); public static final QName XSD_DURATION = new QName(URI_2001_SCHEMA_XSD, "duration"); public static final QName XSD_NAME = new QName(URI_2001_SCHEMA_XSD, "Name"); public static final QName XSD_NCNAME = new QName(URI_2001_SCHEMA_XSD, "NCName"); public static final QName XSD_NMTOKEN = new QName(URI_2001_SCHEMA_XSD, "NMTOKEN"); public static final QName XSD_NMTOKENS = new QName(URI_2001_SCHEMA_XSD, "NMTOKENS"); public static final QName XSD_NOTATION = new QName(URI_2001_SCHEMA_XSD, "NOTATION"); public static final QName XSD_ENTITY = new QName(URI_2001_SCHEMA_XSD, "ENTITY"); public static final QName XSD_ENTITIES = new QName(URI_2001_SCHEMA_XSD, "ENTITIES"); public static final QName XSD_IDREF = new QName(URI_2001_SCHEMA_XSD, "IDREF"); public static final QName XSD_IDREFS = new QName(URI_2001_SCHEMA_XSD, "IDREFS"); public static final QName XSD_ANYURI = new QName(URI_2001_SCHEMA_XSD, "anyURI"); public static final QName XSD_LANGUAGE = new QName(URI_2001_SCHEMA_XSD, "language"); public static final QName XSD_ID = new QName(URI_2001_SCHEMA_XSD, "ID"); public static final QName XSD_SCHEMA = new QName(URI_2001_SCHEMA_XSD, "schema"); public static final QName XML_LANG = new QName(NS_URI_XML, "lang"); public static final QName SOAP_BASE64 = new QName(URI_DEFAULT_SOAP_ENC, "base64"); public static final QName SOAP_BASE64BINARY = new QName(URI_DEFAULT_SOAP_ENC, "base64Binary"); public static final QName SOAP_STRING = new QName(URI_DEFAULT_SOAP_ENC, "string"); public static final QName SOAP_BOOLEAN = new QName(URI_DEFAULT_SOAP_ENC, "boolean"); public static final QName SOAP_DOUBLE = new QName(URI_DEFAULT_SOAP_ENC, "double"); public static final QName SOAP_FLOAT = new QName(URI_DEFAULT_SOAP_ENC, "float"); public static final QName SOAP_INT = new QName(URI_DEFAULT_SOAP_ENC, "int"); public static final QName SOAP_LONG = new QName(URI_DEFAULT_SOAP_ENC, "long"); public static final QName SOAP_SHORT = new QName(URI_DEFAULT_SOAP_ENC, "short"); public static final QName SOAP_BYTE = new QName(URI_DEFAULT_SOAP_ENC, "byte"); public static final QName SOAP_INTEGER = new QName(URI_DEFAULT_SOAP_ENC, "integer"); public static final QName SOAP_DECIMAL = new QName(URI_DEFAULT_SOAP_ENC, "decimal"); public static final QName SOAP_ARRAY = new QName(URI_DEFAULT_SOAP_ENC, "Array"); public static final QName SOAP_COMMON_ATTRS11 = new QName(URI_SOAP11_ENC, "commonAttributes"); public static final QName SOAP_COMMON_ATTRS12 = new QName(URI_SOAP12_ENC, "commonAttributes"); public static final QName SOAP_ARRAY_ATTRS11 = new QName(URI_SOAP11_ENC, "arrayAttributes"); public static final QName SOAP_ARRAY_ATTRS12 = new QName(URI_SOAP12_ENC, "arrayAttributes"); public static final QName SOAP_ARRAY12 = new QName(URI_SOAP12_ENC, "Array"); public static final QName SOAP_MAP = new QName(NS_URI_XMLSOAP, "Map"); public static final QName SOAP_ELEMENT = new QName(NS_URI_XMLSOAP, "Element"); public static final QName SOAP_DOCUMENT = new QName(NS_URI_XMLSOAP, "Document"); public static final QName SOAP_VECTOR = new QName(NS_URI_XMLSOAP, "Vector"); public static final QName MIME_IMAGE = new QName(NS_URI_XMLSOAP, "Image"); public static final QName MIME_PLAINTEXT = new QName(NS_URI_XMLSOAP, "PlainText"); public static final QName MIME_MULTIPART = new QName(NS_URI_XMLSOAP, "Multipart"); public static final QName MIME_SOURCE = new QName(NS_URI_XMLSOAP, "Source"); public static final QName MIME_OCTETSTREAM = new QName(NS_URI_XMLSOAP, "octet-stream"); public static final QName MIME_DATA_HANDLER = new QName(NS_URI_XMLSOAP, "DataHandler"); public static final QName QNAME_LITERAL_ITEM = new QName(URI_LITERAL_ENC,"item"); public static final QName QNAME_RPC_RESULT = new QName(URI_SOAP12_RPC,"result"); /** * QName of stack trace element in an axis fault detail. */ public static final QName QNAME_FAULTDETAIL_STACKTRACE = new QName(NS_URI_AXIS,"stackTrace"); /** * QName of exception Name element in an axis fault detail. * Do not use - this is for pre-1.0 server-&gt;client exceptions. */ public static final QName QNAME_FAULTDETAIL_EXCEPTIONNAME = new QName(NS_URI_AXIS, "exceptionName"); /** * Flag set if this was a runtime exception, rather than something thrown by the class at the end of the * chain. Axis' logging treats runtime exceptions more seriously. */ public static final QName QNAME_FAULTDETAIL_RUNTIMEEXCEPTION = new QName(NS_URI_AXIS, "isRuntimeException"); /** * QName of stack trace element in an axis fault detail. */ public static final QName QNAME_FAULTDETAIL_HTTPERRORCODE = new QName(NS_URI_AXIS, "HttpErrorCode"); /** * QName of a nested fault in an axis fault detail. */ public static final QName QNAME_FAULTDETAIL_NESTEDFAULT = new QName(NS_URI_AXIS, "nestedFault"); /** * QName of a hostname in an axis fault detail. */ public static final QName QNAME_FAULTDETAIL_HOSTNAME = new QName(NS_URI_AXIS, "hostname"); //QNames of well known faults /** * The no-service fault value. */ public static final QName QNAME_NO_SERVICE_FAULT_CODE = new QName(NS_URI_AXIS, "Server.NoService"); // Misc Strings ////////////////////////////////////////////////////////////////////////// // Where to put those pesky JWS classes public static final String MC_JWS_CLASSDIR = "jws.classDir" ; // Where we're rooted public static final String MC_HOME_DIR = "home.dir"; // Relative path of the request URL (ie. http://.../axis/a.jws = /a.jws public static final String MC_RELATIVE_PATH = "path"; // MessageContext param for the engine's path public static final String MC_REALPATH = "realpath"; // MessageContext param for the location of config files public static final String MC_CONFIGPATH = "configPath"; // MessageContext param for the IP of the calling client public static final String MC_REMOTE_ADDR = "remoteaddr"; // When invoked from a servlet, per JAX-RPC, we need a // ServletEndpointContext object. This is where it lives. public static final String MC_SERVLET_ENDPOINT_CONTEXT = "servletEndpointContext"; // If we're SOAP 1.2, the default behavior in org.apache.axis.message.BodyBuilder // is to throw a ProcedureNotPresent fault if we can't dispatch to an // OperationDesc during deserialization. Set this property to any non-null // value to prevent this behavior (only used by test.soap12. public static final String MC_NO_OPERATION_OK = "NoOperationOK"; // This property indicates we're supporting only a single SOAP version. // If set (by the service or engine), we'll only accept envelopes of the // specified version. Value should be an org.apache.axis.soap.SOAPConstants public static final String MC_SINGLE_SOAP_VERSION = "SingleSOAPVersion"; /** * What the extension of JWS files is. If changing this, note that * AxisServlet has an xdoclet declaration in the class javadocs that * also needs updating. */ public static final String JWS_DEFAULT_FILE_EXTENSION = ".jws"; /** * The default timeout for messages. * * @since Axis1.2 */ public static final int DEFAULT_MESSAGE_TIMEOUT=60*1000*10; /** * MIME Content Types * * @since Axis1.2 */ public static final String MIME_CT_APPLICATION_OCTETSTREAM = "application/octet-stream"; public static final String MIME_CT_TEXT_PLAIN = "text/plain"; public static final String MIME_CT_IMAGE_JPEG = "image/jpeg"; public static final String MIME_CT_IMAGE_GIF = "image/gif"; public static final String MIME_CT_TEXT_XML = "text/xml"; public static final String MIME_CT_APPLICATION_XML = "application/xml"; public static final String MIME_CT_MULTIPART_PREFIX = "multipart/"; }
7,332
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/SimpleProvider.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.configuration; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.handlers.soap.SOAPService; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; /** * A SimpleProvider is an EngineConfiguration which contains a simple * HashMap-based registry of Handlers, Transports, and Services. This is * for when you want to programatically deploy components which you create. * * SimpleProvider may also optionally contain a reference to a "default" * EngineConfiguration, which will be scanned for components not found in * the internal registry. This is handy when you want to start with a base * configuration (like the default WSDD) and then quickly add stuff without * changing the WSDD document. * * @author Glen Daniels (gdaniels@apache.org) */ public class SimpleProvider implements EngineConfiguration { /** Handler registry */ HashMap handlers = new HashMap(); /** Transport registry */ HashMap transports = new HashMap(); /** Service registry */ HashMap services = new HashMap(); /** Global configuration stuff */ Hashtable globalOptions = null; Handler globalRequest = null; Handler globalResponse = null; List roles = new ArrayList(); /** Our TypeMappingRegistry */ TypeMappingRegistry tmr = null; /** An optional "default" EngineConfiguration */ EngineConfiguration defaultConfiguration = null; private AxisEngine engine; /** * Default constructor. */ public SimpleProvider() { } /** * Constructor which takes an EngineConfiguration which will be used * as the default. */ public SimpleProvider(EngineConfiguration defaultConfiguration) { this.defaultConfiguration = defaultConfiguration; } /** * Construct a SimpleProvider using the supplied TypeMappingRegistry. * * @param typeMappingRegistry */ public SimpleProvider(TypeMappingRegistry typeMappingRegistry) { this.tmr = typeMappingRegistry; } /** * Configure an AxisEngine. Right now just calls the default * configuration if there is one, since we don't do anything special. */ public void configureEngine(AxisEngine engine) throws ConfigurationException { this.engine = engine; if (defaultConfiguration != null) defaultConfiguration.configureEngine(engine); for (Iterator i = services.values().iterator(); i.hasNext(); ) { ((SOAPService)i.next()).setEngine(engine); } } /** * We don't write ourselves out, so this is a noop. */ public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { } /** * Returns the global configuration options. */ public Hashtable getGlobalOptions() throws ConfigurationException { if (globalOptions != null) return globalOptions; if (defaultConfiguration != null) return defaultConfiguration.getGlobalOptions(); return null; } /** * Set the global options Hashtable * * @param options */ public void setGlobalOptions(Hashtable options) { globalOptions = options; } /** * Returns a global request handler. */ public Handler getGlobalRequest() throws ConfigurationException { if (globalRequest != null) return globalRequest; if (defaultConfiguration != null) return defaultConfiguration.getGlobalRequest(); return null; } /** * Set the global request Handler * * @param globalRequest */ public void setGlobalRequest(Handler globalRequest) { this.globalRequest = globalRequest; } /** * Returns a global response handler. */ public Handler getGlobalResponse() throws ConfigurationException { if (globalResponse != null) return globalResponse; if (defaultConfiguration != null) return defaultConfiguration.getGlobalResponse(); return null; } /** * Set the global response Handler * * @param globalResponse */ public void setGlobalResponse(Handler globalResponse) { this.globalResponse = globalResponse; } /** * Get our TypeMappingRegistry. Returns our specific one if we have * one, otherwise the one from our defaultConfiguration. If we don't * have one and also don't have a defaultConfiguration, we create one. * */ public TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException { if (tmr != null) return tmr; if (defaultConfiguration != null) return defaultConfiguration.getTypeMappingRegistry(); // No default config, but we need a TypeMappingRegistry... // (perhaps the TMRs could just be chained?) tmr = new TypeMappingRegistryImpl(); return tmr; } public TypeMapping getTypeMapping(String encodingStyle) throws ConfigurationException { return (TypeMapping)getTypeMappingRegistry().getTypeMapping(encodingStyle); } public Handler getTransport(QName qname) throws ConfigurationException { Handler transport = (Handler)transports.get(qname); if ((defaultConfiguration != null) && (transport == null)) transport = defaultConfiguration.getTransport(qname); return transport; } public SOAPService getService(QName qname) throws ConfigurationException { SOAPService service = (SOAPService)services.get(qname); if ((defaultConfiguration != null) && (service == null)) service = defaultConfiguration.getService(qname); return service; } /** * Get a service which has been mapped to a particular namespace * * @param namespace a namespace URI * @return an instance of the appropriate Service, or null */ public SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException { SOAPService service = (SOAPService)services.get(new QName("",namespace)); if ((service == null) && (defaultConfiguration != null)) service = defaultConfiguration.getServiceByNamespaceURI(namespace); return service; } public Handler getHandler(QName qname) throws ConfigurationException { Handler handler = (Handler)handlers.get(qname); if ((defaultConfiguration != null) && (handler == null)) handler = defaultConfiguration.getHandler(qname); return handler; } public void deployService(QName qname, SOAPService service) { services.put(qname, service); if (engine != null) service.setEngine(engine); } public void deployService(String name, SOAPService service) { deployService(new QName(null, name), service); } public void deployTransport(QName qname, Handler transport) { transports.put(qname, transport); } public void deployTransport(String name, Handler transport) { deployTransport(new QName(null, name), transport); } /** * Get an enumeration of the services deployed to this engine */ public Iterator getDeployedServices() throws ConfigurationException { ArrayList serviceDescs = new ArrayList(); Iterator i = services.values().iterator(); while (i.hasNext()) { SOAPService service = (SOAPService)i.next(); serviceDescs.add(service.getServiceDescription()); } return serviceDescs.iterator(); } /** * Set the global role list for this configuration. Note that we use * the actual passed value, so if anyone else changes that collection, * our role list will change. Be careful to pass this a cloned list if * you want to change the list later without affecting the config. * * @param roles */ public void setRoles(List roles) { this.roles = roles; } /** * Add a role to the configuration's global list * * @param role */ public void addRole(String role) { roles.add(role); } /** * Remove a role from the configuration's global list * * @param role */ public void removeRole(String role) { roles.remove(role); } /** * Get a list of roles that this engine plays globally. Services * within the engine configuration may also add additional roles. * * @return a <code>List</code> of the roles for this engine */ public List getRoles() { return roles; } }
7,333
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/NullProvider.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.configuration; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.handlers.soap.SOAPService; import javax.xml.namespace.QName; import java.util.Hashtable; import java.util.Iterator; import java.util.List; /** * A do-nothing ConfigurationProvider * * @author Glen Daniels (gdaniels@apache.org) */ public class NullProvider implements EngineConfiguration { public void configureEngine(AxisEngine engine) throws ConfigurationException { } public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { } public Hashtable getGlobalOptions() throws ConfigurationException { return null; } public Handler getGlobalResponse() throws ConfigurationException { return null; } public Handler getGlobalRequest() throws ConfigurationException { return null; } public TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException { return null; } public TypeMapping getTypeMapping(String encodingStyle) throws ConfigurationException { return null; } public Handler getTransport(QName qname) throws ConfigurationException { return null; } public SOAPService getService(QName qname) throws ConfigurationException { return null; } public SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException { return null; } public Handler getHandler(QName qname) throws ConfigurationException { return null; } /** * Get an enumeration of the services deployed to this engine */ public Iterator getDeployedServices() throws ConfigurationException { return null; } /** * Get a list of roles that this engine plays globally. Services * within the engine configuration may also add additional roles. * * @return a <code>List</code> of the roles for this engine */ public List getRoles() { return null; } }
7,334
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/EngineConfigurationFactoryDefault.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.configuration; import org.apache.axis.AxisProperties; import org.apache.axis.EngineConfiguration; import org.apache.axis.EngineConfigurationFactory; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** * This is a default implementation of EngineConfigurationFactory. * It is user-overrideable by a system property without affecting * the caller. If you decide to override it, use delegation if * you want to inherit the behaviour of this class as using * class extension will result in tight loops. That is, your * class should implement EngineConfigurationFactory and keep * an instance of this class in a member field and delegate * methods to that instance when the default behaviour is * required. * * @author Richard A. Sitze * @author Glyn Normington (glyn@apache.org) */ public class EngineConfigurationFactoryDefault implements EngineConfigurationFactory { protected static Log log = LogFactory.getLog(EngineConfigurationFactoryDefault.class.getName()); public static final String OPTION_CLIENT_CONFIG_FILE = "axis.ClientConfigFile"; public static final String OPTION_SERVER_CONFIG_FILE = "axis.ServerConfigFile"; protected static final String CLIENT_CONFIG_FILE = "client-config.wsdd"; protected static final String SERVER_CONFIG_FILE = "server-config.wsdd"; protected String clientConfigFile; protected String serverConfigFile; /** * Creates and returns a new EngineConfigurationFactory. * If a factory cannot be created, return 'null'. * * The factory may return non-NULL only if: * - it knows what to do with the param (param == null) * - it can find it's configuration information * * @see org.apache.axis.configuration.EngineConfigurationFactoryFinder */ public static EngineConfigurationFactory newFactory(Object param) { if (param != null) return null; // not for us. /** * Default, let this one go through. * * The REAL reason we are not trying to make any * decision here is because it's impossible * (without refactoring FileProvider) to determine * if a *.wsdd file is present or not until the configuration * is bound to an engine. * * FileProvider/EngineConfiguration pretend to be independent, * but they are tightly bound to an engine instance... */ return new EngineConfigurationFactoryDefault(); } /** * Create the default engine configuration and detect whether the user * has overridden this with their own. */ protected EngineConfigurationFactoryDefault() { clientConfigFile = AxisProperties.getProperty(OPTION_CLIENT_CONFIG_FILE, CLIENT_CONFIG_FILE); serverConfigFile = AxisProperties.getProperty(OPTION_SERVER_CONFIG_FILE, SERVER_CONFIG_FILE); } /** * Get a default client engine configuration. * * @return a client EngineConfiguration */ public EngineConfiguration getClientEngineConfig() { return new FileProvider(clientConfigFile); } /** * Get a default server engine configuration. * * @return a server EngineConfiguration */ public EngineConfiguration getServerEngineConfig() { return new FileProvider(serverConfigFile); } }
7,335
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/BasicClientConfig.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.configuration; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.transport.http.HTTPSender; import org.apache.axis.transport.java.JavaSender; import org.apache.axis.transport.local.LocalSender; /** * A SimpleProvider set up with hardcoded basic configuration for a client * (i.e. http and local transports). * * @author Glen Daniels (gdaniels@apache.org) */ public class BasicClientConfig extends SimpleProvider { /** * Constructor - deploy client-side basic transports. */ public BasicClientConfig() { deployTransport("java", new SimpleTargetedChain(new JavaSender())); deployTransport("local", new SimpleTargetedChain(new LocalSender())); deployTransport("http", new SimpleTargetedChain(new HTTPSender())); } }
7,336
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/DirProvider.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.configuration; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.FileFilter; import java.io.IOException; import java.util.Hashtable; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDDocument; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; public class DirProvider extends DelegatingWSDDEngineConfiguration { protected static Log log = LogFactory.getLog(DirProvider.class.getName()); private WSDDDeployment deployment = null; private String configFile; private File dir; private static final String SERVER_CONFIG_FILE = "server-config.wsdd"; public DirProvider(String basepath) throws ConfigurationException { this(basepath, SERVER_CONFIG_FILE); } public DirProvider(String basepath, String configFile) throws ConfigurationException { File dir = new File(basepath); /* * If the basepath is not a readable directory, throw an internal * exception to make it easier to debug setup problems. */ if (!dir.exists() || !dir.isDirectory() || !dir.canRead()) { throw new ConfigurationException(Messages.getMessage ("invalidConfigFilePath", basepath)); } this.dir = dir; this.configFile = configFile; } public WSDDDeployment getDeployment() { return this.deployment; } private static class DirFilter implements FileFilter { public boolean accept(File path) { return path.isDirectory(); } } public void configureEngine(AxisEngine engine) throws ConfigurationException { this.deployment = new WSDDDeployment(); WSDDGlobalConfiguration config = new WSDDGlobalConfiguration(); config.setOptionsHashtable(new Hashtable()); this.deployment.setGlobalConfiguration(config); File [] dirs = this.dir.listFiles(new DirFilter()); for (int i = 0; i < dirs.length; i++) { processWSDD(dirs[i]); } this.deployment.configureEngine(engine); engine.refreshGlobalOptions(); } private void processWSDD(File dir) throws ConfigurationException { File file = new File(dir, this.configFile); if (!file.exists()) { return; } log.debug("Loading service configuration from file: " + file); InputStream in = null; try { in = new FileInputStream(file); WSDDDocument doc = new WSDDDocument(XMLUtils.newDocument(in)); doc.deploy(this.deployment); } catch (Exception e) { throw new ConfigurationException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) {} } } } /** * Save the engine configuration. In case there's a problem, we * write it to a string before saving it out to the actual file so * we don't screw up the file. */ public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { // this is not implemented } }
7,337
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/EngineConfigurationFactoryFinder.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.configuration; import org.apache.axis.AxisProperties; import org.apache.axis.EngineConfigurationFactory; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.discovery.ResourceClassIterator; import org.apache.commons.discovery.tools.ClassUtils; import org.apache.commons.logging.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; /** * This is a default implementation of EngineConfigurationFactory. * It is user-overrideable by a system property without affecting * the caller. If you decide to override it, use delegation if * you want to inherit the behaviour of this class as using * class extension will result in tight loops. That is, your * class should implement EngineConfigurationFactory and keep * an instance of this class in a member field and delegate * methods to that instance when the default behaviour is * required. * * @author Richard A. Sitze */ public class EngineConfigurationFactoryFinder { protected static Log log = LogFactory.getLog(EngineConfigurationFactoryFinder.class.getName()); private static final Class mySpi = EngineConfigurationFactory.class; private static final Class[] newFactoryParamTypes = new Class[] { Object.class }; private static final String requiredMethod = "public static EngineConfigurationFactory newFactory(Object)"; static { AxisProperties.setClassOverrideProperty( EngineConfigurationFactory.class, EngineConfigurationFactory.SYSTEM_PROPERTY_NAME); AxisProperties.setClassDefaults(EngineConfigurationFactory.class, new String[] { "org.apache.axis.configuration.EngineConfigurationFactoryServlet", "org.apache.axis.configuration.EngineConfigurationFactoryDefault", }); } private EngineConfigurationFactoryFinder() { } /** * Create the default engine configuration and detect whether the user * has overridden this with their own. * * The discovery mechanism will use the following logic: * * - discover all available EngineConfigurationFactories * - find all META-INF/services/org.apache.axis.EngineConfigurationFactory * files available through class loaders. * - read files (see Discovery) to obtain implementation(s) of that * interface * - For each impl, call 'newFactory(Object param)' * - Each impl should examine the 'param' and return a new factory ONLY * - if it knows what to do with it * (i.e. it knows what to do with the 'real' type) * - it can find it's configuration information * - Return first non-null factory found. * - Try EngineConfigurationFactoryServlet.newFactory(obj) * - Try EngineConfigurationFactoryDefault.newFactory(obj) * - If zero found (all return null), throw exception * * *** * This needs more work: System.properties, etc. * Discovery will have more tools to help with that * (in the manner of use below) in the near future. * *** * */ public static EngineConfigurationFactory newFactory(final Object obj) { /** * recreate on each call is critical to gaining * the right class loaders. Do not cache. */ final Object[] params = new Object[] { obj }; /** * Find and examine each service */ return (EngineConfigurationFactory)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { ResourceClassIterator services = AxisProperties.getResourceClassIterator(mySpi); EngineConfigurationFactory factory = null; while (factory == null && services.hasNext()) { try { Class service = services.nextResourceClass().loadClass(); /* service == null * if class resource wasn't loadable */ if (service != null) { factory = newFactory(service, newFactoryParamTypes, params); } } catch (Exception e) { // there was an exception creating the factory // the most likely cause was the JDK 1.4 problem // in the discovery code that requires servlet.jar // to be in the client classpath. For now, fall // through to the next factory } } if (factory != null) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("engineFactory", factory.getClass().getName())); } } else { log.error(Messages.getMessage("engineConfigFactoryMissing")); // we should be throwing an exception here, // // but again, requires more refactoring than we want to swallow // at this point in time. Ifthis DOES occur, it's a coding error: // factory should NEVER be null. // Testing will find this, as NullPointerExceptions will be generated // elsewhere. } return factory; } }); } public static EngineConfigurationFactory newFactory() { return newFactory(null); } private static EngineConfigurationFactory newFactory(Class service, Class[] paramTypes, Object[] param) { /** * Some JDK's may link on method resolution (findPublicStaticMethod) * and others on method call (method.invoke). * * Either way, catch class load/resolve problems and return null. */ try { /** * Verify that service implements: * public static EngineConfigurationFactory newFactory(Object); */ Method method = ClassUtils.findPublicStaticMethod(service, EngineConfigurationFactory.class, "newFactory", paramTypes); if (method == null) { log.warn(Messages.getMessage("engineConfigMissingNewFactory", service.getName(), requiredMethod)); } else { try { return (EngineConfigurationFactory)method.invoke(null, param); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof NoClassDefFoundError) { log.debug(Messages.getMessage("engineConfigLoadFactory", service.getName())); } else { log.warn(Messages.getMessage("engineConfigInvokeNewFactory", service.getName(), requiredMethod), e); } } catch (Exception e) { log.warn(Messages.getMessage("engineConfigInvokeNewFactory", service.getName(), requiredMethod), e); } } } catch (NoClassDefFoundError e) { log.debug(Messages.getMessage("engineConfigLoadFactory", service.getName())); } return null; } }
7,338
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/DelegatingWSDDEngineConfiguration.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.configuration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.axis.ConfigurationException; import org.apache.axis.Handler; import org.apache.axis.WSDDEngineConfiguration; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.utils.Messages; /** * {@link WSDDEngineConfiguration} implementation that delegates to the {@link WSDDDeployment} * returned by {@link WSDDEngineConfiguration#getDeployment()}. */ public abstract class DelegatingWSDDEngineConfiguration implements WSDDEngineConfiguration { /** * retrieve an instance of the named handler * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public final Handler getHandler(QName qname) throws ConfigurationException { return getDeployment().getHandler(qname); } /** * retrieve an instance of the named service * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public final SOAPService getService(QName qname) throws ConfigurationException { SOAPService service = getDeployment().getService(qname); if (service == null) { throw new ConfigurationException(Messages.getMessage("noService10", qname.toString())); } return service; } /** * Get a service which has been mapped to a particular namespace * * @param namespace a namespace URI * @return an instance of the appropriate Service, or null */ public final SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException { return getDeployment().getServiceByNamespaceURI(namespace); } /** * retrieve an instance of the named transport * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public final Handler getTransport(QName qname) throws ConfigurationException { return getDeployment().getTransport(qname); } public final TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException { return getDeployment().getTypeMappingRegistry(); } /** * Returns a global request handler. */ public final Handler getGlobalRequest() throws ConfigurationException { return getDeployment().getGlobalRequest(); } /** * Returns a global response handler. */ public final Handler getGlobalResponse() throws ConfigurationException { return getDeployment().getGlobalResponse(); } /** * Returns the global configuration options. */ public final Hashtable getGlobalOptions() throws ConfigurationException { WSDDGlobalConfiguration globalConfig = getDeployment().getGlobalConfiguration(); if (globalConfig != null) return globalConfig.getParametersTable(); return null; } /** * Get an enumeration of the services deployed to this engine */ public final Iterator getDeployedServices() throws ConfigurationException { return getDeployment().getDeployedServices(); } /** * Get a list of roles that this engine plays globally. Services * within the engine configuration may also add additional roles. * * @return a <code>List</code> of the roles for this engine */ public final List getRoles() { return getDeployment().getRoles(); } }
7,339
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/FileProvider.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.configuration; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDDocument; import org.apache.axis.utils.Admin; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; /** * A simple ConfigurationProvider that uses the Admin class to read + * write XML files. * * @author Glen Daniels (gdaniels@apache.org) * @author Glyn Normington (glyn@apache.org) */ public class FileProvider extends DelegatingWSDDEngineConfiguration { protected static Log log = LogFactory.getLog(FileProvider.class.getName()); private WSDDDeployment deployment = null; private String filename; private File configFile = null; private InputStream myInputStream = null; private boolean readOnly = true; // Should we search the classpath for the file if we don't find it in // the specified location? private boolean searchClasspath = true; /** * Constructor which accesses a file in the current directory of the * engine or at an absolute path. */ public FileProvider(String filename) { this.filename = filename; configFile = new File(filename); check(); } /** * Constructor which accesses a file relative to a specific base * path. */ public FileProvider(String basepath, String filename) throws ConfigurationException { this.filename = filename; File dir = new File(basepath); /* * If the basepath is not a readable directory, throw an internal * exception to make it easier to debug setup problems. */ if (!dir.exists() || !dir.isDirectory() || !dir.canRead()) { throw new ConfigurationException(Messages.getMessage ("invalidConfigFilePath", basepath)); } configFile = new File(basepath, filename); check(); } /** * Check the configuration file attributes and remember whether * or not the file is read-only. */ private void check() { try { readOnly = configFile.canRead() & !configFile.canWrite(); } catch (SecurityException se){ readOnly = true; } /* * If file is read-only, log informational message * as configuration changes will not persist. */ if (readOnly) { log.info(Messages.getMessage("readOnlyConfigFile")); } } /** * Constructor which takes an input stream directly. * Note: The configuration will be read-only in this case! */ public FileProvider(InputStream is) { setInputStream(is); } public void setInputStream(InputStream is) { myInputStream = is; } private InputStream getInputStream() { return myInputStream; } public WSDDDeployment getDeployment() { return deployment; } public void setDeployment(WSDDDeployment deployment) { this.deployment = deployment; } /** * Determine whether or not we will look for a "*-config.wsdd" file * on the classpath if we don't find it in the specified location. * * @param searchClasspath true if we should search the classpath */ public void setSearchClasspath(boolean searchClasspath) { this.searchClasspath = searchClasspath; } public void configureEngine(AxisEngine engine) throws ConfigurationException { try { InputStream configFileInputStream = getInputStream(); if (configFileInputStream == null) { try { configFileInputStream = new FileInputStream(configFile); } catch (Exception e) { // Ignore and continue } } if (configFileInputStream == null && searchClasspath) { // Attempt to load the file from the classpath configFileInputStream = ClassUtils.getResourceAsStream(filename, engine.getClass().getClassLoader()); } if (configFileInputStream == null) { // Load the default configuration. This piece of code provides compatibility with Axis 1.4, // which ends up loading org/apache/axis/(client|server)/(client|server)-config.wsdd if // (1) filename is (client|server)-config.wsdd; // (2) the runtime type of the engine is AxisClient or AxisServer; // (3) the file is not found on the file system or in the classpath. String type; if (filename.equals(EngineConfigurationFactoryDefault.CLIENT_CONFIG_FILE)) { type = "client"; } else if (filename.equals(EngineConfigurationFactoryDefault.SERVER_CONFIG_FILE)) { type = "server"; } else { throw new ConfigurationException( Messages.getMessage("noConfigFile")); } DefaultConfiguration defaultConfig = new DefaultConfiguration(type); defaultConfig.configureEngine(engine); deployment = defaultConfig.getDeployment(); } else { WSDDDocument doc = new WSDDDocument(XMLUtils. newDocument(configFileInputStream)); deployment = doc.getDeployment(); deployment.configureEngine(engine); } engine.refreshGlobalOptions(); setInputStream(null); } catch (Exception e) { throw new ConfigurationException(e); } } /** * Save the engine configuration. In case there's a problem, we * write it to a string before saving it out to the actual file so * we don't screw up the file. */ public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { if (!readOnly) { try { Document doc = Admin.listConfig(engine); Writer osWriter = new OutputStreamWriter( new FileOutputStream(configFile),XMLUtils.getEncoding()); PrintWriter writer = new PrintWriter(new BufferedWriter(osWriter)); XMLUtils.DocumentToWriter(doc, writer); writer.println(); writer.close(); } catch (Exception e) { throw new ConfigurationException(e); } } } }
7,340
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/XMLStringProvider.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.configuration; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import java.io.ByteArrayInputStream; /** * A simple ConfigurationProvider that uses the Admin class to * configure the engine from a String containing XML. * * This provider does not write configuration to persistent storage. * * Example of usage: * new XMLStringProvider("&lt;engineConfig&gt;&lt;handlers&gt;&lt;handler name=" + * "\"MsgDispatcher\" class=\"org.apache.axis.providers.java" + * ".MsgProvider\"/&gt;&lt;/handlers&gt;&lt;services&gt;&lt;service name=\"Adm" + * "inService\" pivot=\"MsgDispatcher\"&gt;&lt;option name=\"class" + * "Name\" value=\"org.apache.axis.utils.Admin\"/&gt;&lt;option na" + * "me=\"allowedMethods\" value=\"AdminService\"/&gt;&lt;option na" + * "me=\"enableRemoteAdmin\" value=\"false\"/&gt;&lt;/service&gt;&lt;/se" + * "rvices&gt;&lt;/engineConfig&gt;"); * * @author Glen Daniels (gdaniels@apache.org) */ public class XMLStringProvider extends FileProvider { String xmlConfiguration; /** * Constructor * * @param xmlConfiguration a String containing an engine configuration * in XML. */ public XMLStringProvider(String xmlConfiguration) { super(new ByteArrayInputStream(xmlConfiguration.getBytes())); this.xmlConfiguration = xmlConfiguration; } public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { // NOOP } public void configureEngine(AxisEngine engine) throws ConfigurationException { setInputStream(new ByteArrayInputStream(xmlConfiguration.getBytes())); super.configureEngine(engine); } }
7,341
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/DefaultConfiguration.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.configuration; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDDocument; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; /** * Configuration provider that loads the default Axis configuration. It first loads the * <tt>org/apache/axis/&lt;type&gt;/&lt;type&gt;-config.wsdd</tt> resource and then searches for resources * with name <tt>META-INF/axis/default-&lt;type&gt;-config.wsdd</tt>. All the discovered WSDD documents * are merged into a single configuration. <tt>&lt;type&gt;</tt> identifies the engine type for which * the configuration is to be built; it is either <tt>client</tt> or <tt>server</tt>. * <p> * This class looks up the resources using the thread context class loader, except if it determines * that the context class loader is not set correctly, in which case it falls back to the class * loader that loaded the {@link DefaultConfiguration} class. To determine if the context class * loader is set correctly, the code checks that the {@link DefaultConfiguration} class is visible * to the context class loader. * <p> * The algorithm implemented by this class is designed to support the modularized artifacts * introduced in Axis 1.4.1. It allows individual JARs to contribute items (transports, handlers, * etc.) to the default configuration. The naming convention for the base configuration file * (<tt>org/apache/axis/&lt;type&gt;/&lt;type&gt;-config.wsdd</tt>) was chosen for consistency with Axis * 1.4, while <tt>META-INF/axis/default-&lt;type&gt;-config.wsdd</tt> is new in Axis 1.4.1. * <p> * {@link DefaultConfiguration} is also used by {@link FileProvider} to build the configuration if * no existing configuration file is found. * * @author Andreas Veithen */ public class DefaultConfiguration extends DelegatingWSDDEngineConfiguration { private static final Log log = LogFactory.getLog(DefaultConfiguration.class.getName()); private final String type; private WSDDDeployment deployment; /** * Constructor. * * @param type * the engine type to load the default configuration for; this should be * <code>client</code> or <code>server</code> (although any value is supported) */ public DefaultConfiguration(String type) { this.type = type; } public void configureEngine(AxisEngine engine) throws ConfigurationException { ClassLoader classLoader; try { classLoader = Thread.currentThread().getContextClassLoader(); } catch (SecurityException ex) { // We can only get a SecurityException if "the caller's class loader is not the same as // or an ancestor of the context class loader". In this case we are not interested in // the class loader anyway. classLoader = null; } if (classLoader != null) { // Check if we are visible to the thread context class loader. If this is not the case, // then the context class loader is likely not set correctly and we ignore it. try { classLoader.loadClass(DefaultConfiguration.class.getName()); } catch (ClassNotFoundException ex) { log.debug(DefaultConfiguration.class.getName() + " not visible to thread context class loader"); classLoader = null; } } if (classLoader == null) { log.debug("Not using thread context class loader"); classLoader = DefaultConfiguration.class.getClassLoader(); } else { log.debug("Using thread context class loader"); } // Load the base configuration String resourceName = "org/apache/axis/" + type + "/" + type + "-config.wsdd"; if (log.isDebugEnabled()) { log.debug("Loading resource " + resourceName); } InputStream in = classLoader.getResourceAsStream(resourceName); if (in == null) { throw new ConfigurationException("Resource " + resourceName + " not found"); } try { try { deployment = new WSDDDocument(XMLUtils.newDocument(in)).getDeployment(); } finally { in.close(); } } catch (Exception ex) { // TODO: refactor ConfigurationException to support exception chaining throw new ConfigurationException(/*"Failed to process resource " + baseConfigResource,*/ ex); } // Discover and load additional default configuration fragments resourceName = "META-INF/axis/default-" + type + "-config.wsdd"; Enumeration resources; try { resources = classLoader.getResources(resourceName); } catch (IOException ex) { // TODO: refactor ConfigurationException to support exception chaining throw new ConfigurationException(/*"Failed to discover resources with name " + resourceName,*/ ex); } while (resources.hasMoreElements()) { URL url = (URL)resources.nextElement(); if (log.isDebugEnabled()) { log.debug("Loading " + url); } try { in = url.openStream(); try { new WSDDDocument(XMLUtils.newDocument(in)).deploy(deployment); } finally { in.close(); } } catch (Exception ex) { // TODO: refactor ConfigurationException to support exception chaining throw new ConfigurationException(/*"Failed to process " + url,*/ ex); } } deployment.configureEngine(engine); } public WSDDDeployment getDeployment() { return deployment; } public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { // Default configuration is read-only } }
7,342
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/BasicServerConfig.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.configuration; import org.apache.axis.Handler; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.transport.local.LocalResponder; import org.apache.axis.transport.local.LocalSender; /** * A SimpleProvider set up with hardcoded basic configuration for a server * (i.e. local transport). Mostly handy for testing. * * @author Glen Daniels (gdaniels@apache.org) */ public class BasicServerConfig extends SimpleProvider { /** * Constructor - deploy a hardcoded basic server-side configuration. */ public BasicServerConfig() { Handler h = new LocalResponder(); SimpleTargetedChain transport = new SimpleTargetedChain(null, null, h); deployTransport("local", transport); deployTransport("java", new SimpleTargetedChain(new LocalSender())); } }
7,343
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/configuration/EngineConfigurationFactoryServlet.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.configuration; import org.apache.axis.AxisProperties; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.EngineConfigurationFactory; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.server.AxisServer; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import java.io.File; import java.io.InputStream; /** * This is a default implementation of ServletEngineConfigurationFactory. * It is user-overrideable by a system property without affecting * the caller. If you decide to override it, use delegation if * you want to inherit the behaviour of this class as using * class extension will result in tight loops. That is, your * class should implement EngineConfigurationFactory and keep * an instance of this class in a member field and delegate * methods to that instance when the default behaviour is * required. * * @author Richard A. Sitze * @author Davanum Srinivas (dims@apache.org) */ public class EngineConfigurationFactoryServlet extends EngineConfigurationFactoryDefault { protected static Log log = LogFactory.getLog(EngineConfigurationFactoryServlet.class.getName()); private ServletConfig cfg; /** * Creates and returns a new EngineConfigurationFactory. * If a factory cannot be created, return 'null'. * * The factory may return non-NULL only if: * - it knows what to do with the param (param instanceof ServletContext) * - it can find it's configuration information * * @see org.apache.axis.configuration.EngineConfigurationFactoryFinder */ public static EngineConfigurationFactory newFactory(Object param) { /** * Default, let this one go through if we find a ServletContext. * * The REAL reason we are not trying to make any * decision here is because it's impossible * (without refactoring FileProvider) to determine * if a *.wsdd file is present or not until the configuration * is bound to an engine. * * FileProvider/EngineConfiguration pretend to be independent, * but they are tightly bound to an engine instance... */ return (param instanceof ServletConfig) ? new EngineConfigurationFactoryServlet((ServletConfig)param) : null; } /** * Create the default engine configuration and detect whether the user * has overridden this with their own. */ protected EngineConfigurationFactoryServlet(ServletConfig conf) { super(); this.cfg = conf; } /** * Get a default server engine configuration. * * @return a server EngineConfiguration */ public EngineConfiguration getServerEngineConfig() { return getServerEngineConfig(cfg); } /** * Get a default server engine configuration in a servlet environment. * * @param ctx a ServletContext * @return a server EngineConfiguration */ private static EngineConfiguration getServerEngineConfig(ServletConfig cfg) { ServletContext ctx = cfg.getServletContext(); // Respect the system property setting for a different config file String configFile = cfg.getInitParameter(OPTION_SERVER_CONFIG_FILE); if (configFile == null) configFile = AxisProperties.getProperty(OPTION_SERVER_CONFIG_FILE); if (configFile == null) { configFile = SERVER_CONFIG_FILE; } /** * Flow can be confusing. Here is the logic: * 1) Make all attempts to open resource IF it exists * - If it exists as a file, open as file (r/w) * - If not a file, it may still be accessable as a stream (r) * (env will handle security checks). * 2) If it doesn't exist, allow it to be opened/created * * Now, the way this is done below is: * a) If the file does NOT exist, attempt to open as a stream (r) * b) Open named file (opens existing file, creates if not avail). */ /* * Use the WEB-INF directory * (so the config files can't get snooped by a browser) */ String appWebInfPath = "/WEB-INF"; FileProvider config = null; String realWebInfPath = ctx.getRealPath(appWebInfPath); /** * If path/file doesn't exist, it may still be accessible * as a resource-stream (i.e. it may be packaged in a JAR * or WAR file). */ if (realWebInfPath == null || !(new File(realWebInfPath, configFile)).exists()) { String name = appWebInfPath + "/" + configFile; InputStream is = ctx.getResourceAsStream(name); if (is != null) { // FileProvider assumes responsibility for 'is': // do NOT call is.close(). config = new FileProvider(is); } if (config == null) { log.error(Messages.getMessage("servletEngineWebInfError03", name)); } } /** * Couldn't get data OR file does exist. * If we have a path, then attempt to either open * the existing file, or create an (empty) file. */ if (config == null && realWebInfPath != null) { try { config = new FileProvider(realWebInfPath, configFile); } catch (ConfigurationException e) { log.error(Messages.getMessage("servletEngineWebInfError00"), e); } } /** * Fall back to config file packaged with AxisEngine */ if (config == null) { log.warn(Messages.getMessage("servletEngineWebInfWarn00")); try { InputStream is = ClassUtils.getResourceAsStream(AxisServer.class, SERVER_CONFIG_FILE); config = new FileProvider(is); } catch (Exception e) { log.error(Messages.getMessage("servletEngineWebInfError02"), e); } } return config; } }
7,344
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/UnsignedShortHolder.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.holders; import org.apache.axis.types.UnsignedShort; import javax.xml.rpc.holders.Holder; /** * Class UnsignedShortHolder * */ public final class UnsignedShortHolder implements Holder { /** Field _value */ public UnsignedShort value; /** * Constructor UnsignedShortHolder */ public UnsignedShortHolder() { } /** * Constructor UnsignedShortHolder * * @param value */ public UnsignedShortHolder(UnsignedShort value) { this.value = value; } }
7,345
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/SourceHolder.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.holders; import javax.xml.rpc.holders.Holder; import javax.xml.transform.Source; /** * Class SourceHolder * * @version 1.0 */ public final class SourceHolder implements Holder { /** Field _value */ public Source value; /** * Constructor SourceHolder */ public SourceHolder() {} /** * Constructor SourceHolder * * @param value */ public SourceHolder(Source value) { this.value = value; } }
7,346
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/NonNegativeIntegerHolder.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.holders; import org.apache.axis.types.NonNegativeInteger; import javax.xml.rpc.holders.Holder; /** * Class NonNegativeIntegerHolder * */ public final class NonNegativeIntegerHolder implements Holder { /** Field _value */ public NonNegativeInteger value; /** * Constructor NonNegativeIntegerHolder */ public NonNegativeIntegerHolder() { } /** * Constructor NonNegativeIntegerHolder * * @param value */ public NonNegativeIntegerHolder(NonNegativeInteger value) { this.value = value; } }
7,347
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/YearHolder.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.holders; import org.apache.axis.types.Year; import javax.xml.rpc.holders.Holder; /** * Class YearHolder * */ public final class YearHolder implements Holder { /** Field _value */ public Year value; /** * Constructor YearHolder */ public YearHolder() { } /** * Constructor YearHolder * * @param value */ public YearHolder(Year value) { this.value = value; } }
7,348
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/SchemaHolder.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.holders; /** * Custom class for supporting XSD schema * * @author Davanum Srinivas (dims@yahoo.com) */ public final class SchemaHolder implements javax.xml.rpc.holders.Holder { public org.apache.axis.types.Schema value; public SchemaHolder() { } public SchemaHolder(org.apache.axis.types.Schema value) { this.value = value; } }
7,349
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/UnsignedByteHolder.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.holders; import org.apache.axis.types.UnsignedByte; import javax.xml.rpc.holders.Holder; /** * Class UnsignedByteHolder * */ public final class UnsignedByteHolder implements Holder { /** Field _value */ public UnsignedByte value; /** * Constructor UnsignedByteHolder */ public UnsignedByteHolder() { } /** * Constructor UnsignedByteHolder * * @param value */ public UnsignedByteHolder(UnsignedByte value) { this.value = value; } }
7,350
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/YearMonthHolder.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.holders; import org.apache.axis.types.YearMonth; import javax.xml.rpc.holders.Holder; /** * Class YearMonthHolder * */ public final class YearMonthHolder implements Holder { /** Field _value */ public YearMonth value; /** * Constructor YearMonthHolder */ public YearMonthHolder() { } /** * Constructor YearMonthHolder * * @param value */ public YearMonthHolder(YearMonth value) { this.value = value; } }
7,351
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/HexBinaryHolder.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.holders; import org.apache.axis.types.HexBinary; import javax.xml.rpc.holders.Holder; /** * Class HexBinaryHolder * */ public final class HexBinaryHolder implements Holder { /** Field _value */ public HexBinary value; /** * Constructor HexBinaryHolder */ public HexBinaryHolder() { } /** * Constructor HexBinaryHolder * * @param value */ public HexBinaryHolder(HexBinary value) { this.value = value; } }
7,352
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/PositiveIntegerHolder.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.holders; import org.apache.axis.types.PositiveInteger; import javax.xml.rpc.holders.Holder; /** * Class PositiveIntegerHolder * */ public final class PositiveIntegerHolder implements Holder { /** Field _value */ public PositiveInteger value; /** * Constructor PositiveIntegerHolder */ public PositiveIntegerHolder() { } /** * Constructor PositiveIntegerHolder * * @param value */ public PositiveIntegerHolder(PositiveInteger value) { this.value = value; } }
7,353
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/DataHandlerHolder.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.holders; import javax.xml.rpc.holders.Holder; import javax.activation.DataHandler; /** * Class DataHandlerHolder * * @version 1.0 */ public final class DataHandlerHolder implements Holder { /** Field _value */ public DataHandler value; /** * Constructor MimeMultipartHolder */ public DataHandlerHolder() {} /** * Constructor MimeMultipartHolder * * @param value */ public DataHandlerHolder(DataHandler value) { this.value = value; } }
7,354
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/ImageHolder.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.holders; import javax.xml.rpc.holders.Holder; import java.awt.*; /** * Class ImageHolder * * @version 1.0 */ public final class ImageHolder implements Holder { /** Field _value */ public Image value; /** * Constructor ImageHolder */ public ImageHolder() {} /** * Constructor ImageHolder * * @param value */ public ImageHolder(Image value) { this.value = value; } }
7,355
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/UnsignedLongHolder.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.holders; import org.apache.axis.types.UnsignedLong; import javax.xml.rpc.holders.Holder; /** * Class UnsignedLongHolder * */ public final class UnsignedLongHolder implements Holder { /** Field _value */ public UnsignedLong value; /** * Constructor UnsignedLongHolder */ public UnsignedLongHolder() { } /** * Constructor UnsignedLongHolder * * @param value */ public UnsignedLongHolder(UnsignedLong value) { this.value = value; } }
7,356
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/DateHolder.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.holders; import javax.xml.rpc.holders.Holder; import java.util.Date; /** * Class DateHolder * */ public final class DateHolder implements Holder { /** Field _value */ public Date value; /** * Constructor DateHolder */ public DateHolder() { } /** * Constructor DateHolder * * @param value */ public DateHolder(Date value) { this.value = value; } }
7,357
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/NegativeIntegerHolder.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.holders; import org.apache.axis.types.NegativeInteger; import javax.xml.rpc.holders.Holder; /** * Class NegativeIntegerHolder * */ public final class NegativeIntegerHolder implements Holder { /** Field _value */ public NegativeInteger value; /** * Constructor NegativeIntegerHolder */ public NegativeIntegerHolder() { } /** * Constructor NegativeIntegerHolder * * @param value */ public NegativeIntegerHolder(NegativeInteger value) { this.value = value; } }
7,358
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/MonthDayHolder.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.holders; import org.apache.axis.types.MonthDay; import javax.xml.rpc.holders.Holder; /** * Class MonthDayHolder * */ public final class MonthDayHolder implements Holder { /** Field _value */ public MonthDay value; /** * Constructor MonthDayHolder */ public MonthDayHolder() { } /** * Constructor MonthDayHolder * * @param value */ public MonthDayHolder(MonthDay value) { this.value = value; } }
7,359
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/OctetStreamHolder.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.holders; import org.apache.axis.attachments.OctetStream; import javax.xml.rpc.holders.Holder; /** * Class OctetStreamHolder * */ public final class OctetStreamHolder implements Holder { /** Field _value */ public OctetStream value; /** * Constructor OctetStreamHolder */ public OctetStreamHolder() { } /** * Constructor OctetStreamHolder * * @param value */ public OctetStreamHolder(org.apache.axis.attachments.OctetStream value) { this.value = value; } }
7,360
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/MonthHolder.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.holders; import org.apache.axis.types.Month; import javax.xml.rpc.holders.Holder; /** * Class MonthHolder * */ public final class MonthHolder implements Holder { /** Field _value */ public Month value; /** * Constructor MonthHolder */ public MonthHolder() { } /** * Constructor MonthHolder * * @param value */ public MonthHolder(Month value) { this.value = value; } }
7,361
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/TimeHolder.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.holders; import org.apache.axis.types.Time; import javax.xml.rpc.holders.Holder; /** * Class TimeHolder * */ public final class TimeHolder implements Holder { /** Field _value */ public Time value; /** * Constructor TimeHolder */ public TimeHolder() { } /** * Constructor TimeHolder * * @param value */ public TimeHolder(Time value) { this.value = value; } }
7,362
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/URIHolder.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.holders; import org.apache.axis.types.URI; import javax.xml.rpc.holders.Holder; /** * Class URIHolder * */ public final class URIHolder implements Holder { /** Field _value */ public URI value; /** * Constructor URIHolder */ public URIHolder() { } /** * Constructor URIHolder * * @param value */ public URIHolder(URI value) { this.value = value; } }
7,363
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/MimeMultipartHolder.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.holders; import javax.mail.internet.MimeMultipart; import javax.xml.rpc.holders.Holder; /** * Class MimeMultipartHolder * * @version 1.0 */ public final class MimeMultipartHolder implements Holder { /** Field _value */ public MimeMultipart value; /** * Constructor MimeMultipartHolder */ public MimeMultipartHolder() {} /** * Constructor MimeMultipartHolder * * @param value */ public MimeMultipartHolder(MimeMultipart value) { this.value = value; } }
7,364
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/UnsignedIntHolder.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.holders; import org.apache.axis.types.UnsignedInt; import javax.xml.rpc.holders.Holder; /** * Class UnsignedIntHolder * */ public final class UnsignedIntHolder implements Holder { /** Field _value */ public UnsignedInt value; /** * Constructor UnsignedIntHolder */ public UnsignedIntHolder() { } /** * Constructor UnsignedIntHolder * * @param value */ public UnsignedIntHolder(UnsignedInt value) { this.value = value; } }
7,365
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/DurationHolder.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.holders; import org.apache.axis.types.Duration; import javax.xml.rpc.holders.Holder; /** * Class DurationHolder * */ public final class DurationHolder implements Holder { /** Field _value */ public Duration value; /** * Constructor DurationHolder */ public DurationHolder() { } /** * Constructor DurationHolder * * @param value */ public DurationHolder(Duration value) { this.value = value; } }
7,366
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/DayHolder.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.holders; import org.apache.axis.types.Day; import javax.xml.rpc.holders.Holder; /** * Class DayHolder * */ public final class DayHolder implements Holder { /** Field _value */ public Day value; /** * Constructor DayHolder */ public DayHolder() { } /** * Constructor DayHolder * * @param value */ public DayHolder(Day value) { this.value = value; } }
7,367
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/NormalizedStringHolder.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.holders; import org.apache.axis.types.NormalizedString; import javax.xml.rpc.holders.Holder; /** * Class NormalizedStringHolder * */ public final class NormalizedStringHolder implements Holder { /** Field _value */ public NormalizedString value; /** * Constructor NormalizedStringHolder */ public NormalizedStringHolder() { } /** * Constructor NormalizedStringHolder * * @param value */ public NormalizedStringHolder(NormalizedString value) { this.value = value; } }
7,368
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/NonPositiveIntegerHolder.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.holders; import org.apache.axis.types.NonPositiveInteger; import javax.xml.rpc.holders.Holder; /** * Class NonPositiveIntegerHolder * */ public final class NonPositiveIntegerHolder implements Holder { /** Field _value */ public NonPositiveInteger value; /** * Constructor NonPositiveIntegerHolder */ public NonPositiveIntegerHolder() { } /** * Constructor NonPositiveIntegerHolder * * @param value */ public NonPositiveIntegerHolder(NonPositiveInteger value) { this.value = value; } }
7,369
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/holders/TokenHolder.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.holders; import org.apache.axis.types.Token; import javax.xml.rpc.holders.Holder; /** * Class TokenHolder * */ public final class TokenHolder implements Holder { /** Field _value */ public Token value; /** * Constructor TokenHolder */ public TokenHolder() { } /** * Constructor NormalizedTokenHolderStringHolder * * @param value */ public TokenHolder(Token value) { this.value = value; } }
7,370
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Duration.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.util.Calendar; /** * Implementation of the XML Schema type duration. Duration supports a minimum * fractional second precision of milliseconds. * * @author Wes Moulder (wes@themindelectric.com) * @author Dominik Kacprzak (dominik@opentoolbox.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#duration">XML Schema 3.2.6</a> */ public class Duration implements java.io.Serializable { boolean isNegative = false; int years; int months; int days; int hours; int minutes; double seconds; /** * Default no-arg constructor */ public Duration() { } /** * @param negative * @param aYears * @param aMonths * @param aDays * @param aHours * @param aMinutes * @param aSeconds */ public Duration(boolean negative, int aYears, int aMonths, int aDays, int aHours, int aMinutes, double aSeconds) { isNegative = negative; years = aYears; months = aMonths; days = aDays; hours = aHours; minutes = aMinutes; setSeconds(aSeconds); } /** * Constructs Duration from a String in an xsd:duration format - * PnYnMnDTnHnMnS. * * @param duration String * @throws IllegalArgumentException if the string doesn't parse correctly. */ public Duration(String duration) throws IllegalArgumentException { int position = 1; int timePosition = duration.indexOf("T"); // P is required but P by itself is invalid if (duration.indexOf("P") == -1 || duration.equals("P")) { throw new IllegalArgumentException( Messages.getMessage("badDuration")); } // if present, time cannot be empty if (duration.lastIndexOf("T") == duration.length() - 1) { throw new IllegalArgumentException( Messages.getMessage("badDuration")); } // check the sign if (duration.startsWith("-")) { isNegative = true; position++; } // parse time part if (timePosition != -1) { parseTime(duration.substring(timePosition + 1)); } else { timePosition = duration.length(); } // parse date part if (position != timePosition) { parseDate(duration.substring(position, timePosition)); } } /** * Constructs Duration from a Calendar. * * @param calendar Calendar * @throws IllegalArgumentException if the calendar object does not * represent any date nor time. */ public Duration(boolean negative, Calendar calendar) throws IllegalArgumentException { this.isNegative = negative; this.years = calendar.get(Calendar.YEAR); this.months = calendar.get(Calendar.MONTH); this.days = calendar.get(Calendar.DATE); this.hours = calendar.get(Calendar.HOUR); this.minutes = calendar.get(Calendar.MINUTE); this.seconds = calendar.get(Calendar.SECOND); this.seconds += ((double) calendar.get(Calendar.MILLISECOND)) / 100; if (years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) { throw new IllegalArgumentException(Messages.getMessage( "badCalendarForDuration")); } } /** * This method parses the time portion of a String that represents * xsd:duration - nHnMnS. * * @param time * @throws IllegalArgumentException if time does not match pattern * */ public void parseTime(String time) throws IllegalArgumentException { if (time.length() == 0 || time.indexOf("-") != -1) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } // check if time ends with either H, M, or S if (!time.endsWith("H") && !time.endsWith("M") && !time.endsWith("S")) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } try { // parse string and extract hours, minutes, and seconds int start = 0; // Hours int end = time.indexOf("H"); // if there is H in a string but there is no value for hours, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } if (end != -1) { hours = Integer.parseInt(time.substring(0, end)); start = end + 1; } // Minutes end = time.indexOf("M"); // if there is M in a string but there is no value for hours, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } if (end != -1) { minutes = Integer.parseInt(time.substring(start, end)); start = end + 1; } // Seconds end = time.indexOf("S"); // if there is S in a string but there is no value for hours, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } if (end != -1) { setSeconds(Double.parseDouble(time.substring(start, end))); } } catch (NumberFormatException e) { throw new IllegalArgumentException( Messages.getMessage("badTimeDuration")); } } /** * This method parses the date portion of a String that represents * xsd:duration - nYnMnD. * * @param date * @throws IllegalArgumentException if date does not match pattern * */ public void parseDate(String date) throws IllegalArgumentException { if (date.length() == 0 || date.indexOf("-") != -1) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } // check if date string ends with either Y, M, or D if (!date.endsWith("Y") && !date.endsWith("M") && !date.endsWith("D")) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } // catch any parsing exception try { // parse string and extract years, months, days int start = 0; int end = date.indexOf("Y"); // if there is Y in a string but there is no value for years, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } if (end != -1) { years = Integer.parseInt(date.substring(0, end)); start = end + 1; } // months end = date.indexOf("M"); // if there is M in a string but there is no value for months, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } if (end != -1) { months = Integer.parseInt(date.substring(start, end)); start = end + 1; } end = date.indexOf("D"); // if there is D in a string but there is no value for days, // throw an exception if (start == end) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } if (end != -1) { days = Integer.parseInt(date.substring(start, end)); } } catch (NumberFormatException e) { throw new IllegalArgumentException( Messages.getMessage("badDateDuration")); } } /** * */ public boolean isNegative() { return isNegative; } /** * */ public int getYears() { return years; } /** * */ public int getMonths() { return months; } /** * */ public int getDays() { return days; } /** * */ public int getHours() { return hours; } /** * */ public int getMinutes() { return minutes; } /** * */ public double getSeconds() { return seconds; } /** * @param negative */ public void setNegative(boolean negative) { isNegative = negative; } /** * @param years */ public void setYears(int years) { this.years = years; } /** * @param months */ public void setMonths(int months) { this.months = months; } /** * @param days */ public void setDays(int days) { this.days = days; } /** * @param hours */ public void setHours(int hours) { this.hours = hours; } /** * @param minutes */ public void setMinutes(int minutes) { this.minutes = minutes; } /** * @param seconds * @deprecated use {@link #setSeconds(double) setSeconds(double)} * instead */ public void setSeconds(int seconds) { this.seconds = seconds; } /** * Sets the seconds. NOTE: The fractional value of seconds is rounded up to * milliseconds. * * @param seconds double */ public void setSeconds(double seconds) { this.seconds = ((double) (Math.round(seconds * 100))) / 100; } /** * This returns the xml representation of an xsd:duration object. */ public String toString() { StringBuffer duration = new StringBuffer(); duration.append("P"); if (years != 0) { duration.append(years + "Y"); } if (months != 0) { duration.append(months + "M"); } if (days != 0) { duration.append(days + "D"); } if (hours != 0 || minutes != 0 || seconds != 0.0) { duration.append("T"); if (hours != 0) { duration.append(hours + "H"); } if (minutes != 0) { duration.append(minutes + "M"); } if (seconds != 0) { if (seconds == (int) seconds) { duration.append((int) seconds + "S"); } else { duration.append(seconds + "S"); } } } if (duration.length() == 1) { duration.append("T0S"); } if (isNegative) { duration.insert(0, "-"); } return duration.toString(); } /** * The equals method compares the time represented by duration object, not * its string representation. * Hence, a duration object representing 65 minutes is considered equal to a * duration object representing 1 hour and 5 minutes. * * @param object */ public boolean equals(Object object) { if (!(object instanceof Duration)) { return false; } Calendar thisCalendar = this.getAsCalendar(); Duration duration = (Duration) object; return this.isNegative == duration.isNegative && this.getAsCalendar().equals(duration.getAsCalendar()); } public int hashCode() { int hashCode = 0; if (isNegative) { hashCode++; } hashCode += years; hashCode += months; hashCode += days; hashCode += hours; hashCode += minutes; hashCode += seconds; // milliseconds hashCode += (seconds * 100) % 100; return hashCode; } /** * Returns duration as a calendar. Due to the way a Calendar class works, * the values for particular fields may not be the same as obtained through * getter methods. For example, if a duration's object getMonths * returns 20, a similar call on a calendar object will return 1 year and * 8 months. * * @return Calendar */ public Calendar getAsCalendar() { return getAsCalendar(Calendar.getInstance()); } /** * Returns duration as a calendar. Due to the way a Calendar class works, * the values for particular fields may not be the same as obtained through * getter methods. For example, if a Duration's object getMonths * returns 20, a similar call on a Calendar object will return 1 year and * 8 months. * * @param startTime Calendar * @return Calendar */ public Calendar getAsCalendar(Calendar startTime) { Calendar ret = (Calendar) startTime.clone(); ret.set(Calendar.YEAR, years); ret.set(Calendar.MONTH, months); ret.set(Calendar.DATE, days); ret.set(Calendar.HOUR, hours); ret.set(Calendar.MINUTE, minutes); ret.set(Calendar.SECOND, (int) seconds); ret.set(Calendar.MILLISECOND, (int) (seconds * 100 - Math.round(seconds) * 100)); return ret; } }
7,371
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Id.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting XSD data type ID * The base type of Id is NCName. * * @author Eddie Pick (eddie@pick.eu.org) * @see <a href="http://www.w3.org/TR/xmlschema-2/#ID">XML Schema 3.3.8</a> */ public class Id extends NCName { public Id() { super(); } /** * ctor for Id * @exception IllegalArgumentException will be thrown if validation fails */ public Id(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badIdType00") + "data=[" + stValue + "]"); } } /** * * validates the data and sets the value for the object. * @param stValue String value * @throws IllegalArgumentException if invalid format */ public void setValue(String stValue) throws IllegalArgumentException { if (Id.isValid(stValue) == false) throw new IllegalArgumentException( Messages.getMessage("badIdType00") + " data=[" + stValue + "]"); m_value = stValue; } /** * * validate the value against the xsd definition * * Same validation as NCName for the time being */ public static boolean isValid(String stValue) { return NCName.isValid(stValue); } }
7,372
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/IDRef.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; /** * Custom class for supporting XSD data type IDRef * * @author Davanum Srinivas (dims@yahoo.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#IDREF">XML Schema 3.3.10 IDREFS</a> */ public class IDRef extends NCName { public IDRef() { super(); } /** * ctor for IDRef * @exception IllegalArgumentException will be thrown if validation fails */ public IDRef (String stValue) throws IllegalArgumentException { super(stValue); } }
7,373
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Schema.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; /** * Custom class for supporting XSD schema * * @author Davanum Srinivas (dims@yahoo.com) */ public class Schema implements java.io.Serializable { private org.apache.axis.message.MessageElement[] _any; private org.apache.axis.types.URI targetNamespace; // attribute private org.apache.axis.types.NormalizedString version; // attribute private org.apache.axis.types.Id id; // attribute public Schema() { } public org.apache.axis.message.MessageElement[] get_any() { return _any; } public void set_any(org.apache.axis.message.MessageElement[] _any) { this._any = _any; } public org.apache.axis.types.URI getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(org.apache.axis.types.URI targetNamespace) { this.targetNamespace = targetNamespace; } public org.apache.axis.types.NormalizedString getVersion() { return version; } public void setVersion(org.apache.axis.types.NormalizedString version) { this.version = version; } public org.apache.axis.types.Id getId() { return id; } public void setId(org.apache.axis.types.Id id) { this.id = id; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Schema)) return false; Schema other = (Schema) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((_any == null && other.get_any() == null) || (_any != null && java.util.Arrays.equals(_any, other.get_any()))) && ((targetNamespace == null && other.getTargetNamespace() == null) || (targetNamespace != null && targetNamespace.equals(other.getTargetNamespace()))) && ((version == null && other.getVersion() == null) || (version != null && version.equals(other.getVersion()))) && ((id == null && other.getId() == null) || (id != null && id.equals(other.getId()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (get_any() != null) { for (int i = 0; i < java.lang.reflect.Array.getLength(get_any()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(get_any(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getTargetNamespace() != null) { _hashCode += getTargetNamespace().hashCode(); } if (getVersion() != null) { _hashCode += getVersion().hashCode(); } if (getId() != null) { _hashCode += getId().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Schema.class); static { org.apache.axis.description.FieldDesc field = new org.apache.axis.description.AttributeDesc(); field.setFieldName("targetNamespace"); field.setXmlName(new javax.xml.namespace.QName("", "targetNamespace")); field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "anyURI")); typeDesc.addFieldDesc(field); field = new org.apache.axis.description.AttributeDesc(); field.setFieldName("version"); field.setXmlName(new javax.xml.namespace.QName("", "version")); field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "normalizedString")); typeDesc.addFieldDesc(field); field = new org.apache.axis.description.AttributeDesc(); field.setFieldName("id"); field.setXmlName(new javax.xml.namespace.QName("", "id")); field.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "ID")); typeDesc.addFieldDesc(field); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
7,374
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/UnsignedByte.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting primitive XSD data type UnsignedByte * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#unsignedByte">XML Schema 3.3.24</a> */ public class UnsignedByte extends UnsignedShort { public UnsignedByte() { } /** * ctor for UnsignedByte * @exception NumberFormatException will be thrown if validation fails */ public UnsignedByte(long sValue) throws NumberFormatException { setValue(sValue); } public UnsignedByte(String sValue) throws NumberFormatException { setValue(Long.parseLong(sValue)); } /** * * validates the data and sets the value for the object. * * @param sValue the number to set */ public void setValue(long sValue) throws NumberFormatException { if (UnsignedByte.isValid(sValue) == false) throw new NumberFormatException( Messages.getMessage("badUnsignedByte00") + String.valueOf(sValue) + "]"); lValue = new Long(sValue); } /** * * validate the value against the xsd value space definition * @param sValue number to check against range */ public static boolean isValid(long sValue) { if ( (sValue < 0L ) || (sValue > 255L) ) return false; else return true; } }
7,375
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NMToken.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLChar; /** * Custom class for supporting XSD data type NMToken * * NMTOKEN represents the NMTOKEN attribute type from * [XML 1.0(Second Edition)]. The value space of NMTOKEN * is the set of tokens that match the Nmtoken production * in [XML 1.0 (Second Edition)]. * The base type of NMTOKEN is token. * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#nmtoken">XML Schema 3.3.4</a> */ public class NMToken extends Token { public NMToken() { super(); } /** * ctor for NMToken * @exception IllegalArgumentException will be thrown if validation fails */ public NMToken(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badNmtoken00") + "data=[" + stValue + "]"); } } /** * * validate the value against the xsd definition * Nmtoken ::= (NameChar)+ * NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */ public static boolean isValid(String stValue) { int scan; for (scan=0; scan < stValue.length(); scan++) { if (XMLChar.isName(stValue.charAt(scan)) == false) return false; } return true; } }
7,376
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Day.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.text.NumberFormat; /** * Implementation of the XML Schema type gDay * * @author Tom Jordahl (tomj@macromedia.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#gDay">XML Schema 3.2.13</a> */ public class Day implements java.io.Serializable { int day; String timezone = null; /** * Constructs a Day with the given values * No timezone is specified */ public Day(int day) throws NumberFormatException { setValue(day); } /** * Constructs a Day with the given values, including a timezone string * The timezone is validated but not used. */ public Day(int day, String timezone) throws NumberFormatException { setValue(day, timezone); } /** * Construct a Day from a String in the format ---DD[timezone] */ public Day(String source) throws NumberFormatException { if (source.length() < 5) { throw new NumberFormatException( Messages.getMessage("badDay00")); } if (source.charAt(0) != '-' || source.charAt(1) != '-' || source.charAt(2) != '-' ) { throw new NumberFormatException( Messages.getMessage("badDay00")); } setValue(Integer.parseInt(source.substring(3,5)), source.substring(5)); } public int getDay() { return day; } /** * Set the day */ public void setDay(int day) { // validate day if (day < 1 || day > 31) { throw new NumberFormatException( Messages.getMessage("badDay00")); } this.day = day; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { // validate timezone if (timezone != null && timezone.length() > 0) { // Format [+/-]HH:MM if (timezone.charAt(0)=='+' || (timezone.charAt(0)=='-')) { if (timezone.length() != 6 || !Character.isDigit(timezone.charAt(1)) || !Character.isDigit(timezone.charAt(2)) || timezone.charAt(3) != ':' || !Character.isDigit(timezone.charAt(4)) || !Character.isDigit(timezone.charAt(5))) throw new NumberFormatException( Messages.getMessage("badTimezone00")); } else if (!timezone.equals("Z")) { throw new NumberFormatException( Messages.getMessage("badTimezone00")); } // if we got this far, its good this.timezone = timezone; } } public void setValue(int day, String timezone) throws NumberFormatException { setDay(day); setTimezone(timezone); } public void setValue(int day) throws NumberFormatException { setDay(day); } public String toString() { // use NumberFormat to ensure leading zeros NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); // Day nf.setMinimumIntegerDigits(2); String s = "---" + nf.format(day); // timezone if (timezone != null) { s = s + timezone; } return s; } public boolean equals(Object obj) { if (!(obj instanceof Day)) return false; Day other = (Day) obj; if (obj == null) return false; if (this == obj) return true; boolean equals = (this.day == other.day); if (timezone != null) { equals = equals && timezone.equals(other.timezone); } return equals; } /** * Return the value of day XORed with the hashCode of timezone * iff one is defined. * * @return an <code>int</code> value */ public int hashCode() { return null == timezone ? day : day ^ timezone.hashCode(); } }
7,377
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/UnsignedLong.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.math.BigInteger; /** * Custom class for supporting primitive XSD data type UnsignedLong * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#unsignedLong">XML Schema 3.3.21</a> */ public class UnsignedLong extends java.lang.Number implements java.lang.Comparable { protected BigInteger lValue = BigInteger.ZERO; private static BigInteger MAX = new BigInteger("18446744073709551615"); // max unsigned long public UnsignedLong() { } public UnsignedLong(double value) throws NumberFormatException { setValue(new BigInteger(Double.toString(value))); } public UnsignedLong(BigInteger value) throws NumberFormatException { setValue(value); } public UnsignedLong(long lValue) throws NumberFormatException { setValue(BigInteger.valueOf(lValue)); } public UnsignedLong(String stValue) throws NumberFormatException { setValue(new BigInteger(stValue)); } private void setValue(BigInteger val) { if (!UnsignedLong.isValid(val)) { throw new NumberFormatException(Messages.getMessage( "badUnsignedLong00") + String.valueOf(val) + "]"); } this.lValue = val; } public static boolean isValid(BigInteger value) { if (value.compareTo(BigInteger.ZERO) == -1 || // less than zero value.compareTo(MAX) == 1) { return false; } return true; } public String toString() { return lValue.toString(); } public int hashCode() { if (lValue != null) return lValue.hashCode(); else return 0; } private Object __equalsCalc = null; public synchronized boolean equals(Object obj) { if (!(obj instanceof UnsignedLong)) return false; UnsignedLong other = (UnsignedLong) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((lValue == null && other.lValue == null) || (lValue != null && lValue.equals(other.lValue))); __equalsCalc = null; return _equals; } // implement java.lang.comparable interface public int compareTo(Object obj) { if (lValue != null) return lValue.compareTo(obj); else if (equals(obj) == true) return 0; // null == null else return 1; // object is greater } // Implement java.lang.Number interface public byte byteValue() { return lValue.byteValue(); } public short shortValue() { return lValue.shortValue(); } public int intValue() { return lValue.intValue(); } public long longValue() { return lValue.longValue(); } public double doubleValue() { return lValue.doubleValue(); } public float floatValue() { return lValue.floatValue(); } }
7,378
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NonPositiveInteger.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.math.BigInteger; import java.util.Random; import java.io.ObjectStreamException; /** * Custom class for supporting primitive XSD data type nonPositiveInteger * * nonPositiveInteger is derived from integer by setting the value of * maxInclusive to be 0. This results in the standard mathematical * concept of the non-positive integers. The value space of * nonPositiveInteger is the infinite set {...,-2,-1,0}. * * @author Chris Haddad (haddadc@apache.org) * @see <a href="http://www.w3.org/TR/xmlschema-2/#nonPositiveInteger">XML Schema 3.3.14</a> */ public class NonPositiveInteger extends BigInteger { public NonPositiveInteger(byte[] val) { super(val); checkValidity(); } // ctor public NonPositiveInteger(int signum, byte[] magnitude) { super(signum, magnitude); checkValidity(); } // ctor public NonPositiveInteger(int bitLength, int certainty, Random rnd) { super(bitLength, certainty, rnd); checkValidity(); } // ctor public NonPositiveInteger(int numBits, Random rnd) { super(numBits, rnd); checkValidity(); } // ctor public NonPositiveInteger(String val) { super(val); checkValidity(); } public NonPositiveInteger(String val, int radix) { super(val, radix); checkValidity(); } // ctor /** * validate the value against the xsd definition */ private BigInteger zero = new BigInteger("0"); private void checkValidity() { if (compareTo(zero) > 0) { throw new NumberFormatException( Messages.getMessage("badNonPosInt00") + ": " + this); } } // checkValidity /** * Work-around for http://developer.java.sun.com/developer/bugParade/bugs/4378370.html * @return BigIntegerRep * @throws java.io.ObjectStreamException */ public Object writeReplace() throws ObjectStreamException { return new BigIntegerRep(toByteArray()); } protected static class BigIntegerRep implements java.io.Serializable { private byte[] array; protected BigIntegerRep(byte[] array) { this.array = array; } protected Object readResolve() throws java.io.ObjectStreamException { return new NonPositiveInteger(array); } } } // class NonPositiveInteger
7,379
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Time.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Class that represents the xsd:time XML Schema type */ public class Time implements java.io.Serializable { private Calendar _value; /** * a shared java.text.SimpleDateFormat instance used for parsing the basic * component of the timestamp */ private static SimpleDateFormat zulu = new SimpleDateFormat("HH:mm:ss.SSS'Z'"); // We should always format dates in the GMT timezone static { zulu.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * Initialize with a Calender, year month and date are ignored */ public Time(Calendar value) { this._value = value; _value.set(0,0,0); // ignore year, month, date } /** * Converts a string formatted as HH:mm:ss[.SSS][+/-offset] */ public Time(String value) throws NumberFormatException { _value = makeValue(value); } /** * return the time as a calendar: ignore the year, month and date fields * @return calendar value; may be null */ public Calendar getAsCalendar() { return _value; } /** * set the time; ignore year, month, date * @param date */ public void setTime(Calendar date) { this._value = date; _value.set(0,0,0); // ignore year, month, date } /** * set the time from a date instance * @param date */ public void setTime(Date date) { _value.setTime(date); _value.set(0,0,0); // ignore year, month, date } /** * Utility function that parses xsd:time strings and returns a Date object */ private Calendar makeValue(String source) throws NumberFormatException { Calendar calendar = Calendar.getInstance(); Date date; validateSource(source); // convert what we have validated so far date = ParseHoursMinutesSeconds(source); int pos = 8; // The "." in hh:mm:ss.sss // parse optional milliseconds if ( source != null ) { if (pos < source.length() && source.charAt(pos)=='.') { int milliseconds = 0; int start = ++pos; while (pos<source.length() && Character.isDigit(source.charAt(pos))) { pos++; } String decimal=source.substring(start,pos); if (decimal.length()==3) { milliseconds=Integer.parseInt(decimal); } else if (decimal.length() < 3) { milliseconds=Integer.parseInt((decimal+"000") .substring(0,3)); } else { milliseconds=Integer.parseInt(decimal.substring(0,3)); if (decimal.charAt(3)>='5') { ++milliseconds; } } // add milliseconds to the current date date.setTime(date.getTime()+milliseconds); } // parse optional timezone if (pos+5 < source.length() && (source.charAt(pos)=='+' || (source.charAt(pos)=='-'))) { if (!Character.isDigit(source.charAt(pos+1)) || !Character.isDigit(source.charAt(pos+2)) || source.charAt(pos+3) != ':' || !Character.isDigit(source.charAt(pos+4)) || !Character.isDigit(source.charAt(pos+5))) { throw new NumberFormatException( Messages.getMessage("badTimezone00")); } int hours = (source.charAt(pos+1)-'0')*10 +source.charAt(pos+2)-'0'; int mins = (source.charAt(pos+4)-'0')*10 +source.charAt(pos+5)-'0'; int milliseconds = (hours*60+mins)*60*1000; // subtract milliseconds from current date to obtain GMT if (source.charAt(pos)=='+') { milliseconds=-milliseconds; } date.setTime(date.getTime()+milliseconds); pos+=6; } if (pos < source.length() && source.charAt(pos)=='Z') { pos++; calendar.setTimeZone(TimeZone.getTimeZone("GMT")); } if (pos < source.length()) { throw new NumberFormatException( Messages.getMessage("badChars00")); } } calendar.setTime(date); calendar.set(0,0,0); // ignore year, month, date return calendar; } private int getTimezoneNumberValue(char c) { int n=c-'0'; if(n<0 || n>9) { //oops, out of range throw new NumberFormatException( Messages.getMessage("badTimezone00")); } return n; } /** * parse the hours, minutes and seconds of a string, by handing it off to * the java runtime. * The relevant code will return null if a null string is passed in, so this * code may return a null date in response * @param source * @return * @throws NumberFormatException in the event of trouble */ private static Date ParseHoursMinutesSeconds(String source) { Date date; try { synchronized (zulu) { String fulltime = source == null ? null : (source.substring(0,8)+".000Z"); date = zulu.parse(fulltime); } } catch (Exception e) { throw new NumberFormatException(e.toString()); } return date; } /** * validate the source * @param source */ private void validateSource(String source) { // validate fixed portion of format if ( source != null ) { if (source.charAt(2) != ':' || source.charAt(5) != ':') { throw new NumberFormatException( Messages.getMessage("badTime00")); } if (source.length() < 8) { throw new NumberFormatException( Messages.getMessage("badTime00")); } } } /** * stringify method returns the time as it would be in GMT, only accurate to the * second...millis probably get lost. * @return */ public String toString() { if(_value==null) { return "unassigned Time"; } synchronized (zulu) { return zulu.format(_value.getTime()); } } public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Time)) return false; Time other = (Time) obj; if (this == obj) return true; boolean _equals; _equals = true && ((_value ==null && other._value ==null) || (_value !=null && _value.getTime().equals(other._value.getTime()))); return _equals; } /** * Returns the hashcode of the underlying calendar. * * @return an <code>int</code> value */ public int hashCode() { return _value == null ? 0 : _value.hashCode(); } }
7,380
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Entities.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import java.util.StringTokenizer; /** * Custom class for supporting XSD data type Entities * * @author Davanum Srinivas (dims@yahoo.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#ENTITIES">XML Schema 3.3.12 ENTITIES</a> */ public class Entities extends NCName { private Entity[] entities; public Entities() { super(); } /** * ctor for Entities * @exception IllegalArgumentException will be thrown if validation fails */ public Entities (String stValue) throws IllegalArgumentException { StringTokenizer tokenizer = new StringTokenizer(stValue); int count = tokenizer.countTokens(); entities = new Entity[count]; for(int i=0;i<count;i++){ entities[i] = new Entity(tokenizer.nextToken()); } } }
7,381
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/YearMonth.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.text.NumberFormat; /** * Implementation of the XML Schema type gYearMonth * * @author Tom Jordahl (tomj@macromedia.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#gYearMonth">XML Schema 3.2.10</a> */ public class YearMonth implements java.io.Serializable { int year; int month; String timezone = null; /** * Constructs a YearMonth with the given values * No timezone is specified */ public YearMonth(int year, int month) throws NumberFormatException { setValue(year, month); } /** * Constructs a YearMonth with the given values, including a timezone string * The timezone is validated but not used. */ public YearMonth(int year, int month, String timezone) throws NumberFormatException { setValue(year, month, timezone); } /** * Construct a YearMonth from a String in the format [-]CCYY-MM */ public YearMonth(String source) throws NumberFormatException { int negative = 0; if (source.charAt(0) == '-') { negative = 1; } if (source.length() < (7 + negative)) { throw new NumberFormatException( Messages.getMessage("badYearMonth00")); } // look for first '-' int pos = source.substring(negative).indexOf('-'); if (pos < 0) { throw new NumberFormatException( Messages.getMessage("badYearMonth00")); } if (negative > 0) pos++; //adjust index for orginal string setValue(Integer.parseInt(source.substring(0,pos)), Integer.parseInt(source.substring(pos+1,pos+3)), source.substring(pos+3)); } public int getYear() { return year; } public void setYear(int year) { // validate year, more than 4 digits are allowed! if (year == 0) { throw new NumberFormatException( Messages.getMessage("badYearMonth00")); } this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { // validate month if (month < 1 || month > 12) { throw new NumberFormatException( Messages.getMessage("badYearMonth00")); } this.month = month; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { // validate timezone if (timezone != null && timezone.length() > 0) { // Format [+/-]HH:MM if (timezone.charAt(0)=='+' || (timezone.charAt(0)=='-')) { if (timezone.length() != 6 || !Character.isDigit(timezone.charAt(1)) || !Character.isDigit(timezone.charAt(2)) || timezone.charAt(3) != ':' || !Character.isDigit(timezone.charAt(4)) || !Character.isDigit(timezone.charAt(5))) throw new NumberFormatException( Messages.getMessage("badTimezone00")); } else if (!timezone.equals("Z")) { throw new NumberFormatException( Messages.getMessage("badTimezone00")); } // if we got this far, its good this.timezone = timezone; } } public void setValue(int year, int month, String timezone) throws NumberFormatException { setYear(year); setMonth(month); setTimezone(timezone); } public void setValue(int year, int month) throws NumberFormatException { setYear(year); setMonth(month); } public String toString() { // use NumberFormat to ensure leading zeros NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); // year nf.setMinimumIntegerDigits(4); String s = nf.format(year) + "-"; // month nf.setMinimumIntegerDigits(2); s += nf.format(month); // timezone if (timezone != null) { s = s + timezone; } return s; } public boolean equals(Object obj) { if (!(obj instanceof YearMonth)) return false; YearMonth other = (YearMonth) obj; if (obj == null) return false; if (this == obj) return true; boolean equals = (this.year == other.year && this.month == other.month); if (timezone != null) { equals = equals && timezone.equals(other.timezone); } return equals; } /** * Return the value of (month + year) XORed with the hashCode of * timezone iff one is defined. * * @return an <code>int</code> value */ public int hashCode() { return null == timezone ? (month + year) : (month + year) ^ timezone.hashCode(); } }
7,382
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NonNegativeInteger.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.io.ObjectStreamException; import java.math.BigInteger; import java.util.Random; /** * Custom class for supporting primitive XSD data type nonNegativeInteger * * @author Russell Butek (butek@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#nonNegativeInteger">XML Schema 3.3.20</a> */ public class NonNegativeInteger extends BigInteger { public NonNegativeInteger(byte[] val) { super(val); checkValidity(); } // ctor public NonNegativeInteger(int signum, byte[] magnitude) { super(signum, magnitude); checkValidity(); } // ctor public NonNegativeInteger(int bitLength, int certainty, Random rnd) { super(bitLength, certainty, rnd); checkValidity(); } // ctor public NonNegativeInteger(int numBits, Random rnd) { super(numBits, rnd); checkValidity(); } // ctor public NonNegativeInteger(String val) { super(val); checkValidity(); } public NonNegativeInteger(String val, int radix) { super(val, radix); checkValidity(); } // ctor /** * validate the value against the xsd definition */ private BigInteger zero = new BigInteger("0"); private void checkValidity() { if (compareTo(zero) < 0) { throw new NumberFormatException( Messages.getMessage("badNonNegInt00") + ": " + this); } } // checkValidity /** * Work-around for http://developer.java.sun.com/developer/bugParade/bugs/4378370.html * @return BigIntegerRep * @throws ObjectStreamException */ public Object writeReplace() throws ObjectStreamException { return new BigIntegerRep(toByteArray()); } protected static class BigIntegerRep implements java.io.Serializable { private byte[] array; protected BigIntegerRep(byte[] array) { this.array = array; } protected Object readResolve() throws java.io.ObjectStreamException { return new NonNegativeInteger(array); } } } // class NonNegativeInteger
7,383
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Year.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.text.NumberFormat; /** * Implementation of the XML Schema type gYear * * @author Tom Jordahl (tomj@macromedia.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#gYear">XML Schema 3.2.11</a> */ public class Year implements java.io.Serializable { int year; String timezone = null; /** * Constructs a Year with the given values * No timezone is specified */ public Year(int year) throws NumberFormatException { setValue(year); } /** * Constructs a Year with the given values, including a timezone string * The timezone is validated but not used. */ public Year(int year, String timezone) throws NumberFormatException { setValue(year, timezone); } /** * Construct a Year from a String in the format [-]CCYY[timezone] */ public Year(String source) throws NumberFormatException { int negative = 0; if (source.charAt(0) == '-') { negative = 1; } if (source.length() < (4 + negative)) { throw new NumberFormatException( Messages.getMessage("badYear00")); } // calculate how many more than 4 digits (if any) in the year int pos = 4 + negative; // skip minus sign if present while (pos < source.length() && Character.isDigit(source.charAt(pos))) { ++pos; } setValue(Integer.parseInt(source.substring(0,pos)), source.substring(pos)); } public int getYear() { return year; } public void setYear(int year) { // validate year, more than 4 digits are allowed! if (year == 0) { throw new NumberFormatException( Messages.getMessage("badYear00")); } this.year = year; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { // validate timezone if (timezone != null && timezone.length() > 0) { // Format [+/-]HH:MM if (timezone.charAt(0)=='+' || (timezone.charAt(0)=='-')) { if (timezone.length() != 6 || !Character.isDigit(timezone.charAt(1)) || !Character.isDigit(timezone.charAt(2)) || timezone.charAt(3) != ':' || !Character.isDigit(timezone.charAt(4)) || !Character.isDigit(timezone.charAt(5))) throw new NumberFormatException( Messages.getMessage("badTimezone00")); } else if (!timezone.equals("Z")) { throw new NumberFormatException( Messages.getMessage("badTimezone00")); } // if we got this far, its good this.timezone = timezone; } } public void setValue(int year, String timezone) throws NumberFormatException { setYear(year); setTimezone(timezone); } public void setValue(int year) throws NumberFormatException { setYear(year); } public String toString() { // use NumberFormat to ensure leading zeros NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); // year nf.setMinimumIntegerDigits(4); String s = nf.format(year); // timezone if (timezone != null) { s = s + timezone; } return s; } public boolean equals(Object obj) { if (!(obj instanceof Year)) return false; Year other = (Year) obj; if (obj == null) return false; if (this == obj) return true; boolean equals = (this.year == other.year); if (timezone != null) { equals = equals && timezone.equals(other.timezone); } return equals; } /** * Return the value of year XORed with the hashCode of timezone * iff one is defined. * * @return an <code>int</code> value */ public int hashCode() { return null == timezone ? year : year ^ timezone.hashCode(); } }
7,384
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/MonthDay.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.text.NumberFormat; /** * Implementation of the XML Schema type gMonthDay * * @author Tom Jordahl (tomj@macromedia.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#gMonthDay">XML Schema 3.2.12</a> */ public class MonthDay implements java.io.Serializable { int month; int day; String timezone = null; /** * Constructs a MonthDay with the given values * No timezone is specified */ public MonthDay(int month, int day) throws NumberFormatException { setValue(month, day); } /** * Constructs a MonthDay with the given values, including a timezone string * The timezone is validated but not used. */ public MonthDay(int month, int day, String timezone) throws NumberFormatException { setValue(month, day, timezone); } /** * Construct a MonthDay from a String in the format --MM-DD[timezone] */ public MonthDay(String source) throws NumberFormatException { if (source.length() < 6) { throw new NumberFormatException( Messages.getMessage("badMonthDay00")); } if (source.charAt(0) != '-' || source.charAt(1) != '-' || source.charAt(4) != '-' ) { throw new NumberFormatException( Messages.getMessage("badMonthDay00")); } setValue(Integer.parseInt(source.substring(2,4)), Integer.parseInt(source.substring(5,7)), source.substring(7)); } public int getMonth() { return month; } public void setMonth(int month) { // validate month if (month < 1 || month > 12) { throw new NumberFormatException( Messages.getMessage("badMonthDay00")); } this.month = month; } public int getDay() { return day; } /** * Set the day * NOTE: if the month isn't set yet, the day isn't validated */ public void setDay(int day) { // validate day if (day < 1 || day > 31) { throw new NumberFormatException( Messages.getMessage("badMonthDay00")); } // 30 days has September... All the rest have 31 (except Feb!) // NOTE: if month isn't set, we don't validate day. if ((month == 2 && day > 29) || ((month == 9 || month == 4 || month == 6 || month == 11) && day > 30)) { throw new NumberFormatException( Messages.getMessage("badMonthDay00")); } this.day = day; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { // validate timezone if (timezone != null && timezone.length() > 0) { // Format [+/-]HH:MM if (timezone.charAt(0)=='+' || (timezone.charAt(0)=='-')) { if (timezone.length() != 6 || !Character.isDigit(timezone.charAt(1)) || !Character.isDigit(timezone.charAt(2)) || timezone.charAt(3) != ':' || !Character.isDigit(timezone.charAt(4)) || !Character.isDigit(timezone.charAt(5))) throw new NumberFormatException( Messages.getMessage("badTimezone00")); } else if (!timezone.equals("Z")) { throw new NumberFormatException( Messages.getMessage("badTimezone00")); } // if we got this far, its good this.timezone = timezone; } } public void setValue(int month, int day, String timezone) throws NumberFormatException { setMonth(month); setDay(day); setTimezone(timezone); } public void setValue(int month, int day) throws NumberFormatException { setMonth(month); setDay(day); } public String toString() { // use NumberFormat to ensure leading zeros NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); // month & Day: --MM-DD nf.setMinimumIntegerDigits(2); String s = "--" + nf.format(month) + "-" + nf.format(day); // timezone if (timezone != null) { s = s + timezone; } return s; } public boolean equals(Object obj) { if (!(obj instanceof MonthDay)) return false; MonthDay other = (MonthDay) obj; if (obj == null) return false; if (this == obj) return true; boolean equals = (this.month == other.month && this.day == other.day); if (timezone != null) { equals = equals && timezone.equals(other.timezone); } return equals; } /** * Return the value of (month + day) XORed with the hashCode of * timezone iff one is defined. * * @return an <code>int</code> value */ public int hashCode() { return null == timezone ? (month + day) : (month + day) ^ timezone.hashCode(); } }
7,385
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/UnsignedShort.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting primitive XSD data type UnsignedShort * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#unsignedShort">XML Schema 3.3.23</a> */ public class UnsignedShort extends UnsignedInt { public UnsignedShort() { } /** * ctor for UnsignedShort * @exception NumberFormatException will be thrown if validation fails */ public UnsignedShort(long sValue) throws NumberFormatException { setValue(sValue); } public UnsignedShort(String sValue) throws NumberFormatException { setValue(Long.parseLong(sValue)); } /** * * validates the data and sets the value for the object. * * @param sValue value */ public void setValue(long sValue) throws NumberFormatException { if (UnsignedShort.isValid(sValue) == false) throw new NumberFormatException( Messages.getMessage("badUnsignedShort00") + String.valueOf(sValue) + "]"); lValue = new Long(sValue); } /** * * validate the value against the xsd definition * */ public static boolean isValid(long sValue) { if ( (sValue < 0L ) || (sValue > 65535L) ) return false; else return true; } }
7,386
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NegativeInteger.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.math.BigInteger; import java.util.Random; import java.io.ObjectStreamException; /** * Custom class for supporting primitive XSD data type negativeinteger * * negativeInteger is derived from nonPositiveInteger by setting the * value of maxInclusive to be -1. This results in the standard * mathematical concept of the negative integers. The value space of * negativeInteger is the infinite set {...,-2,-1}. * The base type of negativeInteger is nonPositiveInteger. * * @author Chris Haddad (haddadc@apache.org) * @see <a href="http://www.w3.org/TR/xmlschema-2/#negativeInteger">XML Schema 3.3.15</a> */ public class NegativeInteger extends NonPositiveInteger { public NegativeInteger(byte[] val) { super(val); checkValidity(); } // ctor public NegativeInteger(int signum, byte[] magnitude) { super(signum, magnitude); checkValidity(); } // ctor public NegativeInteger(int bitLength, int certainty, Random rnd) { super(bitLength, certainty, rnd); checkValidity(); } // ctor public NegativeInteger(int numBits, Random rnd) { super(numBits, rnd); checkValidity(); } // ctor public NegativeInteger(String val) { super(val); checkValidity(); } public NegativeInteger(String val, int radix) { super(val, radix); checkValidity(); } // ctor /** * validate the value against the xsd definition */ private BigInteger zero = new BigInteger("0"); private void checkValidity() { if (compareTo(zero) >= 0) { throw new NumberFormatException( Messages.getMessage("badnegInt00") + ": " + this); } } // checkValidity /** * Work-around for http://developer.java.sun.com/developer/bugParade/bugs/4378370.html * @return BigIntegerRep * @throws java.io.ObjectStreamException */ public Object writeReplace() throws ObjectStreamException { return new BigIntegerRep(toByteArray()); } protected static class BigIntegerRep implements java.io.Serializable { private byte[] array; protected BigIntegerRep(byte[] array) { this.array = array; } protected Object readResolve() throws java.io.ObjectStreamException { return new NegativeInteger(array); } } } // class NonNegativeInteger
7,387
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NormalizedString.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting XSD data type NormalizedString. * normalizedString represents white space normalized strings. * The base type of normalizedString is string. * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#normalizedString">XML Schema Part 2: Datatypes 3.3.1</a> */ public class NormalizedString extends Object implements java.io.Serializable { String m_value = null; // JAX-RPC maps xsd:string to java.lang.String public NormalizedString() { super(); } /** * * ctor for NormalizedString * @param stValue is the String value * @throws IllegalArgumentException if invalid format */ public NormalizedString(String stValue) throws IllegalArgumentException { setValue(stValue); } /** * * validates the data and sets the value for the object. * @param stValue String value * @throws IllegalArgumentException if invalid format */ public void setValue(String stValue) throws IllegalArgumentException { if (NormalizedString.isValid(stValue) == false) throw new IllegalArgumentException( Messages.getMessage("badNormalizedString00") + " data=[" + stValue + "]"); m_value = stValue; } public String toString(){ return m_value; } public int hashCode(){ return m_value.hashCode(); } /** * * validate the value against the xsd definition for the object * * The value space of normalizedString is the set of strings that * do not contain the carriage return (#xD), line feed (#xA) nor * tab (#x9) characters. The lexical space of normalizedString is * the set of strings that do not contain the carriage return (#xD) * nor tab (#x9) characters. * * @param stValue the String to test * @return true if valid normalizedString */ public static boolean isValid(String stValue) { int scan; for (scan = 0; scan < stValue.length(); scan++) { char cDigit = stValue.charAt(scan); switch (cDigit) { case 0x09: case 0x0A: case 0x0D: return false; default: break; } } return true; } public boolean equals(Object object) { String s1 = object.toString(); return s1.equals(m_value); } }
7,388
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/PositiveInteger.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import java.math.BigInteger; import java.util.Random; import java.io.ObjectStreamException; /** * Custom class for supporting primitive XSD data type positiveInteger * * positiveInteger is derived from nonNegativeInteger by setting the value of minInclusive to be 1. * This results in the standard mathematical concept of the positive integer numbers. The value space * of positiveInteger is the infinite set {1,2,...}. * * @author Chris Haddad (haddadc@apache.org) * @see <a href="http://www.w3.org/TR/xmlschema-2/#positiveInteger">XML Schema 3.3.25</a> */ public class PositiveInteger extends NonNegativeInteger { public PositiveInteger(byte[] val) { super(val); checkValidity(); } // ctor public PositiveInteger(int signum, byte[] magnitude) { super(signum, magnitude); checkValidity(); } // ctor public PositiveInteger(int bitLength, int certainty, Random rnd) { super(bitLength, certainty, rnd); checkValidity(); } // ctor public PositiveInteger(int numBits, Random rnd) { super(numBits, rnd); checkValidity(); } // ctor public PositiveInteger(String val) { super(val); checkValidity(); } public PositiveInteger(String val, int radix) { super(val, radix); checkValidity(); } // ctor /** * validate the value against the xsd definition */ private BigInteger iMinInclusive = new BigInteger("1"); private void checkValidity() { if (compareTo(iMinInclusive) < 0) { throw new NumberFormatException( Messages.getMessage("badposInt00") + ": " + this); } } // checkValidity /** * Work-around for http://developer.java.sun.com/developer/bugParade/bugs/4378370.html * @return BigIntegerRep * @throws java.io.ObjectStreamException */ public Object writeReplace() throws ObjectStreamException { return new BigIntegerRep(toByteArray()); } protected static class BigIntegerRep implements java.io.Serializable { private byte[] array; protected BigIntegerRep(byte[] array) { this.array = array; } protected Object readResolve() throws java.io.ObjectStreamException { return new PositiveInteger(array); } } } // class NonNegativeInteger
7,389
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/HexBinary.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types ; import org.apache.axis.utils.Messages; import java.io.ByteArrayOutputStream; /** * Custom class for supporting primitive XSD data type hexBinary. * * @author Davanum Srinivas (dims@yahoo.com) */ public class HexBinary extends Object implements java.io.Serializable{ byte[] m_value = null; public HexBinary() { } public HexBinary(String string){ m_value = decode(string); } public HexBinary(byte[] bytes){ m_value = bytes; } public byte[] getBytes(){ return m_value; } public String toString(){ return encode(m_value); } public int hashCode(){ //TODO: How do we hash this? return super.hashCode(); } public boolean equals(Object object){ //TODO: Is this good enough? String s1 = object.toString(); String s2 = this.toString(); return s1.equals(s2); } public static final String ERROR_ODD_NUMBER_OF_DIGITS = Messages.getMessage("oddDigits00"); public static final String ERROR_BAD_CHARACTER_IN_HEX_STRING = Messages.getMessage("badChars01"); // Code from Ajp11, from Apache's JServ // Table for HEX to DEC byte translation public static final int[] DEC = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 00, 01, 02, 03, 04, 05, 06, 07, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** * Convert a String of hexadecimal digits into the corresponding * byte array by encoding each two hexadecimal digits as a byte. * * @param digits Hexadecimal digits representation * * @exception IllegalArgumentException if an invalid hexadecimal digit * is found, or the input string contains an odd number of hexadecimal * digits */ public static byte[] decode(String digits) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < digits.length(); i += 2) { char c1 = digits.charAt(i); if ((i+1) >= digits.length()) throw new IllegalArgumentException (ERROR_ODD_NUMBER_OF_DIGITS); char c2 = digits.charAt(i + 1); byte b = 0; if ((c1 >= '0') && (c1 <= '9')) b += ((c1 - '0') * 16); else if ((c1 >= 'a') && (c1 <= 'f')) b += ((c1 - 'a' + 10) * 16); else if ((c1 >= 'A') && (c1 <= 'F')) b += ((c1 - 'A' + 10) * 16); else throw new IllegalArgumentException (ERROR_BAD_CHARACTER_IN_HEX_STRING); if ((c2 >= '0') && (c2 <= '9')) b += (c2 - '0'); else if ((c2 >= 'a') && (c2 <= 'f')) b += (c2 - 'a' + 10); else if ((c2 >= 'A') && (c2 <= 'F')) b += (c2 - 'A' + 10); else throw new IllegalArgumentException (ERROR_BAD_CHARACTER_IN_HEX_STRING); baos.write(b); } return (baos.toByteArray()); } /** * Convert a byte array into a printable format containing a * String of hexadecimal digit characters (two per byte). * * @param bytes Byte array representation */ public static String encode(byte bytes[]) { StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { sb.append(convertDigit((int) (bytes[i] >> 4))); sb.append(convertDigit((int) (bytes[i] & 0x0f))); } return (sb.toString()); } /** * Convert 4 hex digits to an int, and return the number of converted * bytes. * * @param hex Byte array containing exactly four hexadecimal digits * * @exception IllegalArgumentException if an invalid hexadecimal digit * is included */ public static int convert2Int( byte[] hex ) { // Code from Ajp11, from Apache's JServ // assert b.length==4 // assert valid data int len; if(hex.length < 4 ) return 0; if( DEC[hex[0]]<0 ) throw new IllegalArgumentException(ERROR_BAD_CHARACTER_IN_HEX_STRING); len = DEC[hex[0]]; len = len << 4; if( DEC[hex[1]]<0 ) throw new IllegalArgumentException(ERROR_BAD_CHARACTER_IN_HEX_STRING); len += DEC[hex[1]]; len = len << 4; if( DEC[hex[2]]<0 ) throw new IllegalArgumentException(ERROR_BAD_CHARACTER_IN_HEX_STRING); len += DEC[hex[2]]; len = len << 4; if( DEC[hex[3]]<0 ) throw new IllegalArgumentException(ERROR_BAD_CHARACTER_IN_HEX_STRING); len += DEC[hex[3]]; return len; } /** * [Private] Convert the specified value (0 .. 15) to the corresponding * hexadecimal digit. * * @param value Value to be converted */ private static char convertDigit(int value) { value &= 0x0f; if (value >= 10) return ((char) (value - 10 + 'a')); else return ((char) (value + '0')); } }
7,390
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Name.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLChar; /** * Custom class for supporting XSD data type Name * Name represents XML Names. The value space of Name is * the set of all strings which match the Name production * of [XML 1.0 (Second Edition)]. * The base type of Name is token. * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#Name">XML Schema 3.3.6</a> */ public class Name extends Token { public Name() { super(); } /** * ctor for Name * @exception IllegalArgumentException will be thrown if validation fails */ public Name(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badNameType00") + "data=[" + stValue + "]"); } } /** * * validates the data and sets the value for the object. * @param stValue String value * @throws IllegalArgumentException if invalid format */ public void setValue(String stValue) throws IllegalArgumentException { if (Name.isValid(stValue) == false) throw new IllegalArgumentException( Messages.getMessage("badNameType00") + " data=[" + stValue + "]"); m_value = stValue; } /** * * validate the value against the xsd definition * Name ::= (Letter | '_' | ':') ( NameChar)* * NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender */ public static boolean isValid(String stValue) { int scan; boolean bValid = true; for (scan=0; scan < stValue.length(); scan++) { if (scan == 0) bValid = XMLChar.isNameStart(stValue.charAt(scan)); else bValid = XMLChar.isName(stValue.charAt(scan)); if (bValid == false) break; } return bValid; } }
7,391
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/URI.java
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import java.io.IOException; import java.io.Serializable; /********************************************************************** * <i>Axis Note: This class was 'borrowed' from Xerces 2: * org.apache.xerces.util.URI.java, version 1.22 </i> * <p> * A class to represent a Uniform Resource Identifier (URI). This class * is designed to handle the parsing of URIs and provide access to * the various components (scheme, host, port, userinfo, path, query * string and fragment) that may constitute a URI. * <p> * Parsing of a URI specification is done according to the URI * syntax described in * <a href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>, * and amended by * <a href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>. * <p> * Every absolute URI consists of a scheme, followed by a colon (':'), * followed by a scheme-specific part. For URIs that follow the * "generic URI" syntax, the scheme-specific part begins with two * slashes ("//") and may be followed by an authority segment (comprised * of user information, host, and port), path segment, query segment * and fragment. Note that RFC 2396 no longer specifies the use of the * parameters segment and excludes the "user:password" syntax as part of * the authority segment. If "user:password" appears in a URI, the entire * user/password string is stored as userinfo. * <p> * For URIs that do not follow the "generic URI" syntax (e.g. mailto), * the entire scheme-specific part is treated as the "path" portion * of the URI. * <p> * Note that, unlike the java.net.URL class, this class does not provide * any built-in network access functionality nor does it provide any * scheme-specific functionality (for example, it does not know a * default port for a specific scheme). Rather, it only knows the * grammar and basic set of operations that can be applied to a URI. * **********************************************************************/ public class URI implements Serializable { /******************************************************************* * MalformedURIExceptions are thrown in the process of building a URI * or setting fields on a URI when an operation would result in an * invalid URI specification. * ********************************************************************/ public static class MalformedURIException extends IOException { /** Serialization version. */ static final long serialVersionUID = -6695054834342951930L; /****************************************************************** * Constructs a <code>MalformedURIException</code> with no specified * detail message. ******************************************************************/ public MalformedURIException() { super(); } /***************************************************************** * Constructs a <code>MalformedURIException</code> with the * specified detail message. * * @param p_msg the detail message. ******************************************************************/ public MalformedURIException(String p_msg) { super(p_msg); } } /** Serialization version. */ static final long serialVersionUID = 1601921774685357214L; private static final byte [] fgLookupTable = new byte[128]; /** * Character Classes */ /** reserved characters ;/?:@&=+$,[] */ //RFC 2732 added '[' and ']' as reserved characters private static final int RESERVED_CHARACTERS = 0x01; /** URI punctuation mark characters: -_.!~*'() - these, combined with alphanumerics, constitute the "unreserved" characters */ private static final int MARK_CHARACTERS = 0x02; /** scheme can be composed of alphanumerics and these characters: +-. */ private static final int SCHEME_CHARACTERS = 0x04; /** userinfo can be composed of unreserved, escaped and these characters: ;:&=+$, */ private static final int USERINFO_CHARACTERS = 0x08; /** ASCII letter characters */ private static final int ASCII_ALPHA_CHARACTERS = 0x10; /** ASCII digit characters */ private static final int ASCII_DIGIT_CHARACTERS = 0x20; /** ASCII hex characters */ private static final int ASCII_HEX_CHARACTERS = 0x40; /** Path characters */ private static final int PATH_CHARACTERS = 0x80; /** Mask for alpha-numeric characters */ private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS; /** Mask for unreserved characters */ private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS; /** Mask for URI allowable characters except for % */ private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS; /** Mask for scheme characters */ private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS; /** Mask for userinfo characters */ private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS; /** Mask for path characters */ private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS; static { // Add ASCII Digits and ASCII Hex Numbers for (int i = '0'; i <= '9'; ++i) { fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters and ASCII Hex Numbers for (int i = 'A'; i <= 'F'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters for (int i = 'G'; i <= 'Z'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS; } // Add Reserved Characters fgLookupTable[';'] |= RESERVED_CHARACTERS; fgLookupTable['/'] |= RESERVED_CHARACTERS; fgLookupTable['?'] |= RESERVED_CHARACTERS; fgLookupTable[':'] |= RESERVED_CHARACTERS; fgLookupTable['@'] |= RESERVED_CHARACTERS; fgLookupTable['&'] |= RESERVED_CHARACTERS; fgLookupTable['='] |= RESERVED_CHARACTERS; fgLookupTable['+'] |= RESERVED_CHARACTERS; fgLookupTable['$'] |= RESERVED_CHARACTERS; fgLookupTable[','] |= RESERVED_CHARACTERS; fgLookupTable['['] |= RESERVED_CHARACTERS; fgLookupTable[']'] |= RESERVED_CHARACTERS; // Add Mark Characters fgLookupTable['-'] |= MARK_CHARACTERS; fgLookupTable['_'] |= MARK_CHARACTERS; fgLookupTable['.'] |= MARK_CHARACTERS; fgLookupTable['!'] |= MARK_CHARACTERS; fgLookupTable['~'] |= MARK_CHARACTERS; fgLookupTable['*'] |= MARK_CHARACTERS; fgLookupTable['\''] |= MARK_CHARACTERS; fgLookupTable['('] |= MARK_CHARACTERS; fgLookupTable[')'] |= MARK_CHARACTERS; // Add Scheme Characters fgLookupTable['+'] |= SCHEME_CHARACTERS; fgLookupTable['-'] |= SCHEME_CHARACTERS; fgLookupTable['.'] |= SCHEME_CHARACTERS; // Add Userinfo Characters fgLookupTable[';'] |= USERINFO_CHARACTERS; fgLookupTable[':'] |= USERINFO_CHARACTERS; fgLookupTable['&'] |= USERINFO_CHARACTERS; fgLookupTable['='] |= USERINFO_CHARACTERS; fgLookupTable['+'] |= USERINFO_CHARACTERS; fgLookupTable['$'] |= USERINFO_CHARACTERS; fgLookupTable[','] |= USERINFO_CHARACTERS; // Add Path Characters fgLookupTable[';'] |= PATH_CHARACTERS; fgLookupTable['/'] |= PATH_CHARACTERS; fgLookupTable[':'] |= PATH_CHARACTERS; fgLookupTable['@'] |= PATH_CHARACTERS; fgLookupTable['&'] |= PATH_CHARACTERS; fgLookupTable['='] |= PATH_CHARACTERS; fgLookupTable['+'] |= PATH_CHARACTERS; fgLookupTable['$'] |= PATH_CHARACTERS; fgLookupTable[','] |= PATH_CHARACTERS; } /** Stores the scheme (usually the protocol) for this URI. */ private String m_scheme = null; /** If specified, stores the userinfo for this URI; otherwise null */ private String m_userinfo = null; /** If specified, stores the host for this URI; otherwise null */ private String m_host = null; /** If specified, stores the port for this URI; otherwise -1 */ private int m_port = -1; /** If specified, stores the registry based authority for this URI; otherwise -1 */ private String m_regAuthority = null; /** If specified, stores the path for this URI; otherwise null */ private String m_path = null; /** If specified, stores the query string for this URI; otherwise null. */ private String m_queryString = null; /** If specified, stores the fragment for this URI; otherwise null */ private String m_fragment = null; private static boolean DEBUG = false; /** * Construct a new and uninitialized URI. */ public URI() { } /** * Construct a new URI from another URI. All fields for this URI are * set equal to the fields of the URI passed in. * * @param p_other the URI to copy (cannot be null) */ public URI(URI p_other) { initialize(p_other); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(String p_uriSpec) throws MalformedURIException { this((URI)null, p_uriSpec); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * Construct a relative URI if boolean is assigned to "true" * and p_uriSpec is not valid absolute URI, instead of throwing an exception. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * @param allowNonAbsoluteURI true to permit non-absolute URIs, * false otherwise. * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException { this((URI)null, p_uriSpec, allowNonAbsoluteURI); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(URI p_base, String p_uriSpec) throws MalformedURIException { initialize(p_base, p_uriSpec); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * Construct a relative URI if boolean is assigned to "true" * and p_uriSpec is not valid absolute URI and p_base is null * instead of throwing an exception. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * @param allowNonAbsoluteURI true to permit non-absolute URIs, * false otherwise. * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException { initialize(p_base, p_uriSpec, allowNonAbsoluteURI); } /** * Construct a new URI that does not follow the generic URI syntax. * Only the scheme and scheme-specific part (stored as the path) are * initialized. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_schemeSpecificPart the scheme-specific part (cannot be * null or empty) * * @exception MalformedURIException if p_scheme violates any * syntax rules */ public URI(String p_scheme, String p_schemeSpecificPart) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme!"); } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme-specific part!"); } setScheme(p_scheme); setPath(p_schemeSpecificPart); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_host, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_userinfo the URI userinfo (cannot be specified if host * is null) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_port the URI port (may be -1 for "unspecified"; cannot * be specified if host is null) * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_userinfo, String p_host, int p_port, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException("Scheme is required!"); } if (p_host == null) { if (p_userinfo != null) { throw new MalformedURIException( "Userinfo may not be specified if host is not specified!"); } if (p_port != -1) { throw new MalformedURIException( "Port may not be specified if host is not specified!"); } } if (p_path != null) { if (p_path.indexOf('?') != -1 && p_queryString != null) { throw new MalformedURIException( "Query string cannot be specified in path and query string!"); } if (p_path.indexOf('#') != -1 && p_fragment != null) { throw new MalformedURIException( "Fragment cannot be specified in both the path and fragment!"); } } setScheme(p_scheme); setHost(p_host); setPort(p_port); setUserinfo(p_userinfo); setPath(p_path); setQueryString(p_queryString); setFragment(p_fragment); } /** * Initialize all fields of this URI from another URI. * * @param p_other the URI to copy (cannot be null) */ private void initialize(URI p_other) { m_scheme = p_other.getScheme(); m_userinfo = p_other.getUserinfo(); m_host = p_other.getHost(); m_port = p_other.getPort(); m_regAuthority = p_other.getRegBasedAuthority(); m_path = p_other.getPath(); m_queryString = p_other.getQueryString(); m_fragment = p_other.getFragment(); } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * @param allowNonAbsoluteURI true to permit non-absolute URIs, * in case of relative URI, false otherwise. * * @exception MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException { String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { if (allowNonAbsoluteURI) { m_path = ""; return; } throw new MalformedURIException("Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. int colonIdx = uriSpec.indexOf(':'); if (colonIdx != -1) { final int searchFrom = colonIdx - 1; // search backwards starting from character before ':'. int slashIdx = uriSpec.lastIndexOf('/', searchFrom); int queryIdx = uriSpec.lastIndexOf('?', searchFrom); int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom); if (colonIdx == 0 || slashIdx != -1 || queryIdx != -1 || fragmentIdx != -1) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0 && !allowNonAbsoluteURI)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } } else if (p_base == null && uriSpec.indexOf('#') != 0 && !allowNonAbsoluteURI) { throw new MalformedURIException("No scheme found in URI."); } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { absolutize(p_base); } } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * * @exception MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. int colonIdx = uriSpec.indexOf(':'); if (colonIdx != -1) { final int searchFrom = colonIdx - 1; // search backwards starting from character before ':'. int slashIdx = uriSpec.lastIndexOf('/', searchFrom); int queryIdx = uriSpec.lastIndexOf('?', searchFrom); int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom); if (colonIdx == 0 || slashIdx != -1 || queryIdx != -1 || fragmentIdx != -1) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } } else if (p_base == null && uriSpec.indexOf('#') != 0) { throw new MalformedURIException("No scheme found in URI."); } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { absolutize(p_base); } } /** * Absolutize URI with given base URI. * * @param p_base base URI for absolutization */ public void absolutize(URI p_base) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); if (m_fragment == null) { m_fragment = p_base.getFragment(); } } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment int index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else { index += 4; } } else { index += 4; } } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } /** * Initialize the scheme for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if URI does not have a conformant * scheme */ private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException("No scheme found in URI."); } else { setScheme(scheme); } } /** * Initialize the authority (either server or registry based) * for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @return true if the given string matched server or registry * based authority */ private boolean initializeAuthority(String p_uriSpec) { int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; String userinfo = null; // userinfo is everything up to @ if (p_uriSpec.indexOf('@', start) != -1) { while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '@') { break; } index++; } userinfo = p_uriSpec.substring(start, index); index++; } // host is everything up to last ':', or up to // and including ']' if followed by ':'. String host = null; start = index; boolean hasPort = false; if (index < end) { if (p_uriSpec.charAt(start) == '[') { int bracketIndex = p_uriSpec.indexOf(']', start); index = (bracketIndex != -1) ? bracketIndex : end; if (index+1 < end && p_uriSpec.charAt(index+1) == ':') { ++index; hasPort = true; } else { index = end; } } else { int colonIndex = p_uriSpec.lastIndexOf(':', end); index = (colonIndex > start) ? colonIndex : end; hasPort = (index != end); } } host = p_uriSpec.substring(start, index); int port = -1; if (host.length() > 0) { // port if (hasPort) { index++; start = index; while (index < end) { index++; } String portStr = p_uriSpec.substring(start, index); if (portStr.length() > 0) { // REVISIT: Remove this code. /** for (int i = 0; i < portStr.length(); i++) { if (!isDigit(portStr.charAt(i))) { throw new MalformedURIException( portStr + " is invalid. Port should only contain digits!"); } }**/ // REVISIT: Remove this code. // Store port value as string instead of integer. try { port = Integer.parseInt(portStr); if (port == -1) --port; } catch (NumberFormatException nfe) { port = -2; } } } } if (isValidServerBasedAuthority(host, port, userinfo)) { m_host = host; m_port = port; m_userinfo = userinfo; return true; } // Note: Registry based authority is being removed from a // new spec for URI which would obsolete RFC 2396. If the // spec is added to XML errata, processing of reg_name // needs to be removed. - mrglavas. else if (isValidRegistryBasedAuthority(p_uriSpec)) { m_regAuthority = p_uriSpec; return true; } return false; } /** * Determines whether the components host, port, and user info * are valid as a server authority. * * @param host the host component of authority * @param port the port number component of authority * @param userinfo the user info component of authority * * @return true if the given host, port, and userinfo compose * a valid server authority */ private boolean isValidServerBasedAuthority(String host, int port, String userinfo) { // Check if the host is well formed. if (!isWellFormedAddress(host)) { return false; } // Check that port is well formed if it exists. // REVISIT: There's no restriction on port value ranges, but // perform the same check as in setPort to be consistent. Pass // in a string to this method instead of an integer. if (port < -1 || port > 65535) { return false; } // Check that userinfo is well formed if it exists. if (userinfo != null) { // Userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = userinfo.length(); char testChar = '\0'; while (index < end) { testChar = userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(userinfo.charAt(index+1)) || !isHex(userinfo.charAt(index+2))) { return false; } index += 2; } else if (!isUserinfoCharacter(testChar)) { return false; } ++index; } } return true; } /** * Determines whether the given string is a registry based authority. * * @param authority the authority component of a URI * * @return true if the given string is a registry based authority */ private boolean isValidRegistryBasedAuthority(String authority) { int index = 0; int end = authority.length(); char testChar; while (index < end) { testChar = authority.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(authority.charAt(index+1)) || !isHex(authority.charAt(index+2))) { return false; } index += 2; } // can check against path characters because the set // is the same except for '/' which we've already excluded. else if (!isPathCharacter(testChar)) { return false; } ++index; } return true; } /** * Initialize the path for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * @param p_nStartIndex the index to begin scanning from * * @exception MalformedURIException if p_uriSpec violates syntax rules */ private void initializePath(String p_uriSpec, int p_nStartIndex) throws MalformedURIException { if (p_uriSpec == null) { throw new MalformedURIException( "Cannot initialize path from null string!"); } int index = p_nStartIndex; int start = p_nStartIndex; int end = p_uriSpec.length(); char testChar = '\0'; // path - everything up to query string or fragment if (start < end) { // RFC 2732 only allows '[' and ']' to appear in the opaque part. if (getScheme() == null || p_uriSpec.charAt(start) == '/') { // Scan path. // abs_path = "/" path_segments // rel_path = rel_segment [ abs_path ] while (index < end) { testChar = p_uriSpec.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Path contains invalid escape sequence!"); } index += 2; } // Path segments cannot contain '[' or ']' since pchar // production was not changed by RFC 2732. else if (!isPathCharacter(testChar)) { if (testChar == '?' || testChar == '#') { break; } throw new MalformedURIException( "Path contains invalid character: " + testChar); } ++index; } } else { // Scan opaque part. // opaque_part = uric_no_slash *uric while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '?' || testChar == '#') { break; } // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Opaque part contains invalid escape sequence!"); } index += 2; } // If the scheme specific part is opaque, it can contain '[' // and ']'. uric_no_slash wasn't modified by RFC 2732, which // I've interpreted as an error in the spec, since the // production should be equivalent to (uric - '/'), and uric // contains '[' and ']'. - mrglavas else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Opaque part contains invalid character: " + testChar); } ++index; } } } m_path = p_uriSpec.substring(start, index); // query - starts with ? and up to fragment or end if (testChar == '?') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '#') { break; } if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Query string contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Query string contains invalid character: " + testChar); } index++; } m_queryString = p_uriSpec.substring(start, index); } // fragment - starts with # if (testChar == '#') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Fragment contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Fragment contains invalid character: "+testChar); } index++; } m_fragment = p_uriSpec.substring(start, index); } } /** * Get the scheme for this URI. * * @return the scheme for this URI */ public String getScheme() { return m_scheme; } /** * Get the scheme-specific part for this URI (everything following the * scheme and the first colon). See RFC 2396 Section 5.2 for spec. * * @return the scheme-specific part for this URI */ public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_host != null || m_regAuthority != null) { schemespec.append("//"); // Server based authority. if (m_host != null) { if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } schemespec.append(m_host); if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } } // Registry based authority. else { schemespec.append(m_regAuthority); } } if (m_path != null) { schemespec.append((m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); } /** * Get the userinfo for this URI. * * @return the userinfo for this URI (null if not specified). */ public String getUserinfo() { return m_userinfo; } /** * Get the host for this URI. * * @return the host for this URI (null if not specified). */ public String getHost() { return m_host; } /** * Get the port for this URI. * * @return the port for this URI (-1 if not specified). */ public int getPort() { return m_port; } /** * Get the registry based authority for this URI. * * @return the registry based authority (null if not specified). */ public String getRegBasedAuthority() { return m_regAuthority; } /** * Get the path for this URI (optionally with the query string and * fragment). * * @param p_includeQueryString if true (and query string is not null), * then a "?" followed by the query string * will be appended * @param p_includeFragment if true (and fragment is not null), * then a "#" followed by the fragment * will be appended * * @return the path for this URI possibly including the query string * and fragment */ public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_includeFragment && m_fragment != null) { pathString.append('#'); pathString.append(m_fragment); } return pathString.toString(); } /** * Get the path for this URI. Note that the value returned is the path * only and does not include the query string or fragment. * * @return the path for this URI. */ public String getPath() { return m_path; } /** * Get the query string for this URI. * * @return the query string for this URI. Null is returned if there * was no "?" in the URI spec, empty string if there was a * "?" but no query string following it. */ public String getQueryString() { return m_queryString; } /** * Get the fragment for this URI. * * @return the fragment for this URI. Null is returned if there * was no "#" in the URI spec, empty string if there was a * "#" but no fragment following it. */ public String getFragment() { return m_fragment; } /** * Set the scheme for this URI. The scheme is converted to lowercase * before it is set. * * @param p_scheme the scheme for this URI (cannot be null) * * @exception MalformedURIException if p_scheme is not a conformant * scheme name */ public void setScheme(String p_scheme) throws MalformedURIException { if (p_scheme == null) { throw new MalformedURIException( "Cannot set scheme from null string!"); } if (!isConformantSchemeName(p_scheme)) { throw new MalformedURIException("The scheme is not conformant."); } m_scheme = p_scheme.toLowerCase(); } /** * Set the userinfo for this URI. If a non-null value is passed in and * the host value is null, then an exception is thrown. * * @param p_userinfo the userinfo for this URI * * @exception MalformedURIException if p_userinfo contains invalid * characters */ public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; return; } else { if (m_host == null) { throw new MalformedURIException( "Userinfo cannot be set when host is null!"); } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_userinfo.charAt(index+1)) || !isHex(p_userinfo.charAt(index+2))) { throw new MalformedURIException( "Userinfo contains invalid escape sequence!"); } } else if (!isUserinfoCharacter(testChar)) { throw new MalformedURIException( "Userinfo contains invalid character:"+testChar); } index++; } } m_userinfo = p_userinfo; } /** * <p>Set the host for this URI. If null is passed in, the userinfo * field is also set to null and the port is set to -1.</p> * * <p>Note: This method overwrites registry based authority if it * previously existed in this URI.</p> * * @param p_host the host for this URI * * @exception MalformedURIException if p_host is not a valid IP * address or DNS hostname. */ public void setHost(String p_host) throws MalformedURIException { if (p_host == null || p_host.length() == 0) { if (p_host != null) { m_regAuthority = null; } m_host = p_host; m_userinfo = null; m_port = -1; return; } else if (!isWellFormedAddress(p_host)) { throw new MalformedURIException("Host is not a well formed address!"); } m_host = p_host; m_regAuthority = null; } /** * Set the port for this URI. -1 is used to indicate that the port is * not specified, otherwise valid port numbers are between 0 and 65535. * If a valid port number is passed in and the host field is null, * an exception is thrown. * * @param p_port the port number for this URI * * @exception MalformedURIException if p_port is not -1 and not a * valid port number */ public void setPort(int p_port) throws MalformedURIException { if (p_port >= 0 && p_port <= 65535) { if (m_host == null) { throw new MalformedURIException( "Port cannot be set when host is null!"); } } else if (p_port != -1) { throw new MalformedURIException("Invalid port number!"); } m_port = p_port; } /** * <p>Sets the registry based authority for this URI.</p> * * <p>Note: This method overwrites server based authority * if it previously existed in this URI.</p> * * @param authority the registry based authority for this URI * * @exception MalformedURIException it authority is not a * well formed registry based authority */ public void setRegBasedAuthority(String authority) throws MalformedURIException { if (authority == null) { m_regAuthority = null; return; } // reg_name = 1*( unreserved | escaped | "$" | "," | // ";" | ":" | "@" | "&" | "=" | "+" ) else if (authority.length() < 1 || !isValidRegistryBasedAuthority(authority) || authority.indexOf('/') != -1) { throw new MalformedURIException("Registry based authority is not well formed."); } m_regAuthority = authority; m_host = null; m_userinfo = null; m_port = -1; } /** * Set the path for this URI. If the supplied path is null, then the * query string and fragment are set to null as well. If the supplied * path includes a query string and/or fragment, these fields will be * parsed and set as well. Note that, for URIs following the "generic * URI" syntax, the path specified should start with a slash. * For URIs that do not follow the generic URI syntax, this method * sets the scheme-specific part. * * @param p_path the path for this URI (may be null) * * @exception MalformedURIException if p_path contains invalid * characters */ public void setPath(String p_path) throws MalformedURIException { if (p_path == null) { m_path = null; m_queryString = null; m_fragment = null; } else { initializePath(p_path, 0); } } /** * Append to the end of the path of this URI. If the current path does * not end in a slash and the path to be appended does not begin with * a slash, a slash will be appended to the current path before the * new segment is added. Also, if the current path ends in a slash * and the new segment begins with a slash, the extra slash will be * removed before the new segment is appended. * * @param p_addToPath the new segment to be added to the current path * * @exception MalformedURIException if p_addToPath contains syntax * errors */ public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException( "Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } } /** * Set the query string for this URI. A non-null value is valid only * if this is an URI conforming to the generic URI syntax and * the path value is not null. * * @param p_queryString the query string for this URI * * @exception MalformedURIException if p_queryString is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setQueryString(String p_queryString) throws MalformedURIException { if (p_queryString == null) { m_queryString = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Query string can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Query string cannot be set when path is null!"); } else if (!isURIString(p_queryString)) { throw new MalformedURIException( "Query string contains invalid character!"); } else { m_queryString = p_queryString; } } /** * Set the fragment for this URI. A non-null value is valid only * if this is a URI conforming to the generic URI syntax and * the path value is not null. * * @param p_fragment the fragment for this URI * * @exception MalformedURIException if p_fragment is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setFragment(String p_fragment) throws MalformedURIException { if (p_fragment == null) { m_fragment = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Fragment can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Fragment cannot be set when path is null!"); } else if (!isURIString(p_fragment)) { throw new MalformedURIException( "Fragment contains invalid character!"); } else { m_fragment = p_fragment; } } /** * Determines if the passed-in Object is equivalent to this URI. * * @param p_test the Object to test for equality. * * @return true if p_test is a URI with all values equal to this * URI, false otherwise */ public boolean equals(Object p_test) { if (p_test instanceof URI) { URI testURI = (URI) p_test; if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme.equals(testURI.m_scheme))) && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null && testURI.m_userinfo != null && m_userinfo.equals(testURI.m_userinfo))) && ((m_regAuthority == null && testURI.m_regAuthority == null) || (m_regAuthority != null && testURI.m_regAuthority != null && m_regAuthority.equals(testURI.m_regAuthority))) && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host.equals(testURI.m_host))) && m_port == testURI.m_port && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path.equals(testURI.m_path))) && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null && testURI.m_queryString != null && m_queryString.equals(testURI.m_queryString))) && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null && testURI.m_fragment != null && m_fragment.equals(testURI.m_fragment)))) { return true; } } return false; } /** * Returns a hash-code value for this URI. The hash code is based upon all * of the URI's components, and satisfies the general contract of the * {@link java.lang.Object#hashCode() Object.hashCode} method. * * @return A hash-code value for this URI */ public int hashCode() { return toString().hashCode(); } /** * Get the URI as a string specification. See RFC 2396 Section 5.2. * * @return the URI string specification */ public String toString() { StringBuffer uriSpecString = new StringBuffer(); if (m_scheme != null) { uriSpecString.append(m_scheme); uriSpecString.append(':'); } uriSpecString.append(getSchemeSpecificPart()); return uriSpecString.toString(); } /** * Get the indicator as to whether this URI uses the "generic URI" * syntax. * * @return true if this URI uses the "generic URI" syntax, false * otherwise */ public boolean isGenericURI() { // presence of the host (whether valid or empty) means // double-slashes which means generic uri return (m_host != null); } /** * Returns whether this URI represents an absolute URI. * * @return true if this URI represents an absolute URI, false * otherwise */ public boolean isAbsoluteURI() { // presence of the scheme means absolute uri return (m_scheme != null); } /** * Determine whether a scheme conforms to the rules for a scheme name. * A scheme is conformant if it starts with an alphanumeric, and * contains only alphanumerics, '+','-' and '.'. * * @return true if the scheme is conformant, false otherwise */ public static boolean isConformantSchemeName(String p_scheme) { if (p_scheme == null || p_scheme.trim().length() == 0) { return false; } if (!isAlpha(p_scheme.charAt(0))) { return false; } char testChar; int schemeLength = p_scheme.length(); for (int i = 1; i < schemeLength; ++i) { testChar = p_scheme.charAt(i); if (!isSchemeCharacter(testChar)) { return false; } } return true; } /** * Determine whether a string is syntactically capable of representing * a valid IPv4 address, IPv6 reference or the domain name of a network host. * A valid IPv4 address consists of four decimal digit groups separated by a * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3, * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname * consists of domain labels (each of which must begin and end with an alphanumeric * but may contain '-') separated &amp; by a '.'. See RFC 2396 Section 3.2.2. * * @return true if the string is a syntactically valid IPv4 address, * IPv6 reference or hostname */ public static boolean isWellFormedAddress(String address) { if (address == null) { return false; } int addrLength = address.length(); if (addrLength == 0) { return false; } // Check if the host is a valid IPv6reference. if (address.startsWith("[")) { return isWellFormedIPv6Reference(address); } // Cannot start with a '.', '-', or end with a '-'. if (address.startsWith(".") || address.startsWith("-") || address.endsWith("-")) { return false; } // rightmost domain label starting with digit indicates IP address // since top level domain label can only start with an alpha // see RFC 2396 Section 3.2.2 int index = address.lastIndexOf('.'); if (address.endsWith(".")) { index = address.substring(0, index).lastIndexOf('.'); } if (index+1 < addrLength && isDigit(address.charAt(index+1))) { return isWellFormedIPv4Address(address); } else { // hostname = *( domainlabel "." ) toplabel [ "." ] // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum // toplabel = alpha | alpha *( alphanum | "-" ) alphanum // RFC 2396 states that hostnames take the form described in // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According // to RFC 1034, hostnames are limited to 255 characters. if (addrLength > 255) { return false; } // domain labels can contain alphanumerics and '-" // but must start and end with an alphanumeric char testChar; int labelCharCount = 0; for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isAlphanum(address.charAt(i-1))) { return false; } if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) { return false; } labelCharCount = 0; } else if (!isAlphanum(testChar) && testChar != '-') { return false; } // RFC 1034: Labels must be 63 characters or less. else if (++labelCharCount > 63) { return false; } } } return true; } /** * <p>Determines whether a string is an IPv4 address as defined by * RFC 2373, and under the further constraint that it must be a 32-bit * address. Though not expressed in the grammar, in order to satisfy * the 32-bit address constraint, each segment of the address cannot * be greater than 255 (8 bits of information).</p> * * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p> * * @return true if the string is a syntactically valid IPv4 address */ public static boolean isWellFormedIPv4Address(String address) { int addrLength = address.length(); char testChar; int numDots = 0; int numDigits = 0; // make sure that 1) we see only digits and dot separators, 2) that // any dot separator is preceded and followed by a digit and // 3) that we find 3 dots // // RFC 2732 amended RFC 2396 by replacing the definition // of IPv4address with the one defined by RFC 2373. - mrglavas // // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT // // One to three digits must be in each segment. for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if ((i > 0 && !isDigit(address.charAt(i-1))) || (i+1 < addrLength && !isDigit(address.charAt(i+1)))) { return false; } numDigits = 0; if (++numDots > 3) { return false; } } else if (!isDigit(testChar)) { return false; } // Check that that there are no more than three digits // in this segment. else if (++numDigits > 3) { return false; } // Check that this segment is not greater than 255. else if (numDigits == 3) { char first = address.charAt(i-2); char second = address.charAt(i-1); if (!(first < '2' || (first == '2' && (second < '5' || (second == '5' && testChar <= '5'))))) { return false; } } } return (numDots == 3); } /** * <p>Determines whether a string is an IPv6 reference as defined * by RFC 2732, where IPv6address is defined in RFC 2373. The * IPv6 address is parsed according to Section 2.2 of RFC 2373, * with the additional constraint that the address be composed of * 128 bits of information.</p> * * <p><code>IPv6reference = "[" IPv6address "]"</code></p> * * <p>Note: The BNF expressed in RFC 2373 Appendix B does not * accurately describe section 2.2, and was in fact removed from * RFC 3513, the successor of RFC 2373.</p> * * @return true if the string is a syntactically valid IPv6 reference */ public static boolean isWellFormedIPv6Reference(String address) { int addrLength = address.length(); int index = 1; int end = addrLength-1; // Check if string is a potential match for IPv6reference. if (!(addrLength > 2 && address.charAt(0) == '[' && address.charAt(end) == ']')) { return false; } // Counter for the number of 16-bit sections read in the address. int [] counter = new int[1]; // Scan hex sequence before possible '::' or IPv4 address. index = scanHexSequence(address, index, end, counter); if (index == -1) { return false; } // Address must contain 128-bits of information. else if (index == end) { return (counter[0] == 8); } if (index+1 < end && address.charAt(index) == ':') { if (address.charAt(index+1) == ':') { // '::' represents at least one 16-bit group of zeros. if (++counter[0] > 8) { return false; } index += 2; // Trailing zeros will fill out the rest of the address. if (index == end) { return true; } } // If the second character wasn't ':', in order to be valid, // the remainder of the string must match IPv4Address, // and we must have read exactly 6 16-bit groups. else { return (counter[0] == 6) && isWellFormedIPv4Address(address.substring(index+1, end)); } } else { return false; } // 3. Scan hex sequence after '::'. int prevCount = counter[0]; index = scanHexSequence(address, index, end, counter); // We've either reached the end of the string, the address ends in // an IPv4 address, or it is invalid. scanHexSequence has already // made sure that we have the right number of bits. return (index == end) || (index != -1 && isWellFormedIPv4Address( address.substring((counter[0] > prevCount) ? index+1 : index, end))); } /** * Helper method for isWellFormedIPv6Reference which scans the * hex sequences of an IPv6 address. It returns the index of the * next character to scan in the address, or -1 if the string * cannot match a valid IPv6 address. * * @param address the string to be scanned * @param index the beginning index (inclusive) * @param end the ending index (exclusive) * @param counter a counter for the number of 16-bit sections read * in the address * * @return the index of the next character to scan, or -1 if the * string cannot match a valid IPv6 address */ private static int scanHexSequence (String address, int index, int end, int [] counter) { char testChar; int numDigits = 0; int start = index; // Trying to match the following productions: // hexseq = hex4 *( ":" hex4) // hex4 = 1*4HEXDIG for (; index < end; ++index) { testChar = address.charAt(index); if (testChar == ':') { // IPv6 addresses are 128-bit, so there can be at most eight sections. if (numDigits > 0 && ++counter[0] > 8) { return -1; } // This could be '::'. if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) { return index; } numDigits = 0; } // This might be invalid or an IPv4address. If it's potentially an IPv4address, // backup to just after the last valid character that matches hexseq. else if (!isHex(testChar)) { if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) { int back = index - numDigits - 1; return (back >= start) ? back : (back+1); } return -1; } // There can be at most 4 hex digits per group. else if (++numDigits > 4) { return -1; } } return (numDigits > 0 && ++counter[0] <= 8) ? end : -1; } /** * Determine whether a char is a digit. * * @return true if the char is betweeen '0' and '9', false otherwise */ private static boolean isDigit(char p_char) { return p_char >= '0' && p_char <= '9'; } /** * Determine whether a character is a hexadecimal character. * * @return true if the char is betweeen '0' and '9', 'a' and 'f' * or 'A' and 'F', false otherwise */ private static boolean isHex(char p_char) { return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0); } /** * Determine whether a char is an alphabetic character: a-z or A-Z * * @return true if the char is alphabetic, false otherwise */ private static boolean isAlpha(char p_char) { return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' )); } /** * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z * * @return true if the char is alphanumeric, false otherwise */ private static boolean isAlphanum(char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0); } /** * Determine whether a character is a reserved character: * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']' * * @return true if the string contains any reserved characters */ private static boolean isReservedCharacter(char p_char) { return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0); } /** * Determine whether a char is an unreserved character. * * @return true if the char is unreserved, false otherwise */ private static boolean isUnreservedCharacter(char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0); } /** * Determine whether a char is a URI character (reserved or * unreserved, not including '%' for escaped octets). * * @return true if the char is a URI character, false otherwise */ private static boolean isURICharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0); } /** * Determine whether a char is a scheme character. * * @return true if the char is a scheme character, false otherwise */ private static boolean isSchemeCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0); } /** * Determine whether a char is a userinfo character. * * @return true if the char is a userinfo character, false otherwise */ private static boolean isUserinfoCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0); } /** * Determine whether a char is a path character. * * @return true if the char is a path character, false otherwise */ private static boolean isPathCharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0); } /** * Determine whether a given string contains only URI characters (also * called "uric" in RFC 2396). uric consist of all reserved * characters, unreserved characters and escaped characters. * * @return true if the string is comprised of uric, false otherwise */ private static boolean isURIString(String p_uric) { if (p_uric == null) { return false; } int end = p_uric.length(); char testChar = '\0'; for (int i = 0; i < end; i++) { testChar = p_uric.charAt(i); if (testChar == '%') { if (i+2 >= end || !isHex(p_uric.charAt(i+1)) || !isHex(p_uric.charAt(i+2))) { return false; } else { i += 2; continue; } } if (isURICharacter(testChar)) { continue; } else { return false; } } return true; } }
7,392
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Token.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting primitive XSD data type Token. * token represents tokenized strings. * The base type of token is normalizedString. * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#token">XML Schema 3.3.2</a> */ public class Token extends NormalizedString { public Token() { super(); } /** * ctor for Token * @exception IllegalArgumentException will be thrown if validation fails */ public Token(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badToken00") + "data=[" + stValue + "]"); } } /** * * validate the value against the xsd definition * * The value space of token is the set of strings that do not * contain the line feed (#xA) nor tab (#x9) characters, that * have no leading or trailing spaces (#x20) and that have no * internal sequences of two or more spaces. The lexical space * of token is the set of strings that do not contain the line * feed (#xA) nor tab (#x9) characters, that have no leading or * trailing spaces (#x20) and that have no internal sequences of two * or more spaces. */ public static boolean isValid(String stValue) { int scan; // check to see if we have a string to review if ( (stValue == null) || (stValue.length() == 0) ) return true; // no leading space if (stValue.charAt(0) == 0x20) return false; // no trail space if (stValue.charAt(stValue.length() - 1) == 0x20) return false; for (scan=0; scan < stValue.length(); scan++) { char cDigit = stValue.charAt(scan); switch (cDigit) { case 0x09: case 0x0A: return false; case 0x20: // no doublspace if (scan+1 < stValue.length()) if (stValue.charAt(scan + 1) == 0x20) { return false; } default: break; } } return true; } /** * * validates the data and sets the value for the object. * @param stValue String value * @throws IllegalArgumentException if invalid format */ public void setValue(String stValue) throws IllegalArgumentException { if (Token.isValid(stValue) == false) throw new IllegalArgumentException( Messages.getMessage("badToken00") + " data=[" + stValue + "]"); m_value = stValue; } }
7,393
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Language.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting XSD data type language * language represents natural language identifiers as defined by [RFC 1766]. * The value space of language is the set of all strings that are valid language identifiers * as defined in the language identification section of [XML 1.0 (Second Edition)]. * The lexical space of language is the set of all strings that are valid language identifiers * as defined in the language identification section of [XML 1.0 (Second Edition)]. * The base type of language is token. * * @author Eddie Pick (eddie@pick.eu.org) * @see <a href="http://www.w3.org/TR/xmlschema-2/#language">XML Schema 3.3.3</a> */ public class Language extends Token { public Language() { super(); } /** * ctor for Language * @exception IllegalArgumentException will be thrown if validation fails */ public Language(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badLanguage00") + "data=[" + stValue + "]"); } } /** * * validate the value against the xsd definition * TODO * @see <a href="http://www.ietf.org/rfc/rfc1766.txt">RFC1766</a> * Language-Tag = Primary-tag *( "-" Subtag ) * Primary-tag = 1*8ALPHA * Subtag = 1*8ALPHA */ public static boolean isValid(String stValue) { return true; } }
7,394
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/UnsignedInt.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; /** * Custom class for supporting primitive XSD data type UnsignedInt * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#unsignedInt">XML Schema 3.3.22</a> */ public class UnsignedInt extends java.lang.Number implements java.lang.Comparable { protected Long lValue = new Long(0); public UnsignedInt() { } /** * ctor for UnsignedInt * @exception NumberFormatException will be thrown if validation fails */ public UnsignedInt(long iValue) throws NumberFormatException { setValue(iValue); } public UnsignedInt(String stValue) throws NumberFormatException { setValue(Long.parseLong(stValue)); } /** * * validates the data and sets the value for the object. * * @param iValue value */ public void setValue(long iValue) throws NumberFormatException { if (UnsignedInt.isValid(iValue) == false) throw new NumberFormatException( Messages.getMessage("badUnsignedInt00") + String.valueOf(iValue) + "]"); lValue = new Long(iValue); } public String toString(){ if (lValue != null) return lValue.toString(); else return null; } public int hashCode(){ if (lValue != null) return lValue.hashCode(); else return 0; } /** * * validate the value against the xsd definition * */ public static boolean isValid(long iValue) { if ( (iValue < 0L) || (iValue > 4294967295L)) return false; else return true; } private Object __equalsCalc = null; public synchronized boolean equals(Object obj) { if (!(obj instanceof UnsignedInt)) return false; UnsignedInt other = (UnsignedInt) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((lValue ==null && other.lValue ==null) || (lValue !=null && lValue.equals(other.lValue))); __equalsCalc = null; return _equals; } // implement java.lang.comparable interface public int compareTo(Object obj) { if (lValue != null) return lValue.compareTo(obj); else if (equals(obj) == true) return 0; // null == null else return 1; // object is greater } // Implement java.lang.Number interface public byte byteValue() { return lValue.byteValue(); } public short shortValue() { return lValue.shortValue(); } public int intValue() { return lValue.intValue(); } public long longValue() { return lValue.longValue(); } public double doubleValue() { return lValue.doubleValue(); } public float floatValue() { return lValue.floatValue(); } }
7,395
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/Entity.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; /** * Custom class for supporting XSD data type Entity * * @author Davanum Srinivas (dims@yahoo.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#ENTITY">XML Schema 3.3.11 ENTITY</a> */ public class Entity extends NCName { public Entity() { super(); } /** * ctor for Entity * @exception IllegalArgumentException will be thrown if validation fails */ public Entity (String stValue) throws IllegalArgumentException { super(stValue); } }
7,396
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NMTokens.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * Custom class for supporting XSD data type NMTokens * * @author Davanum Srinivas (dims@yahoo.com) */ public class NMTokens extends NCName { private NMToken[] tokens; public NMTokens() { super(); } /** * ctor for NMTokens * @exception IllegalArgumentException will be thrown if validation fails */ public NMTokens (String stValue) throws IllegalArgumentException { setValue(stValue); } public void setValue(String stValue) { StringTokenizer tokenizer = new StringTokenizer(stValue); int count = tokenizer.countTokens(); tokens = new NMToken[count]; for(int i=0;i<count;i++){ tokens[i] = new NMToken(tokenizer.nextToken()); } } public String toString() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < tokens.length; i++) { NMToken token = tokens[i]; if (i > 0) buf.append(" "); buf.append(token.toString()); } return buf.toString(); } /** * NMTokens can be equal without having identical ordering because * they represent a set of references. Hence we have to compare * values here as a set, not a list. * * @param object an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean equals(Object object) { if (object == this) { return true; // succeed quickly, when possible } if (object instanceof NMTokens) { NMTokens that = (NMTokens)object; if (this.tokens.length == that.tokens.length) { Set ourSet = new HashSet(Arrays.asList(this.tokens)); Set theirSet = new HashSet(Arrays.asList(that.tokens)); return ourSet.equals(theirSet); } else { return false; } } else { return false; } } /** * Returns the sum of the hashcodes of the underlying tokens, an * operation which is not sensitive to ordering. * * @return an <code>int</code> value */ public int hashCode() { int hash = 0; for (int i = 0; i < tokens.length; i++) { hash += tokens[i].hashCode(); } return hash; } }
7,397
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/NCName.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLChar; /** * Custom class for supporting XSD data type NCName * NCName represents XML "non-colonized" Names * The base type of NCName is Name. * * @author Chris Haddad (chaddad@cobia.net) * @see <a href="http://www.w3.org/TR/xmlschema-2/#NCName">XML Schema 3.3.7</a> * @see <A href="http://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName">NCName Production</a> */ public class NCName extends Name { public NCName() { super(); } /** * ctor for NCName * @exception IllegalArgumentException will be thrown if validation fails */ public NCName(String stValue) throws IllegalArgumentException { try { setValue(stValue); } catch (IllegalArgumentException e) { // recast normalizedString exception as token exception throw new IllegalArgumentException( Messages.getMessage("badNCNameType00") + "data=[" + stValue + "]"); } } /** * * validates the data and sets the value for the object. * @param stValue String value * @throws IllegalArgumentException if invalid format */ public void setValue(String stValue) throws IllegalArgumentException { if (NCName.isValid(stValue) == false) throw new IllegalArgumentException( Messages.getMessage("badNCNameType00") + " data=[" + stValue + "]"); m_value = stValue; } /** * * validate the value against the xsd definition * * NCName ::= (Letter | '_') (NCNameChar)* * NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar | Extender */ public static boolean isValid(String stValue) { int scan; boolean bValid = true; for (scan=0; scan < stValue.length(); scan++) { if (scan == 0) bValid = XMLChar.isNCNameStart(stValue.charAt(scan)); else bValid = XMLChar.isNCName(stValue.charAt(scan)); if (bValid == false) break; } return bValid; } }
7,398
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/types/IDRefs.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.types; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * Custom class for supporting XSD data type IDRefs * * @author Davanum Srinivas (dims@yahoo.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#IDREFS">XML Schema 3.3.10 IDREFS</a> */ public class IDRefs extends NCName { private IDRef[] idrefs; public IDRefs() { super(); } /** * ctor for IDRefs * @exception IllegalArgumentException will be thrown if validation fails */ public IDRefs (String stValue) throws IllegalArgumentException { setValue(stValue); } public void setValue(String stValue) { StringTokenizer tokenizer = new StringTokenizer(stValue); int count = tokenizer.countTokens(); idrefs = new IDRef[count]; for(int i=0;i<count;i++){ idrefs[i] = new IDRef(tokenizer.nextToken()); } } public String toString() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < idrefs.length; i++) { IDRef ref = idrefs[i]; if (i > 0) buf.append(" "); buf.append(ref.toString()); } return buf.toString(); } /** * IDREFs can be equal without having identical ordering because * they represent a set of references. Hence we have to compare * values here as a set, not a list. * * @param object an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean equals(Object object) { if (object == this) { return true; // succeed quickly, when possible } if (object instanceof IDRefs) { IDRefs that = (IDRefs)object; if (this.idrefs.length == that.idrefs.length) { Set ourSet = new HashSet(Arrays.asList(this.idrefs)); Set theirSet = new HashSet(Arrays.asList(that.idrefs)); return ourSet.equals(theirSet); } else { return false; } } else { return false; } } /** * Returns the sum of the hashcodes of the underlying idrefs, an * operation which is not sensitive to ordering. * * @return an <code>int</code> value */ public int hashCode() { int hash = 0; for (int i = 0; i < idrefs.length; i++) { hash += idrefs[i].hashCode(); } return hash; } }
7,399