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/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/warehouse/WarehouseSoapBindingImplB.java
/** * WarehouseSoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis #axisVersion# #today# WSDL2Java emitter. */ package org.apache.axis.wsi.scm.warehouse; public class WarehouseSoapBindingImplB implements org.apache.axis.wsi.scm.warehouse.WarehouseShipmentsPortType{ public org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList shipGoods(org.apache.axis.wsi.scm.warehouse.ItemList itemList, org.apache.axis.types.NormalizedString customer, org.apache.axis.wsi.scm.configuration.ConfigurationType configurationHeader) throws java.rmi.RemoteException, org.apache.axis.wsi.scm.configuration.ConfigurationFaultType { return null; } }
6,800
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/warehouse/WarehouseSoapBindingImplC.java
/** * WarehouseSoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis #axisVersion# #today# WSDL2Java emitter. */ package org.apache.axis.wsi.scm.warehouse; public class WarehouseSoapBindingImplC implements org.apache.axis.wsi.scm.warehouse.WarehouseShipmentsPortType{ public org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList shipGoods(org.apache.axis.wsi.scm.warehouse.ItemList itemList, org.apache.axis.types.NormalizedString customer, org.apache.axis.wsi.scm.configuration.ConfigurationType configurationHeader) throws java.rmi.RemoteException, org.apache.axis.wsi.scm.configuration.ConfigurationFaultType { return null; } }
6,801
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/warehouse/WarehouseServiceTestCase.java
/** * WarehouseServiceTestCase.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2alpha Jan 15, 2004 (11:28:11 EST) WSDL2Java emitter. */ package org.apache.axis.wsi.scm.warehouse; public class WarehouseServiceTestCase extends junit.framework.TestCase { public WarehouseServiceTestCase(java.lang.String name) { super(name); } /* FIXME: RUNTIME WSDL broken. public void testWarehouseBPortWSDL() throws Exception { javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance(); java.net.URL url = new java.net.URL(new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseBPortAddress() + "?WSDL"); javax.xml.rpc.Service service = serviceFactory.createService(url, new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getServiceName()); assertTrue(service != null); } */ public void test1WarehouseBPortShipGoods() throws Exception { org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub) new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseBPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation try { org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList value = null; value = binding.shipGoods(new org.apache.axis.wsi.scm.warehouse.ItemList(), new org.apache.axis.types.NormalizedString(), new org.apache.axis.wsi.scm.configuration.ConfigurationType()); } catch (org.apache.axis.wsi.scm.configuration.ConfigurationFaultType e1) { throw new junit.framework.AssertionFailedError("ConfigurationFault Exception caught: " + e1); } // TBD - validate results } /* public void testWarehouseCPortWSDL() throws Exception { javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance(); java.net.URL url = new java.net.URL(new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseCPortAddress() + "?WSDL"); javax.xml.rpc.Service service = serviceFactory.createService(url, new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getServiceName()); assertTrue(service != null); } */ public void test2WarehouseCPortShipGoods() throws Exception { org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub) new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseCPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation try { org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList value = null; value = binding.shipGoods(new org.apache.axis.wsi.scm.warehouse.ItemList(), new org.apache.axis.types.NormalizedString(), new org.apache.axis.wsi.scm.configuration.ConfigurationType()); } catch (org.apache.axis.wsi.scm.configuration.ConfigurationFaultType e1) { throw new junit.framework.AssertionFailedError("ConfigurationFault Exception caught: " + e1); } // TBD - validate results } /* public void testWarehouseAPortWSDL() throws Exception { javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance(); java.net.URL url = new java.net.URL(new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseAPortAddress() + "?WSDL"); javax.xml.rpc.Service service = serviceFactory.createService(url, new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getServiceName()); assertTrue(service != null); } */ public void test3WarehouseAPortShipGoods() throws Exception { org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.warehouse.WarehouseSoapBindingStub) new org.apache.axis.wsi.scm.warehouse.WarehouseServiceLocator().getWarehouseAPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation try { org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList value = null; value = binding.shipGoods(new org.apache.axis.wsi.scm.warehouse.ItemList(), new org.apache.axis.types.NormalizedString(), new org.apache.axis.wsi.scm.configuration.ConfigurationType()); } catch (org.apache.axis.wsi.scm.configuration.ConfigurationFaultType e1) { throw new junit.framework.AssertionFailedError("ConfigurationFault Exception caught: " + e1); } // TBD - validate results } }
6,802
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/warehouse/WarehouseSoapBindingImplA.java
/** * WarehouseSoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis #axisVersion# #today# WSDL2Java emitter. */ package org.apache.axis.wsi.scm.warehouse; public class WarehouseSoapBindingImplA implements org.apache.axis.wsi.scm.warehouse.WarehouseShipmentsPortType{ public org.apache.axis.wsi.scm.warehouse.ItemShippingStatusList shipGoods(org.apache.axis.wsi.scm.warehouse.ItemList itemList, org.apache.axis.types.NormalizedString customer, org.apache.axis.wsi.scm.configuration.ConfigurationType configurationHeader) throws java.rmi.RemoteException, org.apache.axis.wsi.scm.configuration.ConfigurationFaultType { return null; } }
6,803
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/logging/LoggingFacilityClient.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.wsi.scm.logging; /** * Test client for LoggingFacilityService * * @author Ias (iasandcb@tmax.co.kr) */ public class LoggingFacilityClient { public static void main(String [] args) throws Exception { // Make a service LoggingFacilityService service = new LoggingFacilityServiceLocator(); // Now use the service to get a stub which implements the SEI. LoggingFacilityLogPortType port = service.getLoggingFacilityPort(); port.logEvent(null); GetEventsResponseType response = port.getEvents(null); System.out.println(response); } }
6,804
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/logging/LoggingFacilitySoapBindingImpl.java
/** * LoggingFacilitySoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis #axisVersion# #today# WSDL2Java emitter. */ package org.apache.axis.wsi.scm.logging; public class LoggingFacilitySoapBindingImpl implements org.apache.axis.wsi.scm.logging.LoggingFacilityLogPortType{ public void logEvent(org.apache.axis.wsi.scm.logging.LogEventRequestType document) throws java.rmi.RemoteException { } public org.apache.axis.wsi.scm.logging.GetEventsResponseType getEvents(org.apache.axis.wsi.scm.logging.GetEventsRequestType document) throws java.rmi.RemoteException, org.apache.axis.wsi.scm.logging.GetEventsFaultType { return null; } }
6,805
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/logging/LoggingFacilityServiceTestCase.java
/** * LoggingFacilityServiceTestCase.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2alpha Jan 15, 2004 (11:28:11 EST) WSDL2Java emitter. */ package org.apache.axis.wsi.scm.logging; public class LoggingFacilityServiceTestCase extends junit.framework.TestCase { public LoggingFacilityServiceTestCase(java.lang.String name) { super(name); } /* FIXME: RUNTIME WSDL broken. public void testLoggingFacilityPortWSDL() throws Exception { javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance(); java.net.URL url = new java.net.URL(new org.apache.axis.wsi.scm.logging.LoggingFacilityServiceLocator().getLoggingFacilityPortAddress() + "?WSDL"); javax.xml.rpc.Service service = serviceFactory.createService(url, new org.apache.axis.wsi.scm.logging.LoggingFacilityServiceLocator().getServiceName()); assertTrue(service != null); } */ public void test1LoggingFacilityPortLogEvent() throws Exception { org.apache.axis.wsi.scm.logging.LoggingFacilitySoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.logging.LoggingFacilitySoapBindingStub) new org.apache.axis.wsi.scm.logging.LoggingFacilityServiceLocator().getLoggingFacilityPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation binding.logEvent(new org.apache.axis.wsi.scm.logging.LogEventRequestType()); // TBD - validate results } public void test2LoggingFacilityPortGetEvents() throws Exception { org.apache.axis.wsi.scm.logging.LoggingFacilitySoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.logging.LoggingFacilitySoapBindingStub) new org.apache.axis.wsi.scm.logging.LoggingFacilityServiceLocator().getLoggingFacilityPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation try { org.apache.axis.wsi.scm.logging.GetEventsResponseType value = null; value = binding.getEvents(new org.apache.axis.wsi.scm.logging.GetEventsRequestType()); } catch (org.apache.axis.wsi.scm.logging.GetEventsFaultType e1) { throw new junit.framework.AssertionFailedError("RepositoryMissingFault Exception caught: " + e1); } // TBD - validate results } }
6,806
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/retailer/RetailerClient.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.wsi.scm.retailer; import org.apache.axis.wsi.scm.retailer.catalog.CatalogItem; import org.apache.axis.wsi.scm.retailer.catalog.CatalogType; /** * Test client for RetailerService * * @author Ias (iasandcb@tmax.co.kr) */ public class RetailerClient { public static void main(String[] args) throws Exception { // Make a service RetailerService service = new RetailerServiceLocator(); // Now use the service to get a stub which implements the SEI. RetailerPortType port = service.getRetailerPort(); CatalogType catalog = port.getCatalog(); CatalogItem[] items = catalog.getItem(); for (int i = 0; i < items.length; i++) { System.out.println("------------------"); CatalogItem item = items[i]; System.out.println(item.getBrand()); } } }
6,807
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/retailer/RetailerServiceTestCase.java
/** * RetailerServiceTestCase.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2alpha Jan 15, 2004 (11:28:11 EST) WSDL2Java emitter. */ package org.apache.axis.wsi.scm.retailer; public class RetailerServiceTestCase extends junit.framework.TestCase { public RetailerServiceTestCase(java.lang.String name) { super(name); } /* FIXME: RUNTIME WSDL broken. public void testRetailerPortWSDL() throws Exception { javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance(); java.net.URL url = new java.net.URL(new org.apache.axis.wsi.scm.retailer.RetailerServiceLocator().getRetailerPortAddress() + "?WSDL"); javax.xml.rpc.Service service = serviceFactory.createService(url, new org.apache.axis.wsi.scm.retailer.RetailerServiceLocator().getServiceName()); assertTrue(service != null); } */ public void test1RetailerPortGetCatalog() throws Exception { org.apache.axis.wsi.scm.retailer.RetailerSoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.retailer.RetailerSoapBindingStub) new org.apache.axis.wsi.scm.retailer.RetailerServiceLocator().getRetailerPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation org.apache.axis.wsi.scm.retailer.catalog.CatalogType catalog = null; catalog = binding.getCatalog(); // TBD - validate results assertNotNull("catalog is null", catalog); org.apache.axis.wsi.scm.retailer.catalog.CatalogItem[] items = catalog.getItem(); assertTrue(items.length > 0); for (int i = 0; i < items.length; i++) { System.out.println("------------------"); System.out.println(items[i].getName()); System.out.println(items[i].getBrand()); } } public void test2RetailerPortSubmitOrder() throws Exception { org.apache.axis.wsi.scm.retailer.RetailerSoapBindingStub binding; try { binding = (org.apache.axis.wsi.scm.retailer.RetailerSoapBindingStub) new org.apache.axis.wsi.scm.retailer.RetailerServiceLocator().getRetailerPort(); } catch (javax.xml.rpc.ServiceException jre) { if(jre.getLinkedCause()!=null) jre.getLinkedCause().printStackTrace(); throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre); } assertNotNull("binding is null", binding); // Time out after a minute binding.setTimeout(60000); // Test operation try { org.apache.axis.wsi.scm.retailer.order.PartsOrderResponseType value = null; value = binding.submitOrder(new org.apache.axis.wsi.scm.retailer.order.PartsOrderType(), new org.apache.axis.wsi.scm.retailer.order.CustomerDetailsType(), new org.apache.axis.wsi.scm.configuration.ConfigurationType()); } catch (org.apache.axis.wsi.scm.retailer.order.InvalidProductCodeType e1) { throw new junit.framework.AssertionFailedError("InvalidProductCode Exception caught: " + e1); } catch (org.apache.axis.wsi.scm.retailer.BadOrderFault e2) { throw new junit.framework.AssertionFailedError("BadOrder Exception caught: " + e2); } catch (org.apache.axis.wsi.scm.configuration.ConfigurationFaultType e3) { throw new junit.framework.AssertionFailedError("ConfigurationFault Exception caught: " + e3); } // TBD - validate results } }
6,808
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ws-i/scm/source/java/implemented/org/apache/axis/wsi/scm/retailer/RetailerSoapBindingImpl.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.wsi.scm.retailer; import java.math.BigDecimal; import javax.xml.rpc.ServiceException; import javax.xml.rpc.server.ServiceLifecycle; import org.apache.axis.wsi.scm.retailer.catalog.CatalogItem; import org.apache.axis.wsi.scm.retailer.catalog.CatalogType; /** * Implementation of RetailerPortType * * @author Ias (iasandcb@tmax.co.kr) */ public class RetailerSoapBindingImpl implements org.apache.axis.wsi.scm.retailer.RetailerPortType, ServiceLifecycle { CatalogType catalog = new CatalogType(); public org.apache.axis.wsi.scm.retailer.catalog.CatalogType getCatalog() throws java.rmi.RemoteException { return catalog; } public org.apache.axis.wsi.scm.retailer.order.PartsOrderResponseType submitOrder( org.apache.axis.wsi.scm.retailer.order.PartsOrderType partsOrder, org.apache.axis.wsi.scm.retailer.order.CustomerDetailsType customerDetails, org.apache.axis.wsi.scm.configuration.ConfigurationType configurationHeader) throws java.rmi.RemoteException, org.apache.axis.wsi.scm.retailer.order.InvalidProductCodeType, org.apache.axis.wsi.scm.retailer.BadOrderFault, org.apache.axis.wsi.scm.configuration.ConfigurationFaultType { return null; } /** * @see javax.xml.rpc.server.ServiceLifecycle#init(java.lang.Object) */ public void init(Object context) throws ServiceException { CatalogItem[] items = new CatalogItem[10]; items[0] = new CatalogItem(); items[0].setName("TV, Brand1"); items[0].setDescription("24in, Color, Advanced Velocity Scan Modulation, Stereo"); items[0].setProductNumber(new java.math.BigInteger("605001")); items[0].setCategory("TV"); items[0].setBrand("Brand1"); items[0].setPrice((new BigDecimal(299.95)).setScale(2, BigDecimal.ROUND_HALF_UP)); items[1] = new CatalogItem(); items[1].setName("TV, Brand2"); items[1].setDescription("32in, Super Slim Flat Panel Plasma"); items[1].setProductNumber(new java.math.BigInteger("605002")); items[1].setCategory("TV"); items[1].setBrand("Brand2"); items[1].setPrice((new BigDecimal(1499.99)).setScale(2, BigDecimal.ROUND_HALF_UP)); items[2] = new CatalogItem(); items[2].setName("TV, Brand3"); items[2].setDescription("50in, Plasma Display"); items[2].setProductNumber(new java.math.BigInteger("605003")); items[2].setCategory("TV"); items[2].setBrand("Brand3"); items[2].setPrice(new BigDecimal("5725.98")); items[3] = new CatalogItem(); items[3].setName("Video, Brand1"); items[3].setDescription("S-VHS"); items[3].setProductNumber(new java.math.BigInteger("605004")); items[3].setCategory("Video"); items[3].setBrand("Brand1"); items[3].setPrice(new BigDecimal("199.95")); items[4] = new CatalogItem(); items[4].setName("Video, Brand2"); items[4].setDescription("HiFi, S-VHS"); items[4].setProductNumber(new java.math.BigInteger("605005")); items[4].setCategory("Video"); items[4].setBrand("Brand2"); items[4].setPrice(new BigDecimal("400.00")); items[5] = new CatalogItem(); items[5].setName("Video, Brand3"); items[5].setDescription("s-vhs, mindv"); items[5].setProductNumber(new java.math.BigInteger("605006")); items[5].setCategory("Video"); items[5].setBrand("Brand3"); items[5].setPrice(new BigDecimal("949.99")); items[6] = new CatalogItem(); items[6].setName("DVD, Brand1"); items[6].setDescription("DVD-Player W/Built-In Dolby Digital Decoder"); items[6].setProductNumber(new java.math.BigInteger("605007")); items[6].setCategory("DVD"); items[6].setBrand("Brand1"); items[6].setPrice(new BigDecimal("100.00")); items[7] = new CatalogItem(); items[7].setName("DVD, Brand2"); items[7].setDescription( "Plays DVD-Video discs, CDs, stereo and multi-channel SACDs, and audio CD-Rs & CD-RWs, 27MHz/10-bit video DAC, "); items[7].setProductNumber(new java.math.BigInteger("605008")); items[7].setCategory("DVD"); items[7].setBrand("Brand2"); items[7].setPrice(new BigDecimal("200.00")); items[8] = new CatalogItem(); items[8].setName("DVD, Brand3"); items[8].setDescription( "DVD Player with SmoothSlow forward/reverse; Digital Video Enhancer; DVD/CD Text; Custom Parental Control (20-disc); Digital Cinema Sound modes"); items[8].setProductNumber(new java.math.BigInteger("605009")); items[8].setCategory("DVD"); items[8].setBrand("Brand3"); items[8].setPrice(new BigDecimal("250.00")); // This one is an invalid product items[9] = new CatalogItem(); items[9].setName("TV, Brand4"); items[9].setDescription( "Designated invalid product code that is allowed to appear in the catalog, but is unable to be ordered"); items[9].setProductNumber(new java.math.BigInteger("605010")); items[9].setCategory("TV"); items[9].setBrand("Brand4"); items[9].setPrice(new BigDecimal("149.99")); catalog.setItem(items); } /** * @see javax.xml.rpc.server.ServiceLifecycle#destroy() */ public void destroy() { } }
6,809
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example2/CalcClient.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example2 ; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.utils.Options; import javax.xml.rpc.ParameterMode; public class CalcClient { public static void main(String [] args) throws Exception { Options options = new Options(args); String endpoint = "http://localhost:" + options.getPort() + "/axis/Calculator.jws"; args = options.getRemainingArgs(); if (args == null || args.length != 3) { System.err.println("Usage: CalcClient <add|subtract> arg1 arg2"); return; } String method = args[0]; if (!(method.equals("add") || method.equals("subtract"))) { System.err.println("Usage: CalcClient <add|subtract> arg1 arg2"); return; } Integer i1 = new Integer(args[1]); Integer i2 = new Integer(args[2]); Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName( method ); call.addParameter( "op1", XMLType.XSD_INT, ParameterMode.IN ); call.addParameter( "op2", XMLType.XSD_INT, ParameterMode.IN ); call.setReturnType( XMLType.XSD_INT ); Integer ret = (Integer) call.invoke( new Object [] { i1, i2 }); System.out.println("Got result : " + ret); } }
6,810
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example2/Calculator.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Calculator { public int add(int i1, int i2) { return i1 + i2; } public int subtract(int i1, int i2) { return i1 - i2; } }
6,811
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example5/BeanService.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example5; public class BeanService { public String processOrder(Order order) { String sep = System.getProperty("line.separator"); String response = "Hi, " + order.getCustomerName() + "!" + sep; response += sep + "You seem to have ordered the following:" + sep; String [] items = order.getItemCodes(); int [] quantities = order.getQuantities(); for (int i = 0; i < items.length; i++) { response += sep + quantities[i] + " of item : " + items[i]; } response += sep + sep + "If this had been a real order processing system, "+ "we'd probably have charged you about now."; return response; } }
6,812
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example5/Order.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example5; /** This is a JavaBean which represents an order for some products. * * @author Glen Daniels (gdaniels@apache.org) */ public class Order { /** Who's ordering */ private String customerName; /** Where do they live */ private String shippingAddress; /** Which items do we want */ private String itemCodes[]; /** And how many */ private int quantities[]; // Bean accessors public String getCustomerName() { return customerName; } public void setCustomerName(String name) { customerName = name; } public String getShippingAddress() { return shippingAddress; } public void setShippingAddress(String address) { shippingAddress = address; } public String [] getItemCodes() { return itemCodes; } public void setItemCodes(String [] items) { itemCodes = items; } public int [] getQuantities() { return quantities; } public void setQuantities(int [] quants) { quantities = quants; } }
6,813
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example5/Client.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example5; import org.apache.axis.AxisFault; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.utils.Options; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; public class Client { public static void main(String [] args) throws Exception { Options options = new Options(args); Order order = new Order(); order.setCustomerName("Glen Daniels"); order.setShippingAddress("275 Grove Street, Newton, MA"); String [] items = new String[] { "mp3jukebox", "1600mahBattery" }; int [] quantities = new int [] { 1, 4 }; order.setItemCodes(items); order.setQuantities(quantities); Service service = new Service(); Call call = (Call) service.createCall(); QName qn = new QName( "urn:BeanService", "Order" ); call.registerTypeMapping(Order.class, qn, new org.apache.axis.encoding.ser.BeanSerializerFactory(Order.class, qn), new org.apache.axis.encoding.ser.BeanDeserializerFactory(Order.class, qn)); String result; try { call.setTargetEndpointAddress( new java.net.URL(options.getURL()) ); call.setOperationName( new QName("OrderProcessor", "processOrder") ); call.addParameter( "arg1", qn, ParameterMode.IN ); call.setReturnType( org.apache.axis.encoding.XMLType.XSD_STRING ); result = (String) call.invoke( new Object[] { order } ); } catch (AxisFault fault) { result = "Error : " + fault.toString(); } System.out.println(result); } }
6,814
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example4/Client.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example4; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.utils.Options; import javax.xml.namespace.QName; public class Client { public static void main(String [] args) { try { Options options = new Options(args); String endpointURL = options.getURL(); Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpointURL) ); call.setOperationName( new QName("LogTestService", "testMethod") ); String res = (String) call.invoke( new Object[] {} ); System.out.println( res ); } catch (Exception e) { System.err.println(e.toString()); } } }
6,815
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example4/LogHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example4; import org.apache.axis.AxisFault; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.handlers.BasicHandler; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Date; public class LogHandler extends BasicHandler { public void invoke(MessageContext msgContext) throws AxisFault { /** Log an access each time we get invoked. */ try { Handler serviceHandler = msgContext.getService(); String filename = (String)getOption("filename"); if ((filename == null) || (filename.equals(""))) throw new AxisFault("Server.NoLogFile", "No log file configured for the LogHandler!", null, null); FileOutputStream fos = new FileOutputStream(filename, true); PrintWriter writer = new PrintWriter(fos); Integer numAccesses = (Integer)serviceHandler.getOption("accesses"); if (numAccesses == null) numAccesses = new Integer(0); numAccesses = new Integer(numAccesses.intValue() + 1); Date date = new Date(); String result = date + ": service " + msgContext.getTargetService() + " accessed " + numAccesses + " time(s)."; serviceHandler.setOption("accesses", numAccesses); writer.println(result); writer.close(); } catch (Exception e) { throw AxisFault.makeFault(e); } } }
6,816
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example4/Service.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example4; public class Service { public String testMethod() { return "Hi, you've reached the testMethod."; } }
6,817
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example3/Client.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example3; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.utils.Options; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; public class Client { public static void main(String [] args) { try { Options options = new Options(args); String endpointURL = options.getURL(); String textToSend; args = options.getRemainingArgs(); if ((args == null) || (args.length < 1)) { textToSend = "<nothing>"; } else { textToSend = args[0]; } Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpointURL) ); call.setOperationName( new QName("http://example3.userguide.samples", "serviceMethod") ); call.addParameter( "arg1", XMLType.XSD_STRING, ParameterMode.IN); call.setReturnType( org.apache.axis.encoding.XMLType.XSD_STRING ); String ret = (String) call.invoke( new Object[] { textToSend } ); System.out.println("You typed : " + ret); } catch (Exception e) { System.err.println(e.toString()); } } }
6,818
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example3/MyService.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example3; public class MyService { public String serviceMethod(String arg) { return arg; } }
6,819
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example6/WidgetPrice.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example6; /** * Interface describing a web service to set and get Widget prices. **/ public interface WidgetPrice { public void setWidgetPrice(String widgetName, String price); public String getWidgetPrice(String widgetName); }
6,820
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example6/WidgetPriceServiceTestCase.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WidgetPriceServiceTestCase.java * */ package samples.userguide.example6; public class WidgetPriceServiceTestCase extends junit.framework.TestCase { public WidgetPriceServiceTestCase(String name) { super(name); } public void testWidgetPrice() { samples.userguide.example6.WidgetPrice binding; try { binding = new WidgetPriceServiceLocator().getWidgetPrice(); } catch (javax.xml.rpc.ServiceException jre) { throw new junit.framework.AssertionFailedError("JAX-RPC ServiceException caught: " + jre ); } ((WidgetPriceSoapBindingStub)binding).setMaintainSession(true); assertTrue("binding is null", binding != null); try { binding.setWidgetPrice("FOO", "$1.00"); } catch (java.rmi.RemoteException re) { throw new junit.framework.AssertionFailedError("Remote Exception caught: " + re ); } try { java.lang.String value = null; value = binding.getWidgetPrice("FOO"); assertTrue("Wrong Price" + value, value.equals("$1.00")); } catch (java.rmi.RemoteException re) { throw new junit.framework.AssertionFailedError("Remote Exception caught: " + re ); } } }
6,821
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example6/Main.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Main.java * * This file was auto-generated from WSDL * by the Apache Axis Wsdl2java emitter. */ package samples.userguide.example6; public class Main { public static void main (String[] args) throws Exception { samples.userguide.example6.WidgetPrice binding = new WidgetPriceServiceLocator().getWidgetPrice(); ((WidgetPriceSoapBindingStub)binding).setMaintainSession(true); try { ((WidgetPriceSoapBindingStub) binding).setWidgetPrice("FOO", "$1.00"); } catch (java.rmi.RemoteException re) { throw new junit.framework.AssertionFailedError("Remote Exception caught: " + re ); } try { java.lang.String value = null; value = binding.getWidgetPrice("FOO"); if (value == null || !value.equals("$1.00")) System.out.println("Wrong Price" + value); } catch (java.rmi.RemoteException re) { throw new junit.framework.AssertionFailedError("Remote Exception caught: " + re ); } } }
6,822
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example6/WidgetPriceSoapBindingImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WidgetPriceSoapBindingImpl.java * * This file is the SOAP implementation of the WidgetPrice Web Service */ package samples.userguide.example6; import java.util.HashMap; public class WidgetPriceSoapBindingImpl implements samples.userguide.example6.WidgetPrice { HashMap table = new HashMap(); public void setWidgetPrice(java.lang.String name, java.lang.String price) throws java.rmi.RemoteException { table.put(name, price); } public java.lang.String getWidgetPrice(java.lang.String name) throws java.rmi.RemoteException { return (String) table.get(name); } }
6,823
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide
Create_ds/axis-axis1-java/distribution/src/main/files/samples/userguide/example1/TestClient.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.userguide.example1; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import javax.xml.namespace.QName; public class TestClient { public static void main(String [] args) { try { String endpoint = "http://nagoya.apache.org:5049/axis/services/echo"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName(new QName("http://soapinterop.org/", "echoString") ); // Call to addParameter/setReturnType as described in user-guide.html //call.addParameter("testParam", // org.apache.axis.Constants.XSD_STRING, // javax.xml.rpc.ParameterMode.IN); //call.setReturnType(org.apache.axis.Constants.XSD_STRING); String ret = (String) call.invoke( new Object[] { "Hello!" } ); System.out.println("Sent 'Hello!', got '" + ret + "'"); } catch (Exception e) { System.err.println(e.toString()); } } }
6,824
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/math/Math.java
package samples.math; public class Math { public float add(float a, float b) { return a+b; } }
6,825
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/perf/PerfPortSoapBindingImpl.java
/** * PerfPortSoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2beta Apr 25, 2004 (11:19:16 EDT) WSDL2Java emitter. */ package samples.perf; public class PerfPortSoapBindingImpl implements samples.perf.PerfService_PortType{ public java.lang.String handleStringArray(java.lang.String[] s) throws java.rmi.RemoteException { String returnString; returnString = "array length was - " + s.length; return returnString; } }
6,826
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/swa/Tester.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.swa; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; /** * Class Tester * * @version %I%, %G% */ public class Tester { /** Field HEADER_CONTENT_TYPE */ public static final String HEADER_CONTENT_TYPE = "Content-Type"; /** Field HEADER_CONTENT_TRANSFER_ENCODING */ public static final String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; /** Field address */ private static final java.lang.String address = "http://localhost:8080/axis/services/SwaHttp"; /** * Method main * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { /* * Start to prepare service call. Once this is done, several * calls can be made on the port (see below) * * Fist: get the service locator. This implements the functionality * to get a client stub (aka port). */ SwaServiceLocator service = new SwaServiceLocator(); /* * Here we use an Axis specific call that allows to override the * port address (service endpoint address) with an own URL. Comes * in handy for testing. */ java.net.URL endpoint; try { endpoint = new java.net.URL(address); } catch (java.net.MalformedURLException e) { throw new javax.xml.rpc.ServiceException(e); } SwaPort port = (SwaPort) service.getSwaHttp(endpoint); /* * At this point all preparations are done. Using the port we can * now perform as many calls as necessary. */ /* * Prepare the Multipart attachment. It consists of several data files. The * multipart container is of type "multipart/mixed" */ MimeMultipart mpRoot = new MimeMultipart(); System.out.println("MimeMultipart content: " + mpRoot.getContentType()); DataHandler dh = new DataHandler(new FileDataSource("duke.gif")); addBodyPart(mpRoot, dh); dh = new DataHandler(new FileDataSource("pivots.jpg")); addBodyPart(mpRoot, dh); // perform call port.swaSend("AppName", mpRoot); } /** * Method addBodyPart * * @param mp * @param dh */ private static void addBodyPart(MimeMultipart mp, DataHandler dh) { MimeBodyPart messageBodyPart = new MimeBodyPart(); try { messageBodyPart.setDataHandler(dh); String contentType = dh.getContentType(); if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = "application/octet-stream"; } System.out.println("Content type: " + contentType); messageBodyPart.setHeader(HEADER_CONTENT_TYPE, contentType); messageBodyPart.setHeader( HEADER_CONTENT_TRANSFER_ENCODING, "binary"); // Safe and fastest for anything other than mail mp.addBodyPart(messageBodyPart); } catch (javax.mail.MessagingException e) { } } }
6,827
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/swa/SwaBindingImpl.java
/** * SwaBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2alpha Dec 07, 2003 (08:01:12 EST) WSDL2Java emitter. */ package samples.swa; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.attachments.AttachmentPart; import org.apache.axis.attachments.Attachments; import javax.activation.DataHandler; import javax.mail.internet.MimeBodyPart; import java.util.Iterator; /** * Class SwaBindingImpl * * @version %I%, %G% */ public class SwaBindingImpl implements samples.swa.SwaPort { /** * Method swaSend * * @param applicationName * @param content * @return * @throws java.rmi.RemoteException */ public java.lang.String swaSend( java.lang.String applicationName, javax.mail.internet.MimeMultipart content) throws java.rmi.RemoteException { MimeBodyPart mpb = null; System.out.println("Application: " + applicationName); /* * Now do some printing to get information about the multipart * content and the associated attachments. Axis performs * several steps during deserialization of this SOAP * call. Only the steps of interesst are described here. * * The MIME multipart that contains the other parts (because * it's multipart/mixed or multipart/related) is handled as * ONE Axis attachment during the first part of * deserialization. This attachment is identified by the CID: * prefixed string generated during serialization. * * The next step (see * MimeMultipartDataHandlerDeserializer.java) gets the data * handler of the Axis attachment and creates a MimeMultipart * object using the data source as input of the new * MimeMultipart object. The MimeMultipart object parses the * input (on demand? -> this need to be clarified) and builds * the associated body parts. * * The Axis attachment part is not disposed or otherwise * managed after it was serialized into the MimeMultipart * object. Therefore it is a good idea to call the dispose() * method of the Axis attachment part after processing is * complete. Doing so releases all used resources, also * deleting disk cache files if necessary, of this attachment * part. */ try { int contCount = content.getCount(); System.out.println("Number of Mimeparts: " + contCount); for (int i = 0; i < contCount; i++) { mpb = (MimeBodyPart) content.getBodyPart(i); DataHandler dh = mpb.getDataHandler(); System.out.println("Mime data type: " + dh.getContentType()); } } catch (javax.mail.MessagingException ex) { } /* * the next prints are just for information only */ AttachmentPart[] attParts = getMessageAttachments(); System.out.println("Number of attachements: " + attParts.length); if (attParts.length > 0) { try { System.out.println("Att[0] type: " + attParts[0].getContentType()); System.out.println( "Att[0] dh type: " + attParts[0].getDataHandler().getContentType()); System.out.println("Att[0] file: " + attParts[0].getAttachmentFile()); } catch (javax.xml.soap.SOAPException ex) { } } /* * Now process the parametes including the MimeMultipart */ /* * Processing is done, now dispose the attachements. This is not done * by Axis, should be done by service. */ MessageContext msgContext = MessageContext.getCurrentContext(); Message reqMsg = msgContext.getRequestMessage(); Attachments messageAttachments = reqMsg.getAttachmentsImpl(); messageAttachments.dispose(); return null; } /** * extract attachments from the current request * * @return a list of attachmentparts or * an empty array for no attachments support in this axis * buid/runtime * @throws AxisFault */ private AttachmentPart[] getMessageAttachments() throws AxisFault { MessageContext msgContext = MessageContext.getCurrentContext(); Message reqMsg = msgContext.getRequestMessage(); Attachments messageAttachments = reqMsg.getAttachmentsImpl(); int attachmentCount = messageAttachments.getAttachmentCount(); AttachmentPart attachments[] = new AttachmentPart[attachmentCount]; Iterator it = messageAttachments.getAttachments().iterator(); int count = 0; while (it.hasNext()) { AttachmentPart part = (AttachmentPart) it.next(); attachments[count++] = part; } return attachments; } }
6,828
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/swa/SwaTestCase.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.swa; import junit.framework.TestCase; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** * Test the SwA sample code. */ public class SwaTestCase extends TestCase { /** Field log */ static Log log = LogFactory.getLog(SwaTestCase.class.getName()); /** * Constructor SwaTestCase * * @param name */ public SwaTestCase(String name) { super(name); } /** * Method doTest * * @throws Exception */ public void doTest() throws Exception { String[] args = { }; Tester.main(args); } /** * Method testSwAService * * @throws Exception */ public void testSwAService() throws Exception { try { log.info("Testing SOAP with Attachements sample."); doTest(); log.info("Test complete."); } catch (Exception e) { e.printStackTrace(); throw new Exception("Fault returned from test: " + e); } } }
6,829
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/client/DynamicInvoker.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.client; import org.apache.axis.Constants; import org.apache.axis.utils.XMLUtils; import org.apache.axis.encoding.ser.SimpleDeserializer; import org.apache.axis.encoding.ser.ElementSerializerFactory; import org.apache.axis.encoding.ser.ElementDeserializerFactory; import org.apache.axis.encoding.ser.ElementDeserializer; import org.apache.axis.wsdl.gen.Parser; import org.apache.axis.wsdl.symbolTable.BaseType; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.w3c.dom.Element; import javax.wsdl.Binding; import javax.wsdl.Operation; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.extensions.soap.SOAPAddress; import javax.xml.namespace.QName; import javax.xml.rpc.Call; import javax.xml.rpc.encoding.Deserializer; import javax.xml.rpc.encoding.DeserializerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; /** * This sample shows how to use Axis for completely dynamic invocations * as it is completely stubless execution. It supports both doc/lit and rpc/encoded * services. But this sample does not support complex types * (it could if there was defined a to encode complex values as command line arguments). * * @author Davanum Srinivas (dims@yahoo.com) */ public class DynamicInvoker { /** Field wsdlParser */ private Parser wsdlParser = null; /** * Constructor DynamicInvoker * * @param wsdlURL * * @throws Exception */ public DynamicInvoker(String wsdlURL) throws Exception { // Start by reading in the WSDL using Parser wsdlParser = new Parser(); System.out.println("Reading WSDL document from '" + wsdlURL + "'"); wsdlParser.run(wsdlURL); } /** * Method usage */ private static void usage() { System.err.println( "Usage: java " + DynamicInvoker.class.getName() + " wsdlLocation " + "operationName[(portName)] " + "[argument1 ...]"); System.exit(1); } /** * Method main * * @param args * * @throws Exception */ public static void main(String[] args) throws Exception { if (args.length < 2) { usage(); } String wsdlLocation = (args.length > 0) ? args[0] : null; String operationName = (args.length > 1) ? args[1] : null; String portName = null; try { portName = operationName.substring(operationName.indexOf("(") + 1, operationName.indexOf(")")); operationName = operationName.substring(0, operationName.indexOf("(")); } catch (Exception ignored) { } DynamicInvoker invoker = new DynamicInvoker(wsdlLocation); HashMap map = invoker.invokeMethod(operationName, portName, args); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof Element) { System.out.println("====== " + key + " ======"); XMLUtils.ElementToStream((Element) value, System.out); System.out.println("========================="); } else { System.out.println(key + "=" + value); } } System.out.println("\nDone!"); } /** * Method invokeMethod * * @param wsdlLocation * @param operationName * @param inputName * @param outputName * @param portName * @param args * * @return * * @throws Exception */ public HashMap invokeMethod( String operationName, String portName, String[] args) throws Exception { String serviceNS = null; String serviceName = null; String operationQName = null; System.out.println("Preparing Axis dynamic invocation"); Service service = selectService(serviceNS, serviceName); Operation operation = null; org.apache.axis.client.Service dpf = new org.apache.axis.client.Service(wsdlParser, service.getQName()); Vector inputs = new Vector(); Port port = selectPort(service.getPorts(), portName); if (portName == null) { portName = port.getName(); } Binding binding = port.getBinding(); Call call = dpf.createCall(QName.valueOf(portName), QName.valueOf(operationName)); ((org.apache.axis.client.Call)call).setTimeout(new Integer(15*1000)); ((org.apache.axis.client.Call)call).setProperty(ElementDeserializer.DESERIALIZE_CURRENT_ELEMENT, Boolean.TRUE); // Output types and names Vector outNames = new Vector(); // Input types and names Vector inNames = new Vector(); Vector inTypes = new Vector(); SymbolTable symbolTable = wsdlParser.getSymbolTable(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); Parameters parameters = null; Iterator i = bEntry.getParameters().keySet().iterator(); while (i.hasNext()) { Operation o = (Operation) i.next(); if (o.getName().equals(operationName)) { operation = o; parameters = (Parameters) bEntry.getParameters().get(o); break; } } if ((operation == null) || (parameters == null)) { throw new RuntimeException(operationName + " was not found."); } // loop over paramters and set up in/out params for (int j = 0; j < parameters.list.size(); ++j) { Parameter p = (Parameter) parameters.list.get(j); if (p.getMode() == 1) { // IN inNames.add(p.getQName().getLocalPart()); inTypes.add(p); } else if (p.getMode() == 2) { // OUT outNames.add(p.getQName().getLocalPart()); } else if (p.getMode() == 3) { // INOUT inNames.add(p.getQName().getLocalPart()); inTypes.add(p); outNames.add(p.getQName().getLocalPart()); } } // set output type if (parameters.returnParam != null) { if(!parameters.returnParam.getType().isBaseType()) { ((org.apache.axis.client.Call)call).registerTypeMapping(org.w3c.dom.Element.class, parameters.returnParam.getType().getQName(), new ElementSerializerFactory(), new ElementDeserializerFactory()); } // Get the QName for the return Type QName returnType = org.apache.axis.wsdl.toJava.Utils.getXSIType( parameters.returnParam); QName returnQName = parameters.returnParam.getQName(); outNames.add(returnQName.getLocalPart()); } if (inNames.size() != args.length - 2) throw new RuntimeException("Need " + inNames.size() + " arguments!!!"); for (int pos = 0; pos < inNames.size(); ++pos) { String arg = args[pos + 2]; Parameter p = (Parameter) inTypes.get(pos); inputs.add(getParamData((org.apache.axis.client.Call) call, p, arg)); } System.out.println("Executing operation " + operationName + " with parameters:"); for (int j = 0; j < inputs.size(); j++) { System.out.println(inNames.get(j) + "=" + inputs.get(j)); } Object ret = call.invoke(inputs.toArray()); Map outputs = call.getOutputParams(); HashMap map = new HashMap(); for (int pos = 0; pos < outNames.size(); ++pos) { String name = (String) outNames.get(pos); Object value = outputs.get(name); if ((value == null) && (pos == 0)) { map.put(name, ret); } else { map.put(name, value); } } return map; } /** * Method getParamData * * @param c * @param arg */ private Object getParamData(org.apache.axis.client.Call c, Parameter p, String arg) throws Exception { // Get the QName representing the parameter type QName paramType = org.apache.axis.wsdl.toJava.Utils.getXSIType(p); TypeEntry type = p.getType(); if (type instanceof BaseType && ((BaseType) type).isBaseType()) { DeserializerFactory factory = c.getTypeMapping().getDeserializer(paramType); Deserializer deserializer = factory.getDeserializerAs(Constants.AXIS_SAX); if (deserializer instanceof SimpleDeserializer) { return ((SimpleDeserializer)deserializer).makeValue(arg); } } throw new RuntimeException("not know how to convert '" + arg + "' into " + c); } /** * Method selectService * * @param def * @param serviceNS * @param serviceName * * @return * * @throws Exception */ public Service selectService(String serviceNS, String serviceName) throws Exception { QName serviceQName = (((serviceNS != null) && (serviceName != null)) ? new QName(serviceNS, serviceName) : null); ServiceEntry serviceEntry = (ServiceEntry) getSymTabEntry(serviceQName, ServiceEntry.class); return serviceEntry.getService(); } /** * Method getSymTabEntry * * @param qname * @param cls * * @return */ public SymTabEntry getSymTabEntry(QName qname, Class cls) { HashMap map = wsdlParser.getSymbolTable().getHashMap(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); QName key = (QName) entry.getKey(); Vector v = (Vector) entry.getValue(); if ((qname == null) || qname.equals(qname)) { for (int i = 0; i < v.size(); ++i) { SymTabEntry symTabEntry = (SymTabEntry) v.elementAt(i); if (cls.isInstance(symTabEntry)) { return symTabEntry; } } } } return null; } /** * Method selectPort * * @param ports * @param portName * * @return * * @throws Exception */ public Port selectPort(Map ports, String portName) throws Exception { Iterator valueIterator = ports.keySet().iterator(); while (valueIterator.hasNext()) { String name = (String) valueIterator.next(); if ((portName == null) || (portName.length() == 0)) { Port port = (Port) ports.get(name); List list = port.getExtensibilityElements(); for (int i = 0; (list != null) && (i < list.size()); i++) { Object obj = list.get(i); if (obj instanceof SOAPAddress) { return port; } } } else if ((name != null) && name.equals(portName)) { return (Port) ports.get(name); } } return null; } }
6,830
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/NiceThingsBeanEJB.java
package samples.ejb; import javax.ejb.*; public class NiceThingsBeanEJB implements SessionBean { public void ejbCreate() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext sc) {} // "Business" Methods: public String sayHello(String name) { return ( "Hiya " + name + ", how are you?"); } public NiceThings findNiceThingsFor(String name) { // In reality our bean would probably be looking up these nice // things from an entity bean. In our case we'll just cheat :) NiceThings niceThings = new NiceThings("cake", 23, "black as night"); return niceThings; } public boolean updateNiceThingsFor(String name, NiceThings niceThings) { // In reality this bean would probably try and update nice things // in the relevant entity bean(s) and return a boolean to indicate // whether the update was successful or not. Again, we'll cheat. return true; } }
6,831
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/SimpleBeanHome.java
package samples.ejb; import javax.ejb.EJBLocalHome; public interface SimpleBeanHome extends EJBLocalHome { SimpleBean create() throws javax.ejb.CreateException; }
6,832
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/SimpleBean.java
package samples.ejb; import javax.ejb.EJBLocalObject; public interface SimpleBean extends EJBLocalObject { public String sayHello(String name) ; public String sayGoodbye(String name) ; }
6,833
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/NiceThings.java
package samples.ejb; import java.io.Serializable; public class NiceThings { private String food; private int luckyNumber; private String colour; public NiceThings(String food, int luckyNumber, String colour) { this.food = food; this.luckyNumber = luckyNumber; this.colour = colour; } public String getFood() { return food; } public int getLuckyNumber() { return luckyNumber; } public String getColour() { return colour; } public void setFood(String food) { this.food = food; } public void setLuckyNumber(int luckyNumber) { this.luckyNumber = luckyNumber; } public void setColour(String colour) { this.colour = colour; } }
6,834
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/SimpleBeanEJB.java
package samples.ejb; import javax.ejb.*; public class SimpleBeanEJB implements SessionBean { public void ejbCreate() { } public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext sc) {} // "Business" Methods: public String sayHello(String name) { return ( "Hello " + name + ", have a nice day."); } public String sayGoodbye(String name) { return ( "See ya, then " + name); } }
6,835
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/NiceThingsBean.java
package samples.ejb; import javax.ejb.EJBLocalObject; public interface NiceThingsBean extends EJBLocalObject { public String sayHello(String name); public NiceThings findNiceThingsFor(String name); public boolean updateNiceThingsFor(String name, NiceThings niceThings); }
6,836
0
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples
Create_ds/axis-axis1-java/distribution/src/main/files/samples/ejb/src/samples/ejb/NiceThingsBeanHome.java
package samples.ejb; import javax.ejb.EJBLocalHome; public interface NiceThingsBeanHome extends EJBLocalHome { NiceThingsBean create() throws javax.ejb.CreateException; }
6,837
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/split/SplitTestCase.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package test.wsdl.split; import java.io.File; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import javax.xml.namespace.QName; import junit.framework.TestCase; public class SplitTestCase extends TestCase { public void testValidateWSDL() throws Exception { WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); Definition definition = reader.readWSDL(new File("target/work/test/wsdl/split/SplitTestImpl.wsdl").getAbsoluteFile().toURI().toString()); Service service = definition.getService(new QName("http://split.wsdl.test", "MyPortTypeService")); Port port = service.getPort("SplitTest"); // This is the critical part: the binding is defined in the imported WSDL Binding binding = port.getBinding(); assertNotNull(binding); assertEquals("MyPortType", binding.getPortType().getQName().getLocalPart()); } }
6,838
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/split/MyPortType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package test.wsdl.split; public interface MyPortType { String echo(String arg); }
6,839
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/SchemaImportTestCase.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.wsdl.schemaImport; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.wsdl.Definition; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import java.io.File; /** * This class contains the methods necessary for testing that the XML Schema * import support is functional within WSDL2Java. This test will generate a * WSDL file and then validate that the schema has been appropriate imported * into said WSDL. * * @version 1.00 01 Nov 2002 * @author Doug Bitting (douglas.bitting@agile.com) */ public class SchemaImportTestCase extends junit.framework.TestCase { public SchemaImportTestCase(String name) { super(name); } public void testSchemaImport() { String path = "target" + File.separator + "work" + File.separator + "test" + File.separator + "wsdl" + File.separator + "schemaImport" + File.separator + "foo.wsdl"; Document doc = null; Definition def = null; // Make sure that the WSDL appears to be valid try { doc = XMLUtils.newDocument(path); assertNotNull("Unable to locate WSDL file: " + path, doc); WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); def = reader.readWSDL(path, doc); assertNotNull("unable to generate WSDL definition from document: " + path, def); assertEquals("Expected xmlns:foo to be set to urn:ImportSchemaTest", "urn:ImportSchemaTest", def.getNamespace("foo")); } catch (Exception e) { throw new junit.framework.AssertionFailedError("Exception caught: " + e); } // Now check that the schema was properly imported. It is assumed // that WSDL generation is validated in other unit tests. Here, we // are only interested in the schema importing functionality. NodeList typeList = doc.getElementsByTagName("wsdl:types"); Node typeNode = typeList.item(0); assertNotNull("types section of the WSDL document", typeNode); Element typeElem = (Element) typeNode; NodeList nodeList = typeElem.getElementsByTagName("xs:complexType"); assertTrue("Could not located imported schema", nodeList.getLength() > 0); Element elt = (Element) nodeList.item(0); assertEquals("Unexpected complexType", "foo", elt.getAttribute("name")); nodeList = elt.getElementsByTagName("xs:documentation"); assertTrue("Could not find schema documentation", nodeList.getLength() > 0); } } // End of SchemaImportTestCase.java
6,840
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/foo.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.wsdl.schemaImport; public class foo { public foo() { } } // End of foobar.java
6,841
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/schemaImport/foobar.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.wsdl.schemaImport; public class foobar { public void run(foo x) { } } // End of foobar.java
6,842
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/qname/MyServiceInterface.java
package test.wsdl.qname; import java.rmi.Remote; public interface MyServiceInterface extends Remote { public String Hello(String pName) throws java.rmi.RemoteException; public String HelloAgain(int pName) throws java.rmi.RemoteException; }
6,843
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/qname/foo.java
package test.wsdl.qname; public class foo { public void bar(String foobar) { } }
6,844
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/qname/MyServiceImpl.java
package test.wsdl.qname; import java.rmi.RemoteException; public class MyServiceImpl implements MyServiceInterface { public MyServiceImpl() { } public String Hello(String pName) throws java.rmi.RemoteException { return "Hello, " + pName; } public String HelloAgain(int pName) throws java.rmi.RemoteException { return "Hello Again, " + Integer.toString(pName); } }
6,845
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/groups/GroupsTestCase.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This tests the file generation of only the items that are referenced in WSDL * * @author Steve Green (steve.green@epok.net) */ package test.wsdl.groups; import java.io.IOException; public class GroupsTestCase extends junit.framework.TestCase { public GroupsTestCase(String name) { super(name); } public void testGroups() throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException { // Test for the proper members Class ourClass = Class.forName("test.wsdl.groups.SomeType"); ourClass.getDeclaredMethod("getA", null); ourClass.getDeclaredMethod("getB", null); ourClass.getDeclaredMethod("getZ", null); return; } }
6,846
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/extra/Extra.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.wsdl.extra; import java.util.Calendar; /** * Extra class which is provided to Java2WSDL but not referenced in the service * class. A complex type should be generated for the class in the WSDL */ public class Extra { private String item1; private int item2; private Calendar stamp; public String getItem1() { return item1; } public void setItem1(String item1) { this.item1 = item1; } public int getItem2() { return item2; } public void setItem2(int item2) { this.item2 = item2; } public Calendar getStamp() { return stamp; } public void setStamp(Calendar stamp) { this.stamp = stamp; } }
6,847
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl
Create_ds/axis-axis1-java/axis-ant/src/test/java/test/wsdl/extra/MyService.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.wsdl.extra; /** * Test service for Extra Classes test case which verifys that * Java2WSDL include the extra classes specified. */ public class MyService { public String myop(String in) { return "out"; } }
6,848
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyServiceImplWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.tools.ant.wsdl; import java.io.IOException; import java.io.PrintWriter; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.toJava.Emitter; import org.apache.axis.wsdl.toJava.JavaServiceImplWriter; public class MyServiceImplWriter extends JavaServiceImplWriter { public MyServiceImplWriter(Emitter emitter, ServiceEntry sEntry, SymbolTable symbolTable) { super(emitter, sEntry, symbolTable); } protected void writeHeaderComments(PrintWriter pw) throws IOException { pw.println("/**"); pw.println(" * My header comment"); pw.println(" */"); } }
6,849
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/CustomGeneratorFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.tools.ant.wsdl; import java.io.File; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; public class CustomGeneratorFactoryTest extends TestCase { public void test() throws Exception { File file = new File("target/work/com/example/stockquote_wsdl/StockQuoteServiceLocator.java"); assertTrue(FileUtils.readFileToString(file).contains("My header comment")); } }
6,850
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyGeneratorFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.tools.ant.wsdl; import javax.wsdl.Service; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.gen.NoopGenerator; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.toJava.Emitter; import org.apache.axis.wsdl.toJava.JavaGeneratorFactory; public class MyGeneratorFactory extends JavaGeneratorFactory { public MyGeneratorFactory(Emitter emitter) { super(emitter); } public Generator getGenerator(Service service, SymbolTable symbolTable) { if (include(service.getQName())) { Generator writer = new MyServiceWriter(emitter, service, symbolTable); ServiceEntry sEntry = symbolTable.getServiceEntry(service.getQName()); serviceWriters.addStuff(writer, sEntry, symbolTable); return serviceWriters; } else { return new NoopGenerator(); } } }
6,851
0
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/test/java/org/apache/axis/tools/ant/wsdl/MyServiceWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.tools.ant.wsdl; import javax.wsdl.Service; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.toJava.Emitter; import org.apache.axis.wsdl.toJava.JavaServiceWriter; public class MyServiceWriter extends JavaServiceWriter { public MyServiceWriter(Emitter emitter, Service service, SymbolTable symbolTable) { super(emitter, service, symbolTable); } protected void setGenerators() { super.setGenerators(); if (serviceImplWriter != null) { ServiceEntry sEntry = symbolTable.getServiceEntry(service.getQName()); serviceImplWriter = new MyServiceImplWriter(emitter, sEntry, symbolTable); } } }
6,852
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ParamSet.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.tools.ant.foreach; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.FileSet; import java.io.File; import java.util.Enumeration; import java.util.Vector; /** * Inner class stores sets of &lt;param&gt;s. * It can hold &lt;fileset&gt;s or &lt;item&gt;s or both. * * @author <a href="mailto:tpv@spamcop.net">Tim Vernum</a> * @author Davanum Srinivas * @author Richard A. Sitze */ public class ParamSet { public static final String TYPE_FILE = "file".intern(); public static final String TYPE_DIR = "dir".intern(); public static final String TYPE_BOTH = "both".intern(); /** * Enumerated attribute with the values "file", "dir" and "both" * for the type attribute. */ public static class FileDirBoth extends EnumeratedAttribute { public String[] getValues() { return new String[]{ TYPE_FILE, TYPE_DIR, TYPE_BOTH }; } } /** Defaults to "file". */ protected String type = TYPE_FILE; private Vector filesets; private Vector items; private String name; public ParamSet() { filesets = new Vector(); items = new Vector(); } public void addFileset(FileSet fileset) { filesets.addElement(fileset); } public ParamItem createItem() { ParamItem item = new ParamItem(); items.addElement(item); return item; } public void setName(String name) { this.name = name; } public String getName() { return name; } public Enumeration getValues(Project project) { /* As an arbitrary rule, this will return filesets first, and then <item>s. The ordering of the buildfile is not guaranteed. */ Vector values = new Vector(); Enumeration e = filesets.elements(); while (e.hasMoreElements()) { FileSet fileSet = (FileSet) e.nextElement(); File base = fileSet.getDir(project); DirectoryScanner scanner = fileSet.getDirectoryScanner(project); if (TYPE_DIR != type) { String[] files = getFiles(base, scanner); for (int j = 0; j < files.length; j++) { File f = new File(base, files[j]); values.addElement(f.getAbsolutePath()); } } if (TYPE_FILE != type) { String[] dirs = getDirs(base, scanner); for (int j = 0; j < dirs.length; j++) { File f = new File(base, dirs[j]); values.addElement(f.getAbsolutePath()); } } } e = items.elements(); while (e.hasMoreElements()) { ParamItem item = (ParamItem) e.nextElement(); values.addElement(item.getValue()); } return values.elements(); } /** * Shall the command work only on files, directories or both? */ public void setType(FileDirBoth type) { this.type = type.getValue().intern(); } /** * Return the list of files from this DirectoryScanner that should * be included on the command line. */ protected String[] getFiles(File basedir, DirectoryScanner ds) { return ds.getIncludedFiles(); } /** * Return the list of Directories from this DirectoryScanner that * should be included on the command line. */ protected String[] getDirs(File basedir, DirectoryScanner ds) { return ds.getIncludedDirectories(); } }
6,853
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ForeachTask.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.tools.ant.foreach; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Ant; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.taskdefs.Property; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.Path; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * Call a target foreach entry in a set of parameters based on a fileset. * <p> * <i>For Axis development; there is no support or stability associated * with this task</i> * <pre> * &lt;target name=&quot;target1&quot;&gt; * &lt;foreach target=&quot;target2&quot;&gt; * &lt;param name=&quot;param1&quot;&gt; * &lt;fileset refid=&quot;fset1&quot;/&gt; * &lt;/param&gt; * &lt;param name=&quot;param2&quot;&gt; * &lt;item value=&quot;jar&quot; /&gt; * &lt;item value=&quot;zip&quot; /&gt; * &lt;/param&gt; * &lt;/foreach&gt; * &lt;/target&gt; * * &lt;target name=&quot;target2&quot;&gt; * &lt;echo message=&quot;prop is ${param1}.${param2}&quot; /&gt; * &lt;/target&gt; * </pre> * <br> * Really this just a wrapper around "AntCall" * <br> * Added a "type" attribute that works precisely like its equivalent * in <code>ExecuteOn</code>. It allows the user * to specify whether directories, files, or both directories and files * from the filesets are included as entries in the parameter set. * @ant.task category="axis" * @author <a href="mailto:tpv@spamcop.net">Tim Vernum</a> * @author Davanum Srinivas */ public class ForeachTask extends Task { private Ant callee; private Java callee2; private String subTarget; private Vector params; private Hashtable properties; // must match the default value of Ant#inheritAll private boolean inheritAll = true; // must match the default value of Ant#inheritRefs private boolean inheritRefs = false; private boolean fork = false; private boolean verbose = false; public ForeachTask() { params = new Vector(); properties = new Hashtable(); } public void init() { } /** * If true, pass all properties to the new Ant project. * Defaults to true. */ public void setInheritAll(boolean inherit) { inheritAll = inherit; } /** * If true, pass all references to the new Ant project. * Defaults to false * @param inheritRefs new value */ public void setInheritRefs(boolean inheritRefs) { this.inheritRefs = inheritRefs; } /** * Target to execute, required. */ public void setTarget(String target) { subTarget = target; } /** * If true, forks the ant invocation. * * @param f "true|false|on|off|yes|no" */ public void setFork(boolean f) { fork = f; } /** * Enable verbose output when signing * ; optional: default false */ public void setVerbose(final boolean verbose) { this.verbose = verbose; } public ParamSet createParam() { ParamSet param = new ParamSet(); params.addElement(param); return param; } private void buildProperty(String propName, String propValue) { properties.put(propName, propValue); } private void executeTarget() { if (subTarget == null) { throw new BuildException("Attribute target is required.", getLocation()); } if(fork) { executeForkedAntTask(); } else { executeAntTask(); } } private void executeForkedAntTask() { /* if (callee2 == null) { */ callee2 = (Java) getProject().createTask("java"); callee2.setOwningTarget(getOwningTarget()); callee2.setTaskName(getTaskName()); callee2.setLocation(getLocation()); callee2.setClassname("org.apache.tools.ant.Main"); callee2.setAppend(true); callee2.setFork(true); callee2.createJvmarg().setValue("-Xbootclasspath/p:" + System.getProperty("sun.boot.class.path")); /* } */ String systemClassPath = System.getProperty("java.class.path"); callee2.setClasspath(new Path(getProject(), systemClassPath)); String args = "-buildfile " + properties.get("file"); Commandline.Argument arguments = callee2.createArg(); arguments.setLine(args); if (verbose) { callee2.createArg().setValue("-verbose"); } callee2.createArg().setValue(subTarget); if (callee2.executeJava() != 0) { throw new BuildException("Execution of ANT Task failed"); } } private void executeAntTask() { /* if (callee == null) { */ callee = (Ant) getProject().createTask("ant"); callee.setOwningTarget(getOwningTarget()); callee.setTaskName(getTaskName()); callee.init(); /* } */ callee.setAntfile(getProject().getProperty("ant.file")); callee.setTarget(subTarget); callee.setInheritAll(inheritAll); callee.setInheritRefs(inheritRefs); Enumeration keys = properties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String val = (String) properties.get(key); Property prop = callee.createProperty(); prop.setName(key); prop.setValue(val); } callee.execute(); System.gc(); System.gc(); System.gc(); } /** * This method is used to recursively iterate through * each parameter set. * It ends up being something like: * <pre> * for( i=0; i< params[0].size ; i++ ) * for( j=0; j < params[1].size ; j++ ) * for( k=0; k < params[2].size ; k++ ) * executeTarget( params[0][i], params[1][j] , params[2][k] ) ; * </pre> */ private void executeParameters(int paramNumber) { if (paramNumber == params.size()) { executeTarget(); } else { ParamSet paramSet = (ParamSet) params.elementAt(paramNumber); Enumeration values = paramSet.getValues(getProject()); while (values.hasMoreElements()) { String val = (String) values.nextElement(); buildProperty(paramSet.getName(), val); executeParameters(paramNumber + 1); } } } public void execute() { if (subTarget == null) { throw new BuildException("Attribute target is required.", getLocation()); } executeParameters(0); } }
6,854
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/foreach/ParamItem.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.tools.ant.foreach; /** * Inner class stores &lt;item&gt;s with &lt;param&gt; lists * * @author <a href="mailto:tpv@spamcop.net">Tim Vernum</a> * @author Davanum Srinivas */ public class ParamItem { private String value; public void setValue(String value) { this.value = value; } public String getValue() { return this.value; } }
6,855
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/axis/AdminClientTask.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.tools.ant.axis; import org.apache.axis.AxisFault; import org.apache.axis.client.AdminClient; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import javax.xml.rpc.ServiceException; import java.io.File; import java.util.Iterator; import java.util.LinkedList; /** * Task to administer a local or remote Axis server. Remember, for remote admin, * the server has to be accept remote management calls. * * @ant.task category="axis" name="axis-admin" */ public class AdminClientTask extends MatchingTask { /** * flag to control action on execution trouble */ private boolean failOnError = true; private String hostname; private int port = 0; private String servletPath; private File srcDir = null; private File xmlFile; private String transportChain; private String username; private String password; private String fileProtocol; private String action = ""; private String url; private boolean debug; private String newPassword; private LinkedList argslist; private boolean fork = false; private Path classpath = null; /** * set a debug flag * * @param debug */ public void setDebug(boolean debug) { this.debug = debug; } /** * set a new password; only valid if action=passwd * * @param newPassword */ public void setNewPassword(String newPassword) { this.newPassword = newPassword; } /** * full url to the admin endpoint * * @param url */ public void setUrl(String url) { this.url = url; } /** * specifies that a simple file protocol be used * * @param fileProtocol */ public void setFileProtocol(String fileProtocol) { this.fileProtocol = fileProtocol; } /** * name the host to admin * * @param hostname */ public void setHostname(String hostname) { this.hostname = hostname; } /** * the admin password * * @param password */ public void setPassword(String password) { this.password = password; } /** * the port to connect to * * @param port */ public void setPort(int port) { this.port = port; } /** * the path to the AxisAdmin servlet * * @param servletPath */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } /** * Set the source dir to find the source text files. */ public void setSrcdir(File srcDir) { this.srcDir = srcDir; } /** * the name of the XML file containing deployment information * * @param xmlFile */ public void setXmlFile(File xmlFile) { this.xmlFile = xmlFile; } /** * set the transport chain to use * * @param transportChain */ public void setTransportChain(String transportChain) { this.transportChain = transportChain; } /** * username to log in as * * @param username */ public void setUsername(String username) { this.username = username; } /** * Whether or not the build should halt if this task fails. * Defaults to <code>true</code>. */ public void setFailOnError(boolean fail) { failOnError = fail; } /** * If true, forks the ant invocation. * * @param f "true|false|on|off|yes|no" */ public void setFork(boolean f) { fork = f; } /** * validation code * * @throws org.apache.tools.ant.BuildException * if validation failed */ protected void validate() throws BuildException { if (srcDir != null) { if (!srcDir.exists()) { throw new BuildException("srcdir does not exist!"); } if (!srcDir.isDirectory()) { throw new BuildException("srcdir is not a directory!"); } } } /** * trace out parameters * * @param logLevel to log at * @see org.apache.tools.ant.Project#log */ public void traceParams(int logLevel) { log("Running axis-admin with parameters:", logLevel); log(" action:" + action, logLevel); log(" url:" + url, logLevel); log(" hostname:" + hostname, logLevel); log(" port:" + port, logLevel); log(" servletPath:" + servletPath, logLevel); log(" fileProtocol:" + fileProtocol, logLevel); log(" username:" + username, logLevel); log(" password:" + password, logLevel); log(" transportChain:" + transportChain, logLevel); log(" debug:" + debug, logLevel); } /** * <p>Processes a set of administration commands.</p> * <p>The following commands are available:</p> * <ul> * <li><code>-l<i>url</i></code> sets the AxisServlet URL</li> * <li><code>-h<i>hostName</i></code> sets the AxisServlet host</li> * <li><code>-p<i>portNumber</i></code> sets the AxisServlet port</li> * <li><code>-s<i>servletPath</i></code> sets the path to the * AxisServlet</li> * <li><code>-f<i>fileName</i></code> specifies that a simple file * protocol should be used</li> * <li><code>-u<i>username</i></code> sets the username</li> * <li><code>-w<i>password</i></code> sets the password</li> * <li><code>-d</code> sets the debug flag (for instance, -ddd would * set it to 3)</li> * <li><code>-t<i>name</i></code> sets the transport chain touse</li> * <li><code>list</code> will list the currently deployed services</li> * <li><code>quit</code> will quit (???)</li> * <li><code>passwd <i>value</i></code> changes the admin password</li> * <li><code><i>xmlConfigFile</i></code> deploys or undeploys * Axis components and web services</li> * </ul> * <p>If <code>-l</code> or <code>-h -p -s</code> are not set, the * AdminClient will invoke * <code>http://localhost:8080/axis/servlet/AxisServlet</code>. * <p> * outputs XML result or null in case of failure. In the case of multiple * commands, the XML results will be concatenated, separated by \n * * @throws BuildException something went wrong */ public void execute() throws BuildException { traceParams(Project.MSG_VERBOSE); validate(); argslist = new LinkedList(); //build an array of args addArgs("-l", url, url != null); addArgs("-h", hostname, hostname != null); addArgs("-p", Integer.toString(port), port != 0); addArgs("-s", servletPath, servletPath != null); addArgs("-f", fileProtocol, fileProtocol != null); addArgs("-u", username, username != null); addArgs("-w", password, password != null); addArgs("-t", transportChain, transportChain != null); addArg("-d", debug); //action addArg(action, action != null); //action extras if ("passwd".equals(action)) { if (newPassword == null) { throw new BuildException("No newpassword set for passwd"); } addArg(newPassword); } else { if (newPassword != null) { throw new BuildException( "newpassword is only used when action=passwd"); } } //final param is the xml file(s) if (xmlFile != null) { if (!xmlFile.exists()) { throw new BuildException("File " + xmlFile + " no found"); } addArg(xmlFile.toString()); } if (srcDir != null) { DirectoryScanner ds = super.getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); for (int i = 0; i < files.length; i++) { File srcFile = new File(srcDir, files[i]); if (!srcFile.exists()) { throw new BuildException("File " + srcFile + " no found"); } addArg(srcFile.getAbsolutePath()); } } //turn the list into an array int counter = 0; String[] args = new String[argslist.size()]; Iterator it = argslist.iterator(); while (it.hasNext()) { String arg = (String) it.next(); args[counter] = arg; counter++; } if (fork) { executeInForkedVM(args); } else { executeInCurrentVM(args); } } private void executeInForkedVM(String[] args) { try { // Create an instance of the compiler, redirecting output to // the project log Java java = (Java) (getProject().createTask("java")); getProject().log("using classpath: " + classpath, Project.MSG_DEBUG); java.setClasspath(classpath); java.setClassname("org.apache.axis.client.AdminClient"); for (int i = 0; i < args.length; i++) { java.createArg().setValue(args[i]); } java.setFailonerror(failOnError); //we are forking here to be sure that if AdminClient calls //System.exit() it doesn't halt the build java.setFork(true); java.setTaskName("AdminClient"); java.execute(); } catch (BuildException e) { //rethrow these throw e; } catch (Exception e) { throw new BuildException("Exception in " + getTaskName(), e); } } private void executeInCurrentVM(String[] args) { //now create a client and invoke it AdminClient admin = null; try { admin = new AdminClient(true); } catch (ServiceException e) { throw new BuildException("failed to start the axis engine", e); } String result = null; try { result = admin.process(args); if (result != null) { log(result); } else { logOrThrow(getTaskName() + " got a null response"); } } catch (AxisFault fault) { log(fault.dumpToString(), Project.MSG_ERR); traceParams(Project.MSG_ERR); logOrThrow(getTaskName() + " failed with " + fault.getFaultCode().toString() + " " + fault.getFaultString()); } catch (BuildException e) { //rethrow these throw e; } catch (Exception e) { throw new BuildException("Exception in " + getTaskName(), e); } } private void logOrThrow(String text) throws BuildException { if (failOnError) { throw new BuildException(text); } else { log(text, Project.MSG_ERR); } } /** * add one arg * * @param argument */ protected void addArg(String argument) { argslist.add(argument); } /** * add one arg * * @param argument */ protected void addArg(String argument, boolean test) { if (test) { argslist.add(argument); } } /** * add an arg pair * * @param argument * @param param */ protected void addArgs(String argument, String param) { addArg(argument); addArg(param); } /** * add an arg pair if the test is true * * @param argument first arg * @param param param to accompany * @param test test to trigger argument add */ protected void addArgs(String argument, String param, boolean test) { if (test) { addArg(argument); addArg(param); } } /** * Set the optional classpath * * @param classpath the classpath to use when loading class */ public void setClasspath(Path classpath) { createClasspath().append(classpath); } /** * Set the optional classpath * * @return a path instance to be configured by the Ant core. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** * Set the reference to an optional classpath * * @param r the id of the Ant path instance to act as the classpath */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } }
6,856
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/axis/RunAxisFunctionalTestsTask.java
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.tools.ant.axis; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.CallTarget; import java.io.BufferedInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; /** * Ant task for starting / stopping servers and running junit in the middle. * Based on the Cactus org.apache.commons.cactus.ant package, heavily munged * and cruftily dumped into one file. * <p> * <i>For Axis development; there is no support or stability associated * with this task</i> * @ant.task category="axis" * @author Rob Jellinghaus (robj@unrealities.com) */ public class RunAxisFunctionalTestsTask extends Task { private String tcpServerTarget = null; private String httpServerTarget = null; private String testTarget; private String httpStopTarget = null; private URL url = null; /** * Executes the task. */ public void execute() throws BuildException { try { callStart(tcpServerTarget); callStart(httpServerTarget); callTests(); } finally { // Make sure we stop the server callStop(); } } /** * Call the start server task */ private void callStart(String startTarget) { if (startTarget == null) { return; } // Execute the ant target new Thread(new TaskRunnable(startTarget)).start(); if (! startTarget.equals(tcpServerTarget)) return; // try a ping for the TCP server while (true) { try { Thread.sleep(500); } catch (InterruptedException ex) { } try { sendOnSocket("ping\r\n"); // if no exception, return System.out.println("RunAxisFunctionalTestsTask.callStart successfully pinged server."); return; } catch (Exception ex) { // loop & try again } } // NOTREACHED since the while loop returns if it successfully pings } /** * Call the run tests target */ private void callTests() { antcall(testTarget); } /** * Call the stop server task */ private void callStop() { try { // first, stop the tcp server if (tcpServerTarget != null) { sendOnSocket("quit\r\n"); } // second, and more involvedly, stop the http server // Try connecting in case the server is already stopped. if (httpServerTarget != null) { URL url = new URL("http://localhost:8080/"); try { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.connect(); readFully(connection); connection.disconnect(); } catch (IOException e) { // Server is not running. Make this task a no-op. System.out.println("Error from HTTP read: " + e); return; } } // Call the target that stops the server antcall(httpStopTarget); // Wait a few ms more (just to make sure) try { Thread.sleep(500); } catch (InterruptedException e) { throw new BuildException("Interruption during sleep", e); } /* // Continuously try calling the test URL until it fails while (true) { System.out.println("Trying localhost:8080..."); try { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.connect(); this.readFully(connection); connection.disconnect(); } catch (IOException e) { break; } try { Thread.sleep(500); } catch (InterruptedException ee) { throw new BuildException("Interruption during sleep", ee); } } // Wait a few ms more (just to be sure !) try { Thread.sleep(500); } catch (InterruptedException e) { throw new BuildException("Interruption during sleep", e); } */ System.out.println("RunAxisFunctionalTestsTask.callStop successfully sent quit message."); } catch (Exception ex) { // ignore; if socket not there, presume dead already } } /** * Call the selected ant task. */ private void antcall (String taskName) { CallTarget callee; callee = (CallTarget) getProject().createTask("antcall"); callee.setOwningTarget(getOwningTarget()); callee.setTaskName(getTaskName()); callee.setLocation(getLocation()); callee.init(); callee.setTarget(taskName); callee.execute(); } /** * Make a socket to the url, and send the given string */ private void sendOnSocket (String str) throws Exception { if (url == null) return; Socket sock = null; try { sock = new Socket(url.getHost(), url.getPort()); sock.getOutputStream().write(new String(str).getBytes()); // get a single byte response int i = sock.getInputStream().read(); } catch (Exception ex) { throw ex; }/* finally { if (sock != null) { try { sock.close(); } catch (IOException ex) { // ignore } } }*/ } /** * Read all the contents that are to be read */ static void readFully(HttpURLConnection connection) throws IOException { // finish reading it to prevent (harmless) server-side exceptions BufferedInputStream is = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[256]; while((is.read(buffer)) > 0) {} is.close(); } /** * Sets the target to call to start server 1. * * @param theStartTarget the Ant target to call */ public void setTcpServerTarget(String theStartTarget) { tcpServerTarget = theStartTarget; } /** * Sets the target to call to start server 2. * * @param theStartTarget the Ant target to call */ public void setHttpServerTarget(String theStartTarget) { httpServerTarget = theStartTarget; } /** * Sets the target to call to run the tests. * * @param theTestTarget the Ant target to call */ public void setTestTarget(String theTestTarget) { testTarget = theTestTarget; } /** * Sets the stop target. This is the target which does * a HTTP admin shutdown on the simple server. */ public void setHttpStopTarget (String theStopTarget) { httpStopTarget = theStopTarget; } /** * Sets the target URL (just http://host:port) */ public void setUrl (String theUrl) { try { url = new URL(theUrl); } catch (MalformedURLException ex) { System.err.println("Can't make URL from "+theUrl); } } /** * Helper class to execute a task in a thread. */ public class TaskRunnable implements Runnable { String taskName; public TaskRunnable (String taskName) { this.taskName = taskName; } public void run () { antcall(taskName); } } }
6,857
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Wsdl2javaAntTask.java
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.tools.ant.wsdl; import java.io.File; import java.io.IOException; import java.net.Authenticator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.axis.constants.Scope; import org.apache.axis.utils.DefaultAuthenticator; import org.apache.axis.utils.ClassUtils; import org.apache.axis.wsdl.toJava.Emitter; import org.apache.axis.wsdl.toJava.FactoryProperty; import org.apache.axis.wsdl.toJava.NamespaceSelector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.Environment; /* * IMPORTANT: see Java2WsdlAntTask on how to javadoc this task and rebuild * the task documentation afterwards * */ /** * Create Java classes from local or remote WSDL. * Mappings from namespaces to packages can be provided as nested &lt;mapping&gt; * elements. * <p> * Proxy settings are taken from the java runtime settings of http.ProxyHost, * http.ProxyPort, etc. The Ant task &lt;setProxy&gt; can set these. * As well as the nested mapping elements, this task uses the file * <tt>NStoPkg.properties</tt> in the project base directory * for namespace mapping * <p> * This task does no dependency checking; files are generated whether they * need to be or not. The exception to this is the Impl class, which is * not overwritten if it exists. This is a safety measure. However, all other * classes are generated overwriting anything that exists. * <p> * The safe way to use this task is to have it generate the java source in * a build directory, then have a &lt;copy&gt; task selectively copy the * files you need into a safe location. Again, copying into the source tree * is dangerous, but a separate build/src tree is safe. Then include this * separate tree in the &lt;javac&gt; task's src attribute to include it in the * build. Implement your own implementation classes of the server stub and the * test cases using the generated templates. * If you want to add methods to autogenerated data types, consider subclassing * them, or write helper classes. * <p> * Tip: if you &lt;get&gt; the wsdl, and use the &lt;filesmatch&gt; condition * to compare the fetched wsdl with a catched copy, you can make the target that * calls the axis-wsd2ljava task conditional on the WSDL having changed. This stops * spurious code regeneration and follow-on rebuilds across the java source tree. * @ant.task category="axis" name="axis-wsdl2java" * @author Davanum Srinivas (dims@yahoo.com) * @author steve loughran */ public class Wsdl2javaAntTask extends Task { private boolean verbose = false; private boolean debug = false; private boolean quiet = false; private boolean server = false; private boolean skeletonDeploy = false; private boolean testCase = false; private boolean noImports = false; private boolean all = false; private boolean helperGen = false; private boolean noWrapped = false; private boolean allowInvalidURL = false; private String factory = null; private HashMap namespaceMap = new HashMap(); private String output = "."; private String protocolHandlerPkgs = ""; private String deployScope = ""; private String url = ""; private String typeMappingVersion = "1.2"; private long timeout = 45000; private File namespaceMappingFile = null; private MappingSet mappings = new MappingSet(); private String username = null; private String password = null; private Path classpath = null; private List nsIncludes = new ArrayList(); private List nsExcludes = new ArrayList(); private List properties = new ArrayList(); private String implementationClassName = null; private CommandlineJava commandline = new CommandlineJava(); /** * do we print a stack trace when something goes wrong? */ private boolean printStackTraceOnFailure = true; /** * what action to take when there was a failure and the source was some * URL */ private boolean failOnNetworkErrors = false; private boolean wrapArrays = false; public Wsdl2javaAntTask() { } /** * validation code * @throws BuildException if validation failed */ protected void validate() throws BuildException { if (url == null || url.length() == 0) { throw new BuildException("No url specified"); } if (timeout < -1) { throw new BuildException("negative timeout supplied"); } File outdir = new File(output); if (!outdir.isDirectory() || !outdir.exists()) { throw new BuildException("output directory is not valid"); } if (quiet) { if (verbose) { throw new BuildException("quiet and verbose options are " + "exclusive"); } if (debug) { throw new BuildException("quiet and debug options are " + "exclusive"); } } } /** * trace out parameters * @param logLevel to log at * @see org.apache.tools.ant.Project#log */ public void traceParams(int logLevel) { log("Running Wsdl2javaAntTask with parameters:", logLevel); log("\tverbose:" + verbose, logLevel); log("\tdebug:" + debug, logLevel); log("\tquiet:" + quiet, logLevel); log("\tserver-side:" + server, logLevel); log("\tskeletonDeploy:" + skeletonDeploy, logLevel); log("\thelperGen:" + helperGen, logLevel); log("\tfactory:" + factory, logLevel); log("\tnsIncludes:" + nsIncludes, logLevel); log("\tnsExcludes:" + nsExcludes, logLevel); log("\tfactoryProps:" + properties, logLevel); log("\ttestCase:" + testCase, logLevel); log("\tnoImports:" + noImports, logLevel); log("\tNStoPkg:" + namespaceMap, logLevel); log("\toutput:" + output, logLevel); log("\tprotocolHandlerPkgs:" + protocolHandlerPkgs, logLevel); log("\tdeployScope:" + deployScope, logLevel); log("\tURL:" + url, logLevel); log("\tall:" + all, logLevel); log("\ttypeMappingVersion:" + typeMappingVersion, logLevel); log("\ttimeout:" + timeout, logLevel); log("\tfailOnNetworkErrors:" + failOnNetworkErrors, logLevel); log("\tprintStackTraceOnFailure:" + printStackTraceOnFailure, logLevel); log("\tnamespaceMappingFile:" + namespaceMappingFile, logLevel); log("\tusername:" + username, logLevel); log("\t:password" + password, logLevel); log("\t:noWrapped" + noWrapped, logLevel); log("\t:allowInvalidURL" + allowInvalidURL, logLevel); log("\t:implementationClassName" + implementationClassName, logLevel); log("\t:classpath" + classpath, logLevel); traceNetworkSettings(logLevel); } /** * The method executing the task * @throws BuildException if validation or execution failed */ public void execute() throws BuildException { //before we get any further, if the user didnt spec a namespace mapping //file, we load in the default traceParams(Project.MSG_VERBOSE); validate(); CommandlineJava.SysProperties sysProperties = commandline.getSystemProperties(); if (sysProperties != null) { sysProperties.setSystem(); } try { // Instantiate the emitter Emitter emitter = createEmitter(); if (classpath != null) { AntClassLoader cl = new AntClassLoader( getClass().getClassLoader(), getProject(), classpath, true); log("Using CLASSPATH " + cl.getClasspath(), Project.MSG_VERBOSE); ClassUtils.setDefaultClassLoader(cl); } //extract the scope Scope scope = Scope.getScope(deployScope, null); if (scope != null) { emitter.setScope(scope); } else if (deployScope.length() == 0 || "none".equalsIgnoreCase(deployScope)) { /* leave default (null, or not-explicit) */; } else { log("Unrecognized scope: " + deployScope + ". Ignoring it.", Project.MSG_VERBOSE); } //do the mappings, with namespaces mapped as the key mappings.execute(this, namespaceMap, false); if (!namespaceMap.isEmpty()) { emitter.setNamespaceMap(namespaceMap); } emitter.setTestCaseWanted(testCase); emitter.setHelperWanted(helperGen); if (factory != null) { emitter.setFactory(factory); } emitter.setNamespaceIncludes(nsIncludes); emitter.setNamespaceExcludes(nsExcludes); emitter.setProperties(properties); emitter.setImports(!noImports); emitter.setAllWanted(all); emitter.setOutputDir(output); emitter.setServerSide(server); emitter.setSkeletonWanted(skeletonDeploy); emitter.setVerbose(verbose); emitter.setDebug(debug); emitter.setQuiet(quiet); emitter.setTypeMappingVersion(typeMappingVersion); emitter.setNowrap(noWrapped); emitter.setAllowInvalidURL(allowInvalidURL); emitter.setWrapArrays(wrapArrays); if (namespaceMappingFile != null) { emitter.setNStoPkg(namespaceMappingFile.toString()); } emitter.setTimeout(timeout); emitter.setImplementationClassName(implementationClassName); Authenticator.setDefault(new DefaultAuthenticator(username, password)); try { if(url.indexOf(':') == -1) url = getProject().resolveFile(url).getAbsolutePath(); } catch (Throwable t){ } log("WSDL2Java " + url, Project.MSG_INFO); try { emitter.run(url); } catch (Throwable e) { if (url.startsWith("http://")) { // What we have is either a network error or invalid XML - // the latter most likely an HTML error page. This makes // it impossible to continue with the test, so we stop here if (!failOnNetworkErrors) { // test mode, issue a warning, and return without //reporting a fatal error. log(e.toString(), Project.MSG_WARN); return; } else { //in 'consumer' mode, bail out with the URL throw new BuildException("Could not build " + url, e); } } else { throw e; } } } catch (BuildException b) { //we rethrow this immediately; but need to catch it to stop it being //mistaken for a throwable. throw b; } catch (Throwable t) { if (printStackTraceOnFailure) { traceParams(Project.MSG_INFO); t.printStackTrace(); } //now throw an exception that includes the error text of the caught exception. throw new BuildException("WSDL processing error for " + url +" :\n "+t.getMessage() , t); } finally { if (sysProperties != null) { sysProperties.restoreSystem(); } } } /** * flag for verbose output; default=false * *@param verbose The new verbose value */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * flag for debug output; default=false * *@param debug The new debug value */ public void setDebug(boolean debug) { this.debug = debug; } /** * flag for quiet output; default=false * *@param quiet The new quiet value */ public void setQuiet(boolean quiet) { this.quiet = quiet; } /** * emit server-side bindings for web service; default=false */ public void setServerSide(boolean parameter) { this.server = parameter; } /** * deploy skeleton (true) or implementation (false) in deploy.wsdd. * Default is false. Assumes server-side="true". */ public void setSkeletonDeploy(boolean parameter) { this.skeletonDeploy = parameter; } /** * flag for automatic Junit testcase generation * default is false */ public void setTestCase(boolean parameter) { this.testCase = parameter; } /** * Turn on/off Helper class generation; * default is false */ public void setHelperGen(boolean parameter) { this.helperGen = parameter; } /** * name of the Java2WSDLFactory class for * extending WSDL generation functions */ public void setFactory(String parameter) { this.factory = parameter; } /** * only generate code for the immediate WSDL document, * and not imports; default=false; */ public void setNoImports(boolean parameter) { this.noImports = parameter; } /** * output directory for emitted files */ public void setOutput(File parameter) throws BuildException { try { this.output = parameter.getCanonicalPath(); } catch (IOException ioe) { throw new BuildException(ioe); } } /** * append any protocol handler pkgs specified with the task */ public void setProtocolHandlerPkgs(String handlerPkgs) { String currentPkgs = System.getProperty("java.protocol.handler.pkgs"); String newPkgs = null; if (currentPkgs == null) newPkgs = handlerPkgs; else // append to the existing list newPkgs = currentPkgs + "|" + handlerPkgs; System.setProperty("java.protocol.handler.pkgs", newPkgs); } /** * add scope to deploy.xml: "Application", "Request", "Session" * optional; */ public void setDeployScope(String scope) { this.deployScope = scope; } /* //unused till we can somehow get ant to be case insensitive when handling enums public void setDeployScope(DeployScopeEnum scope) { this.deployScope = scope.getValue(); } */ /** * URL to fetch and generate WSDL for. * Can be remote or a local file. */ public void setURL(String parameter) { this.url = parameter; } /** * flag to generate code for all elements, even unreferenced ones * default=false; */ public void setAll(boolean parameter) { this.all = parameter; } /** * the default type mapping registry to use. Either 1.1 or 1.2. * Default is 1.1 * @param parameter new version */ public void setTypeMappingVersion(TypeMappingVersionEnum parameter) { this.typeMappingVersion = parameter.getValue(); } /** * timeout in milliseconds for URL retrieval; default is 45 seconds. * Set this to -1 to disable timeouts altogether: other negative values * are not allowed) */ public void setTimeout(long parameter) { this.timeout = parameter; } /** * add a mapping of namespaces to packages */ public void addMapping(NamespaceMapping mapping) { mappings.addMapping(mapping); } /** * add a mapping of namespaces to packages */ public void addMappingSet(MappingSet mappingset) { mappings.addMappingSet(mappingset); } /** * set the mapping file. This is a properties file of * package=namespace order. Optional, default is to look for * a file called NStoPkg.properties in the project directory. * @param namespaceMappingFile */ public void setNamespaceMappingFile(File namespaceMappingFile) { this.namespaceMappingFile = namespaceMappingFile; } /** * valid deploy scopes for the task */ /* public static class DeployScopeEnum extends EnumeratedAttribute { public String[] getValues() { return new String[]{"Application", "Request", "Session","none"}; } } */ /** * should the task fail the build if there is a network error? * optional: defaults to false * @param failOnNetworkErrors */ public void setFailOnNetworkErrors(boolean failOnNetworkErrors) { this.failOnNetworkErrors = failOnNetworkErrors; } /** * should we print a stack trace on failure? * Optional, default=true. * @param printStackTraceOnFailure */ public void setPrintStackTraceOnFailure(boolean printStackTraceOnFailure) { this.printStackTraceOnFailure = printStackTraceOnFailure; } /** * set any username required for BASIC authenticated access to the WSDL; * optional. * @param username */ public void setUsername(String username) { this.username = username; } /** * set any password required for BASIC authenticated access to the WSDL; * optional; only used if username is set * @param password * @see #username */ public void setPassword(String password) { this.password = password; } /** * Set the noWrapped flag. * @param noWrapped */ public void setNoWrapped(boolean noWrapped) { this.noWrapped = noWrapped; } /** * Set the allowInvalidURL flag. */ public void setAllowInvalidUrl(boolean b) { this.allowInvalidURL = b; } /** * Set the name of the class implementing the web service. * This is especially useful when exporting a java class * as a web service using Java2WSDL followed by WSDL2Java. * * @param implementationClassName */ public void setImplementationClassName(String implementationClassName) { this.implementationClassName = implementationClassName; } /** * Set the wrap arrays flag - if true this will make new classes * like "ArrayOfString" for literal "wrapped" arrays. Otherwise it * will use "String []" and generate appropriate metadata. * * @param wrapArrays */ public void setWrapArrays(boolean wrapArrays) { this.wrapArrays = wrapArrays; } /** * set the classpath * @return */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** Adds an additional namespace to the list to be included * in source code generation. */ public NamespaceSelector createNsInclude() { NamespaceSelector selector = new NamespaceSelector(); nsIncludes.add(selector); return selector; } /** Adds an additional namespace to the list to be excluded * from source code generation. */ public NamespaceSelector createNsExclude() { NamespaceSelector selector = new NamespaceSelector(); nsExcludes.add(selector); return selector; } /** Adds a property name/value pair for specialized * JavaGeneratorFactories. */ public FactoryProperty createProperty() { FactoryProperty property = new FactoryProperty(); properties.add(property); return property; } /** This factory method makes it easier to extend this Ant task * with a custom Emitter, if necessary. */ protected Emitter createEmitter() { return new Emitter(); } protected NamespaceSelector createSelector() { return new NamespaceSelector(); } private void traceSystemSetting(String setting, int logLevel) { String value = System.getProperty(setting); log("\t" + setting + "=" + value, logLevel); } private void traceNetworkSettings(int logLevel) { traceSystemSetting("http.proxyHost", logLevel); traceSystemSetting("http.proxyPort", logLevel); traceSystemSetting("http.proxyUser", logLevel); traceSystemSetting("http.proxyPassword", logLevel); traceSystemSetting("socks.proxyHost", logLevel); traceSystemSetting("socks.proxyPort", logLevel); } /** * Adds a system property that tests can access. * @param sysp environment variable to add */ public void addSysproperty(Environment.Variable sysp) { commandline.addSysproperty(sysp); } }
6,858
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Mapper.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.tools.ant.wsdl; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; import java.util.HashMap; /** * interface that namespace mappers are expected to implement */ public interface Mapper { /** * execute the mapping * @param owner owner object * @param map map to map to * @param packageIsKey if the package is to be the key for the map * @throws BuildException in case of emergency */ void execute(ProjectComponent owner, HashMap map, boolean packageIsKey) throws BuildException; }
6,859
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/TypeMappingVersionEnum.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.tools.ant.wsdl; import org.apache.tools.ant.types.EnumeratedAttribute; /** * valid typemappings for the Ant tasks */ public class TypeMappingVersionEnum extends EnumeratedAttribute { public String[] getValues() { return new String[]{"1.0", "1.1", "1.2", "1.3"}; } /** * default mapping version is 1.1 */ public static final String DEFAULT_VERSION="1.1"; }
6,860
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/MappingSet.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.tools.ant.wsdl; import org.apache.tools.ant.ProjectComponent; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** *a mappingset is a set of mappings */ public class MappingSet implements Mapper { List mappings=new LinkedList(); /** * add a new mapping * @param mapping */ public void addMapping(NamespaceMapping mapping) { mappings.add(mapping); } /** * add a mappingset inside this one * @param mappingset */ public void addMappingSet(MappingSet mappingset) { mappings.add(mappingset); } /** * execute by mapping everything iteratively and recursively * @param owner owner task * @param map map to map into * @param packageIsKey if the package is to be the key for the map */ public void execute(ProjectComponent owner, HashMap map, boolean packageIsKey) { Iterator it=mappings.iterator(); while (it.hasNext()) { Mapper mapper = (Mapper) it.next(); mapper.execute(owner,map, packageIsKey); } } }
6,861
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/NamespaceMapping.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.tools.ant.wsdl; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectComponent; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; /** * Used for nested package definitions. * The file format used for storing mappings is a list of package=namespace */ public class NamespaceMapping implements Mapper { private String namespace = null; private String packageName = null; private File mappingFile; /** * pass in the namespace to map to */ public NamespaceMapping() { } /** * the namespace in the WSDL. Required. * @param value new uri of the mapping */ public void setNamespace(String value) { namespace = value; } /** * the Java package to bind to. Required. * @param value java package name */ public void setPackage(String value) { packageName = value; } /** * name of a property file that contains mappings in * package=namespace format * @param file file to load */ public void setFile(File file) { mappingFile = file; } /** * map a namespace to a package * @param owner owning project component (For logging) * @param map map to assign to * @param packName package name * @param nspace namespace * @param packageIsKey if the package is to be the key for the map */ protected void map(ProjectComponent owner, HashMap map, String packName, String nspace, boolean packageIsKey) { owner.log("mapping "+nspace+" to "+packName, Project.MSG_VERBOSE); if(packageIsKey) { map.put(packName,nspace); } else { map.put(nspace, packName); } } /** * validate the option set */ private void validate() { if (mappingFile != null) { if (namespace != null || packageName != null) { throw new BuildException( "Namespace or Package cannot be used with a File attribute"); } } else { if (namespace == null) { throw new BuildException("namespace must be defined"); } if (packageName == null) { throw new BuildException("package must be defined"); } } } /** * Load a mapping file and save it to the map * @param owner owner component * @param map target map file * @param packageIsKey if the package is to be the key for the map * @throws BuildException if an IOException needed swallowing */ protected void mapFile(ProjectComponent owner, HashMap map, boolean packageIsKey) throws BuildException { Properties props = loadMappingPropertiesFile(); Enumeration keys = props.keys(); while (keys.hasMoreElements()) { String packageName = (String) keys.nextElement(); String namespace = props.getProperty(packageName); map(owner, map, packageName, namespace, packageIsKey); } } /** * load a file containing properties * @return a properties file with zero or more mappings * @throws BuildException if the load failed */ private Properties loadMappingPropertiesFile() throws BuildException { Properties props = new Properties(); FileInputStream instr = null; try { instr = new FileInputStream(mappingFile); props.load(new BufferedInputStream(instr)); } catch (IOException e) { throw new BuildException("Failed to load " + mappingFile, e); } finally { if (instr != null) { try { instr.close(); } catch (IOException e) { } } } return props; } /** * execute the mapping * @param owner owner object * @param map map to map to * @param packageIsKey if the package is to be the key for the map * @throws BuildException in case of emergency */ public void execute(ProjectComponent owner, HashMap map, boolean packageIsKey) throws BuildException { validate(); if (mappingFile != null) { mapFile(owner, map,packageIsKey); } else { map(owner, map, packageName, namespace, packageIsKey); } } }
6,862
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/Java2WsdlAntTask.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.tools.ant.wsdl; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.encoding.TypeMappingDelegate; import org.apache.axis.wsdl.fromJava.Emitter; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.CommandlineJava; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; /* * Important. we autogenerate the ant task docs from this. * after adding a new attribute * 1. add the javadoc for the end users. Make it meaningful * 2. get jakarta_ant/proposals/xdocs from ant CVS * 3. run the xdocs target in tools/build.xml * this creates xml files in xdocs/build * 4. run proposals/xdocs/dvsl build.xml to create the html files * these are also created under xdocs/build * 5. copy the the html files to docs/ant * 4. check in the changes in docs/ant */ /** * Generates a WSDL description from a Java class. * @author Rich Scheuerle (scheu@us.ibm.com) * @author Steve Loughran * @ant.task category="axis" name="axis-java2wsdl" */ public class Java2WsdlAntTask extends Task { private String namespace = ""; private String namespaceImpl = null; private HashMap namespaceMap = new HashMap(); private String location = ""; private String locationImport = null; private String output = "." ; private String importSchema = null ; private String input = null ; private String outputImpl = null; private String className = "." ; private String servicePortName = null ; private String portTypeName = null ; private String bindingName = null ; private String implClass = null; private boolean useInheritedMethods = false; private String exclude = null; private String stopClasses = null; private String typeMappingVersion = TypeMappingVersionEnum.DEFAULT_VERSION; private String style = null; private String serviceElementName=null; private String methods=null; private String use = null; private MappingSet mappings=new MappingSet(); private String extraClasses = null; private Path classpath = null; private String soapAction = null; private List complexTypes = new LinkedList(); private boolean isDeploy = false; private CommandlineJava commandline = new CommandlineJava(); /** * trace out parameters * @param logLevel to log at * @see org.apache.tools.ant.Project#log */ public void traceParams(int logLevel) { log("Running Java2WsdlAntTask with parameters:", logLevel); log("\tnamespace:" + namespace, logLevel); log("\tPkgtoNS:" + namespaceMap, logLevel); log("\tlocation:" + location, logLevel); log("\toutput:" + output, logLevel); log("\timportSchema:" + importSchema, logLevel); log("\tinput:" + input, logLevel); log("\tclassName:" + className, logLevel); log("\tservicePortName:" + servicePortName, logLevel); log("\tportTypeName:" + portTypeName, logLevel); log("\tbindingName:" + bindingName, logLevel); log("\timplClass:" + implClass, logLevel); log("\tinheritance:" + useInheritedMethods, logLevel); log("\texcluded:" + exclude, logLevel); log("\tstopClasses:" + stopClasses, logLevel); log("\ttypeMappingVersion:" + typeMappingVersion, logLevel); log("\tstyle:" + style, logLevel); log("\toutputImpl:" + outputImpl, logLevel); log("\tuse:" + use, logLevel); log("\tnamespaceImpl:" + namespaceImpl, logLevel); log("\tlocationImport:" + locationImport, logLevel); log("\tserviceElementName:" + serviceElementName, logLevel); log("\tmethods:" + methods, logLevel); log("\textraClasses:" + extraClasses, logLevel); log("\tsoapAction:" + soapAction, logLevel); log("\tclasspath:" + classpath, logLevel); } /** * validation code * @throws BuildException if validation failed */ protected void validate() throws BuildException { if(className==null || className.length() ==0) { throw new BuildException("No classname was specified"); } if(location==null || location.length() == 0) { throw new BuildException("No location was specified"); } } /** * execute the task * @throws BuildException */ public void execute() throws BuildException { AntClassLoader cl = new AntClassLoader(getClass().getClassLoader(), getProject(), classpath == null ? createClasspath() : classpath, true); CommandlineJava.SysProperties sysProperties = commandline.getSystemProperties(); if (sysProperties != null) { sysProperties.setSystem(); } try { traceParams(Project.MSG_VERBOSE); validate(); // Instantiate the emitter Emitter emitter = new Emitter(); //do the mappings, packages are the key for this map mappings.execute(this,namespaceMap, true); if (!namespaceMap.isEmpty()) { emitter.setNamespaceMap(namespaceMap); } if (servicePortName != null) { emitter.setServicePortName(servicePortName); } if (portTypeName != null) { emitter.setPortTypeName(portTypeName); } if (bindingName != null) { emitter.setBindingName(bindingName); } log("Java2WSDL " + className, Project.MSG_INFO); emitter.setCls(cl.loadClass(className)); if (implClass != null) { emitter.setImplCls(cl.loadClass(implClass)); } if (exclude != null) { emitter.setDisallowedMethods(exclude); } if (stopClasses != null) { emitter.setStopClasses(stopClasses); } if (extraClasses != null) { emitter.setExtraClasses(extraClasses, cl); } TypeMappingRegistryImpl tmr = new TypeMappingRegistryImpl(); tmr.doRegisterFromVersion(typeMappingVersion); emitter.setTypeMappingRegistry(tmr); // Create TypeMapping and register complex types TypeMappingDelegate tmi = (TypeMappingDelegate)tmr.getDefaultTypeMapping(); Iterator i = complexTypes.iterator(); while (i.hasNext()) { ((ComplexType) i.next()).register(cl, tmi); } if (style != null) { emitter.setStyle(style); } if (use != null) { emitter.setUse(use); } if (importSchema != null) { emitter.setInputSchema(importSchema); } if (input != null) { emitter.setInputWSDL(input); } emitter.setIntfNamespace(namespace); emitter.setImplNamespace(namespaceImpl); emitter.setLocationUrl(location); emitter.setImportUrl(locationImport); emitter.setUseInheritedMethods(useInheritedMethods); if(serviceElementName!=null) { emitter.setServiceElementName(serviceElementName); } if(methods!=null) { emitter.setAllowedMethods(methods); } if (soapAction != null) { emitter.setSoapAction(soapAction); } if (outputImpl == null) { // Normal case emitter.emit(output, Emitter.MODE_ALL); } else { // Emit interface and implementation wsdls emitter.emit(output, outputImpl); } if (isDeploy == true) { generateServerSide(emitter, (outputImpl != null) ? outputImpl : output); } } catch(BuildException b) { //pass build exceptions up the wire throw b; } catch (Throwable t) { //other trouble: stack trace the trouble and throw an exception StringWriter writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); log(writer.getBuffer().toString(), Project.MSG_ERR); throw new BuildException("Error while running " + getClass().getName(), t); } finally { if (sysProperties != null) { sysProperties.restoreSystem(); } } } /** * The name of the output WSDL file. * If not specified, a suitable default WSDL file is written into * the current directory. * @param parameter */ public void setOutput(File parameter) { this.output = parameter.getPath(); } /** * Option attribute that indicates the name of an XML Schema file that * should be physically imported into the generated WSDL. * @param parameter */ public void setImportSchema(File parameter) throws BuildException { try { this.importSchema = parameter.toURL().toString(); } catch (java.io.IOException ioe) { throw new BuildException(ioe); } } /** * Optional attribute that indicates the name of the input wsdl file. * The output wsdl file will contain everything from the input wsdl * file plus the new constructs. If a new construct is already present * in the input wsdl file, it is not added. This option is useful for * constructing a wsdl file with multiple ports, bindings, or portTypes. * @param parameter filename */ public void setInput(File parameter) { this.input = parameter.getPath(); } /** * Use this option to indicate the name of the output implementation WSDL * file. If specified, Java2WSDL will produce separate interface and implementation * WSDL files. If not, a single WSDL file is generated * @param parameter */ public void setOutputImpl(File parameter) { this.outputImpl = parameter.getPath(); } /** * The url of the location of the service. The name after the last slash or * backslash is the name of the service port (unless overridden by the -s * option). The service port address location attribute is assigned the * specified value. * @param parameter a URL */ public void setLocation(String parameter) { this.location = parameter; } /** * the location of the interface WSDL when generating an implementation WSDL * Required when <tt>outputImpl</tt> is set * @param parameter URL? */ public void setLocationImport(String parameter) { this.locationImport = parameter; } /** * the class name to import, eg. org.example.Foo. Required. * The class must be on the classpath. * @param parameter fully qualified class name */ public void setClassName(String parameter) { this.className = parameter; } /** * Sometimes extra information is available in the implementation class * file. Use this option to specify the implementation class. * @param parameter */ public void setImplClass(String parameter) { this.implClass = parameter; } /** * service port name (obtained from location if not specified) * @param parameter portname */ public void setServicePortName(String parameter) { this.servicePortName = parameter; } /** * Indicates the name to use use for the portType element. * If not specified, the class-of-portType name is used. * @param parameter */ public void setPortTypeName(String parameter) { this.portTypeName = parameter; } /** * The name to use use for the binding element. * If not specified, the value of the * <tt>servicePortName</tt> + "SoapBinding" is used. * @param parameter */ public void setBindingName(String parameter) { this.bindingName = parameter; } /** * the target namespace. Required. * @param parameter */ public void setNamespace(String parameter) { this.namespace = parameter; } /** * Namespace of the implementation WSDL. * @param parameter */ public void setNamespaceImpl(String parameter) { this.namespaceImpl = parameter; } /** * should inherited methods be exported too? Default=false * @param parameter */ public void setUseInheritedMethods(boolean parameter) { this.useInheritedMethods = parameter; } /** * Comma separated list of methods to exclude from the wsdl file. * @param exclude */ public void setExclude(String exclude) { this.exclude = exclude; } /** * Comma separated list of classes which stop the Java2WSDL * inheritance search. * @param stopClasses */ public void setStopClasses(String stopClasses) { this.stopClasses = stopClasses; } /** * The style of the WSDL document: RPC, DOCUMENT or WRAPPED. * If RPC, a rpc/encoded wsdl is generated. If DOCUMENT, a * document/literal wsdl is generated. If WRAPPED, a * document/literal wsdl is generated using the wrapped approach. * @param style */ public void setStyle(String style) { this.style = style; } /** * add a mapping of namespaces to packages */ public void addMapping(NamespaceMapping mapping) { mappings.addMapping(mapping); } /** * add a mapping of namespaces to packages */ public void addMappingSet(MappingSet mappingset) { mappings.addMappingSet(mappingset); } /** * the default type mapping registry to use. Either 1.1 or 1.2. * Default is 1.1 * @param parameter new version */ public void setTypeMappingVersion(TypeMappingVersionEnum parameter) { this.typeMappingVersion = parameter.getValue(); } /** * If this option is specified, only the indicated methods in your * interface class will be exported into the WSDL file. The methods list * must be comma separated. If not specified, all methods declared in * the interface class will be exported into the WSDL file * @param methods list of methods */ public void setMethods(String methods) { this.methods = methods; } /** * Set the use option */ public void setUse(String use) { this.use = use; } /** * the name of the service element. * If not specified, the service element is the <tt>portTypeName</tt>Service. * @param serviceElementName */ public void setServiceElementName(String serviceElementName) { this.serviceElementName = serviceElementName; } /** * A comma separated list of classes to add to the classpath. */ public void setExtraClasses(String extraClasses) { this.extraClasses = extraClasses; } /** * The setter for the "soapAction" attribute */ public void setSoapAction( String soapAction ) { this.soapAction = soapAction; } /** * Nested element for Complex Types. * Each Complex Type uses the following fields: * @param ct */ public void addComplexType(ComplexType ct) { complexTypes.add(ct); } /** * Set the optional classpath * * @param classpath the classpath to use when loading class */ public void setClasspath(Path classpath) { createClasspath().append(classpath); } /** * Set the optional classpath * * @return a path instance to be configured by the Ant core. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); classpath = classpath.concatSystemClasspath(); } return classpath.createPath(); } /** * Set the reference to an optional classpath * * @param r the id of the Ant path instance to act as the classpath */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } /** * Adds a system property that tests can access. * @param sysp environment variable to add */ public void addSysproperty(Environment.Variable sysp) { commandline.addSysproperty(sysp); } /** * Sets the deploy flag * @param deploy true if deploy mode */ public void setDeploy(boolean deploy) { this.isDeploy = deploy; } /** * Generate the server side artifacts from the generated WSDL * * @param j2w the Java2WSDL emitter * @param wsdlFileName the generated WSDL file * @throws Exception */ protected void generateServerSide(Emitter j2w, String wsdlFileName) throws Exception { org.apache.axis.wsdl.toJava.Emitter w2j = new org.apache.axis.wsdl.toJava.Emitter(); File wsdlFile = new File(wsdlFileName); w2j.setServiceDesc(j2w.getServiceDesc()); w2j.setQName2ClassMap(j2w.getQName2ClassMap()); w2j.setOutputDir(wsdlFile.getParent()); w2j.setServerSide(true); w2j.setDeploy(true); w2j.setHelperWanted(true); // setup namespace-to-package mapping String ns = j2w.getIntfNamespace(); String clsName = j2w.getCls().getName(); int idx = clsName.lastIndexOf("."); String pkg = null; if (idx > 0) { pkg = clsName.substring(0, idx); w2j.getNamespaceMap().put(ns, pkg); } Map nsmap = j2w.getNamespaceMap(); if (nsmap != null) { for (Iterator i = nsmap.keySet().iterator(); i.hasNext(); ) { pkg = (String) i.next(); ns = (String) nsmap.get(pkg); w2j.getNamespaceMap().put(ns, pkg); } } // set 'deploy' mode w2j.setDeploy(true); if (j2w.getImplCls() != null) { w2j.setImplementationClassName(j2w.getImplCls().getName()); } else { if (!j2w.getCls().isInterface()) { w2j.setImplementationClassName(j2w.getCls().getName()); } else { throw new Exception("implementation class is not specified."); } } w2j.run(wsdlFileName); } }
6,863
0
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant
Create_ds/axis-axis1-java/axis-ant/src/main/java/org/apache/axis/tools/ant/wsdl/ComplexType.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.tools.ant.wsdl; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.ser.BaseSerializerFactory; import org.apache.axis.encoding.ser.BaseDeserializerFactory; import javax.xml.rpc.encoding.SerializerFactory; import javax.xml.rpc.encoding.DeserializerFactory; import javax.xml.namespace.QName; public class ComplexType { private String className; private String serializer = "org.apache.axis.encoding.ser.BeanSerializerFactory"; private String deserializer = "org.apache.axis.encoding.ser.BeanDeserializerFactory"; private String namespace; public ComplexType() {} public void setClassName(String className) { this.className = className; } public void setSerializer(String serializer) { this.serializer = serializer; } public void setDeserializer(String deserializer) { this.deserializer = deserializer; } public void setNameSpace(String namespace) { this.namespace = namespace; } public void register(ClassLoader cl, TypeMapping tm) throws ClassNotFoundException { Class cls = cl.loadClass(className); String localName = className.substring((className.lastIndexOf(".") + 1)); QName qName = new QName(namespace,localName); SerializerFactory sf = BaseSerializerFactory.createFactory( cl.loadClass(serializer), cls, qName); DeserializerFactory df = BaseDeserializerFactory.createFactory( cl.loadClass(deserializer), cls, qName); tm.register(cls, qName, sf, df); } }
6,864
0
Create_ds/axis-axis1-java/axis-codegen/src/test/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/test/java/org/apache/axis/wsdl/toJava/TestUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.axis.wsdl.toJava; import junit.framework.TestCase; public class TestUtils extends TestCase { /** * Test for Bug 17995 - wsdl2java converts namespace to uncompilable packages */ public void testPackageNaming() { assertEquals("_0._1.util.liberty", Utils.makePackageName("urn:liberty:util:1.0")); } }
6,865
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/FactoryProperty.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.wsdl.toJava; /** This is a general purpose class that allows one to pass name/value properties to the JavaGeneratorFactory. @author Jim Stafford (jim.stafford@raba.com) */ public class FactoryProperty { private String name_; private String value_; public FactoryProperty() { } public String getName() { return name_; } public String getValue() { return value_; } public void setName(String string) { name_ = string; } public void setValue(String string) { value_ = string; } public String toString() { return name_ + "=" + value_; } public boolean equals(Object rhs) { if (rhs == null) { return false; } else if (rhs instanceof String) { return ((String)rhs).equals(name_); } else if (rhs instanceof FactoryProperty) { return ((FactoryProperty)rhs).equals(name_); } else { return false; } } }
6,866
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaDeployWriter.java
/* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Scope; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.model.wsdd.ArrayMapping; import org.apache.axis.model.wsdd.Deployment; import org.apache.axis.model.wsdd.Fault; import org.apache.axis.model.wsdd.OperationParameter; import org.apache.axis.model.wsdd.ParameterMode; import org.apache.axis.model.wsdd.TypeMapping; import org.apache.axis.model.wsdd.WSDDFactory; import org.apache.axis.model.wsdd.WSDDUtil; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.StringUtils; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.commons.logging.Log; import javax.wsdl.Binding; import javax.wsdl.BindingOperation; import javax.wsdl.Definition; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.extensions.soap.SOAPBinding; import javax.wsdl.extensions.soap12.SOAP12Binding; import javax.xml.namespace.QName; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * This is Wsdl2java's deploy Writer. It writes the deploy.wsdd file. */ public class JavaDeployWriter extends JavaWriter { /** Field log */ protected static Log log = LogFactory.getLog(JavaDeployWriter.class.getName()); /** Field definition */ protected Definition definition; /** Field symbolTable */ protected SymbolTable symbolTable; /** Field emitter */ protected Emitter emitter; /** Field use */ Use use = Use.DEFAULT; /** * Constructor. * * @param emitter * @param definition * @param symbolTable */ public JavaDeployWriter(Emitter emitter, Definition definition, SymbolTable symbolTable) { super(emitter, "deploy"); this.emitter = emitter; this.definition = definition; this.symbolTable = symbolTable; } // ctor /** * Generate deploy.wsdd. Only generate it if the emitter * is generating server-side mappings. * * @throws IOException */ public void generate() throws IOException { if (emitter.isServerSide()) { super.generate(); } } // generate /** * Return the fully-qualified name of the deploy.wsdd file * to be generated. * * @return */ protected String getFileName() { String dir = emitter.getNamespaces().getAsDir(definition.getTargetNamespace()); return dir + "deploy.wsdd"; } // getFileName /** * Replace the default file header with the deployment doc file header. * * @param pw * @throws IOException */ protected void writeFileHeader(PrintWriter pw) throws IOException { pw.println(Messages.getMessage("deploy00")); pw.println(Messages.getMessage("deploy02")); pw.println(Messages.getMessage("deploy03")); pw.println(Messages.getMessage("deploy05")); pw.println(Messages.getMessage("deploy06")); pw.println(Messages.getMessage("deploy07")); pw.println(Messages.getMessage("deploy09")); pw.println(); } // writeFileHeader /** * Write the body of the deploy.wsdd file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { Deployment deployment = WSDDFactory.INSTANCE.createDeployment(); writeDeployServices(deployment); WSDDUtil.save(deployment, pw); } // writeFileBody /** * Write out deployment and undeployment instructions for each WSDL service * * @param deployment * @throws IOException */ protected void writeDeployServices(Deployment deployment) throws IOException { // deploy the ports on each service Map serviceMap = definition.getServices(); for (Iterator mapIterator = serviceMap.values().iterator(); mapIterator.hasNext();) { Service myService = (Service) mapIterator.next(); for (Iterator portIterator = myService.getPorts().values().iterator(); portIterator.hasNext();) { Port myPort = (Port) portIterator.next(); BindingEntry bEntry = symbolTable.getBindingEntry(myPort.getBinding().getQName()); // If this isn't an SOAP binding, skip it if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } writeDeployPort(deployment, myPort, myService, bEntry); } } } // writeDeployServices /** * Write out bean mappings for each type * * @param service * @param binding * @param hasLiteral * @param hasMIME * @param use * @throws IOException */ protected void writeDeployTypes( org.apache.axis.model.wsdd.Service service, Binding binding, boolean hasLiteral, boolean hasMIME, Use use) throws IOException { if (hasMIME) { QName bQName = binding.getQName(); TypeMapping typeMapping = WSDDFactory.INSTANCE.createTypeMapping(); typeMapping.setQname(new QName(bQName.getNamespaceURI(), "DataHandler")); typeMapping.setType(new QName(WSDDConstants.URI_WSDD_JAVA, "javax.activation.DataHandler", WSDDConstants.NS_PREFIX_WSDD_JAVA)); typeMapping.setSerializer("org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"); typeMapping.setDeserializer("org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"); typeMapping.setEncodingStyle(use.getEncoding()); service.getTypeMappings().add(typeMapping); } Map types = symbolTable.getTypeIndex(); Collection typeCollection = types.values(); for (Iterator i = typeCollection.iterator(); i.hasNext(); ) { TypeEntry type = (TypeEntry) i.next(); // Note this same check is repeated in JavaStubWriter. boolean process = true; // Don't register types we shouldn't (see Utils.shouldEmit for // details) if (!Utils.shouldEmit(type)) { process = false; } if (process) { String javaType = type.getName(); String serializerFactory; String deserializerFactory; String encodingStyle = ""; QName innerType = null; if (!hasLiteral) { encodingStyle = use.getEncoding(); } if (javaType.endsWith("[]")) { if (SchemaUtils.isListWithItemType(type.getNode())) { serializerFactory = "org.apache.axis.encoding.ser.SimpleListSerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.SimpleListDeserializerFactory"; } else { serializerFactory = "org.apache.axis.encoding.ser.ArraySerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.ArrayDeserializerFactory"; innerType = type.getComponentType(); } } else if ((type.getNode() != null) && (Utils.getEnumerationBaseAndValues( type.getNode(), symbolTable) != null)) { serializerFactory = "org.apache.axis.encoding.ser.EnumSerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.EnumDeserializerFactory"; } else if (type.isSimpleType()) { serializerFactory = "org.apache.axis.encoding.ser.SimpleSerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.SimpleDeserializerFactory"; } else if (type.getBaseType() != null) { serializerFactory = "org.apache.axis.encoding.ser.SimpleSerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.SimpleDeserializerFactory"; } else { serializerFactory = "org.apache.axis.encoding.ser.BeanSerializerFactory"; deserializerFactory = "org.apache.axis.encoding.ser.BeanDeserializerFactory"; } if (innerType == null) { // no arrays TypeMapping typeMapping = WSDDFactory.INSTANCE.createTypeMapping(); typeMapping.setQname(type.getQName()); typeMapping.setType(new QName(WSDDConstants.URI_WSDD_JAVA, javaType)); typeMapping.setSerializer(serializerFactory); typeMapping.setDeserializer(deserializerFactory); typeMapping.setEncodingStyle(encodingStyle); service.getTypeMappings().add(typeMapping); } else { // arrays ArrayMapping arrayMapping = WSDDFactory.INSTANCE.createArrayMapping(); arrayMapping.setQname(type.getQName()); arrayMapping.setType(new QName(WSDDConstants.URI_WSDD_JAVA, javaType)); arrayMapping.setEncodingStyle(encodingStyle); arrayMapping.setInnerType(innerType); service.getArrayMappings().add(arrayMapping); } } } } // writeDeployTypes /** * Write out deployment and undeployment instructions for given WSDL port * * @param deployment * @param port * @param service * @param bEntry * @throws IOException */ protected void writeDeployPort( Deployment deployment, Port port, Service service, BindingEntry bEntry) throws IOException { String serviceName = port.getName(); boolean hasLiteral = bEntry.hasLiteral(); boolean hasMIME = Utils.hasMIME(bEntry); Style style; Iterator iterator = bEntry.getBinding().getExtensibilityElements().iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj instanceof SOAPBinding || obj instanceof SOAP12Binding) { use = Use.ENCODED; } } if (symbolTable.isWrapped()) { style = Style.WRAPPED; use = Use.LITERAL; } else { style = bEntry.getBindingStyle(); if (hasLiteral) { use = Use.LITERAL; } } org.apache.axis.model.wsdd.Service wsddService = WSDDFactory.INSTANCE.createService(); wsddService.setName(serviceName); wsddService.setProvider(new QName(WSDDConstants.URI_WSDD_JAVA, "RPC")); wsddService.setStyle(style); wsddService.setUse(use); wsddService.setParameter("wsdlTargetNamespace", service.getQName().getNamespaceURI()); wsddService.setParameter("wsdlServiceElement", service.getQName().getLocalPart()); // MIME attachments don't work with multiref, so turn it off. if (hasMIME) { wsddService.setParameter("sendMultiRefs", "false"); } ArrayList qualified = new ArrayList(); ArrayList unqualified = new ArrayList(); Map elementFormDefaults = symbolTable.getElementFormDefaults(); for(Iterator it = elementFormDefaults.entrySet().iterator();it.hasNext();){ Map.Entry entry = (Map.Entry) it.next(); if(entry.getValue().equals("qualified")){ qualified.add(entry.getKey()); } else { unqualified.add(entry.getKey()); } } if(qualified.size()>0){ wsddService.setParameter("schemaQualified", StringUtils.join(qualified, ',')); } if(unqualified.size()>0){ wsddService.setParameter("schemaUnqualified", StringUtils.join(unqualified, ',')); } wsddService.setParameter("wsdlServicePort", serviceName); writeDeployBinding(wsddService, bEntry); writeDeployTypes(wsddService, bEntry.getBinding(), hasLiteral, hasMIME, use); deployment.getServices().add(wsddService); } // writeDeployPort /** * Write out deployment instructions for given WSDL binding * * @param service * @param bEntry * @throws IOException */ protected void writeDeployBinding(org.apache.axis.model.wsdd.Service service, BindingEntry bEntry) throws IOException { Binding binding = bEntry.getBinding(); String className = bEntry.getName(); if (emitter.isSkeletonWanted()) { className += "Skeleton"; } else { String customClassName = emitter.getImplementationClassName(); if ( customClassName != null ) className = customClassName; else className += "Impl"; } service.setParameter("className", className); service.setParameter("wsdlPortType", binding.getPortType().getQName().getLocalPart()); service.setParameter("typeMappingVersion", emitter.getTypeMappingVersion()); HashSet allowedMethods = new HashSet(); String namespaceURI = binding.getQName().getNamespaceURI(); if (!emitter.isSkeletonWanted()) { Iterator operationsIterator = binding.getBindingOperations().iterator(); for (; operationsIterator.hasNext();) { BindingOperation bindingOper = (BindingOperation) operationsIterator.next(); Operation operation = bindingOper.getOperation(); OperationType type = operation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { continue; } String javaOperName = null; ServiceDesc serviceDesc = emitter.getServiceDesc(); if (emitter.isDeploy() && serviceDesc != null) { // If the emitter works in deploy mode, sync the java operation name with it of the ServiceDesc OperationDesc[] operDescs = serviceDesc.getOperationsByQName(new QName(namespaceURI, operation.getName())); if (operDescs.length == 0) { log.warn("Can't find operation in the Java Class for WSDL binding operation : " + operation.getName()); continue; } OperationDesc operDesc = operDescs[0]; if (operDesc.getMethod() == null) { log.warn("Can't find Java method for operation descriptor : " + operDesc.getName()); continue; } javaOperName = operDesc.getMethod().getName(); } else { javaOperName = JavaUtils.xmlNameToJava(operation.getName()); } allowedMethods.add(javaOperName); // We pass "" as the namespace argument because we're just // interested in the return type for now. Parameters params = symbolTable.getOperationParameters(operation, "", bEntry); if (params != null) { // TODO: Should really construct a FaultDesc here and // TODO: pass it to writeOperation, but this will take // TODO: some refactoring // Get the operation QName QName elementQName = Utils.getOperationQName(bindingOper, bEntry, symbolTable); // Get the operation's return QName and type QName returnQName = null; QName returnType = null; if (params.returnParam != null) { returnQName = params.returnParam.getQName(); returnType = Utils.getXSIType(params.returnParam); } // Get the operations faults Map faultMap = bEntry.getFaults(); ArrayList faults = null; if (faultMap != null) { faults = (ArrayList) faultMap.get(bindingOper); } // Get the operation's SOAPAction String SOAPAction = Utils.getOperationSOAPAction(bindingOper); // Write the operation metadata writeOperation(service, javaOperName, elementQName, returnQName, returnType, params, binding.getQName(), faults, SOAPAction); } } } service.setParameter("allowedMethods", allowedMethods.isEmpty() ? "*" : StringUtils.join(allowedMethods, ' ')); Scope scope = emitter.getScope(); if (scope != null) { service.setParameter("scope", scope.getName()); } } // writeDeployBinding /** * Raw routine that writes out the operation and parameters. * * @param service * @param javaOperName * @param elementQName * @param returnQName * @param returnType * @param params * @param bindingQName * @param faults */ protected void writeOperation(org.apache.axis.model.wsdd.Service service, String javaOperName, QName elementQName, QName returnQName, QName returnType, Parameters params, QName bindingQName, ArrayList faults, String SOAPAction) { org.apache.axis.model.wsdd.Operation operation = WSDDFactory.INSTANCE.createOperation(); operation.setName(javaOperName); operation.setQname(elementQName); if (returnQName != null) { operation.setReturnQName(new QName(returnQName.getNamespaceURI(), Utils.getLastLocalPart(returnQName.getLocalPart()))); } operation.setReturnType(returnType); Parameter retParam = params.returnParam; if (retParam != null) { TypeEntry type = retParam.getType(); operation.setReturnItemQName(Utils.getItemQName(type)); if (use == Use.ENCODED) { operation.setReturnItemType(Utils.getItemType(type)); } } operation.setSoapAction(SOAPAction); if (!OperationType.REQUEST_RESPONSE.equals(params.mep)) { operation.setMep(getMepString(params.mep)); } if ((params.returnParam != null) && params.returnParam.isOutHeader()) { operation.setReturnHeader(Boolean.TRUE); } Vector paramList = params.list; for (int i = 0; i < paramList.size(); i++) { Parameter param = (Parameter) paramList.elementAt(i); // Get the parameter name QName and type QName QName paramQName = param.getQName(); QName paramType = Utils.getXSIType(param); OperationParameter parameter = WSDDFactory.INSTANCE.createOperationParameter(); if (paramQName == null) { parameter.setName(param.getName()); } else { parameter.setQname(new QName(paramQName.getNamespaceURI(), Utils.getLastLocalPart(paramQName.getLocalPart()))); } parameter.setType(paramType); // Get the parameter mode if (param.getMode() != Parameter.IN) { parameter.setMode(ParameterMode.get(param.getMode())); } // Is this a header? if (param.isInHeader()) { parameter.setInHeader(Boolean.TRUE); } if (param.isOutHeader()) { parameter.setOutHeader(Boolean.TRUE); } parameter.setItemQName(Utils.getItemQName(param.getType())); operation.getParameters().add(parameter); } if (faults != null) { for (Iterator iterator = faults.iterator(); iterator.hasNext();) { FaultInfo faultInfo = (FaultInfo) iterator.next(); QName faultQName = faultInfo.getQName(); if (faultQName != null) { String className = Utils.getFullExceptionName(faultInfo.getMessage(), symbolTable); Fault fault = WSDDFactory.INSTANCE.createFault(); fault.setName(faultInfo.getName()); fault.setQname(faultQName); fault.setClass(className); fault.setType(faultInfo.getXMLType()); operation.getFaults().add(fault); } } } service.getOperations().add(operation); } /** * Method getPrintWriter * * @param filename * @return * @throws IOException */ protected PrintWriter getPrintWriter(String filename) throws IOException { File file = new File(filename); File parent = new File(file.getParent()); parent.mkdirs(); FileOutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); return new PrintWriter(writer); } private static final Map mepStrings = new HashMap(); static { mepStrings.put(OperationType.REQUEST_RESPONSE.toString(), "request-response"); mepStrings.put(OperationType.ONE_WAY.toString(), "oneway"); } String getMepString(OperationType mep) { return (String)mepStrings.get(mep.toString()); } } // class JavaDeployWriter
6,867
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.Constants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.ContainedAttribute; import org.apache.axis.wsdl.symbolTable.ElementDecl; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; /** * This is Wsdl2java's Complex Type Writer. It writes the &lt;typeName&gt;.java file. */ public class JavaBeanWriter extends JavaClassWriter { /** Field type */ private TypeEntry type; /** Field elements */ private Vector elements; /** Field attributes */ private Vector attributes; /** Field extendType */ private TypeEntry extendType; /** Field helper */ protected JavaBeanHelperWriter helper; /** Field names */ protected Vector names = new Vector(); // even indices: types, odd: vars /** Field simpleValueTypes */ protected ArrayList simpleValueTypes = new ArrayList(); // name of type of simple value /** Field enumerationTypes */ protected Set enumerationTypes = new HashSet(); // name of enumerated types /** Field pw */ protected PrintWriter pw; // The following fields can be set by extended classes // to control processing /** Field enableDefaultConstructor */ protected boolean enableDefaultConstructor = true; /** Field enableFullConstructor */ protected boolean enableFullConstructor = false; /** Field enableSimpleConstructors */ protected boolean enableSimpleConstructors = false; /** Field enableToString */ protected boolean enableToString = false; /** Field enableSetters */ protected boolean enableSetters = true; /** Field enableGetters */ protected boolean enableGetters = true; /** Field enableEquals */ protected boolean enableEquals = true; /** Field enableHashCode */ protected boolean enableHashCode = true; /** Field enableMemberFields */ protected boolean enableMemberFields = true; /** Field isAny */ protected boolean isAny = false; /** Field isMixed */ protected boolean isMixed = false; /** Field parentIsAny */ protected boolean parentIsAny = false; /** Field parentIsMixed */ protected boolean parentIsMixed = false; /** * Constructor. * * @param emitter * @param type The type representing this class * @param elements Vector containing the Type and name of each property * @param extendType The type representing the extended class (or null) * @param attributes Vector containing the attribute types and names * @param helper Helper class writer */ protected JavaBeanWriter(Emitter emitter, TypeEntry type, Vector elements, TypeEntry extendType, Vector attributes, JavaWriter helper) { super(emitter, type.getName(), "complexType"); this.type = type; this.elements = elements; this.attributes = attributes; this.extendType = extendType; this.helper = (JavaBeanHelperWriter) helper; if (type.isSimpleType()) { enableSimpleConstructors = true; enableToString = true; } else { // is this a complex type that is derived from other types // by restriction? if so, do not emit instance variables // or accessor/mutator pairs as those are inherited from // the super type, which must be non-null. if (null != extendType) { if (null != SchemaUtils.getComplexElementRestrictionBase( type.getNode(), emitter.getSymbolTable())) { enableMemberFields = false; enableGetters = false; enableSetters = false; enableEquals = false; enableHashCode = false; } else { // derived by extension. // Write full constructor, so that instance variables // in super class are intialized. enableFullConstructor = true; } } } preprocess(); } // ctor /** * Write a common header, including the package name, the class * declaration, and the opening curly brace. * Prints javadoc from WSDL documentation. (Cannot pull up, type DOM not avail) */ protected void writeFileHeader(PrintWriter pw) throws IOException { writeHeaderComments(pw); writePackage(pw); try { String comments = SchemaUtils.getAnnotationDocumentation(type.getNode()); comments = getJavadocDescriptionPart(comments, false); if (comments != null && comments.trim().length() > 0) { pw.println(); pw.println("/**"); pw.println(comments); pw.println(" */"); } } catch (DOMException e) { // no comment } // print class declaration pw.println(getClassModifiers() + getClassText() + getClassName() + ' ' + getExtendsText() + getImplementsText() + "{"); } // writeFileHeader /** * Generate the binding for the given complex type. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { this.pw = pw; // Populate Names Vector with the names and types of the members. // The write methods use the names vector whenever they need to get // a member name or type. Moved to implements callback in order // to set any interface // preprocess(); // Write Member Fields if (enableMemberFields) { writeMemberFields(); } // Write the default constructor if (enableDefaultConstructor) { writeDefaultConstructor(); } // Write Full Constructor if (enableFullConstructor) { writeFullConstructor(); } // Write SimpleConstructors if (enableSimpleConstructors) { writeSimpleConstructors(); } if(!enableFullConstructor && !enableSimpleConstructors && enableMemberFields) { writeMinimalConstructor(); } // Write ToString method if (enableToString) { writeToStringMethod(); } // Write accessor methods writeAccessMethods(); // Write general purpose equals and hashCode methods if (enableEquals) { writeEqualsMethod(); } if (enableHashCode) { writeHashCodeMethod(); } // Write the meta data into a Helper class or // embed it in the bean class if (!emitter.isHelperWanted()) { // Write the helper info into the bean class helper.setPrintWriter(pw); } helper.generate(); } // writeFileBody /** * Builds the names String vector. * The even indices are the java class names of the * member fields. The odd indices are the member variable * names. * Also sets the simpleValueType variable to the * java class name of the simple value if this bean represents * a simple type */ protected void preprocess() { // Add element names if (elements != null) { // Check the inheritance chain for xs:any and xs:mixed TypeEntry parent = extendType; while ((!parentIsAny || !parentIsMixed) && parent != null) { if (SchemaUtils.isMixed(parent.getNode())) { parentIsMixed = true; } Vector hisElements = parent.getContainedElements(); for (int i = 0; hisElements != null && i < hisElements.size(); i++) { ElementDecl elem = (ElementDecl) hisElements.get(i); if (elem.getAnyElement()) { parentIsAny = true; } } parent = SchemaUtils.getComplexElementExtensionBase(parent.getNode(), emitter.getSymbolTable()); } for (int i = 0; i < elements.size(); i++) { ElementDecl elem = (ElementDecl) elements.get(i); String typeName = elem.getType().getName(); String variableName = null; if (elem.getAnyElement()) { if (!parentIsAny && !parentIsMixed) { typeName = "org.apache.axis.message.MessageElement []"; variableName = Constants.ANYCONTENT; } isAny = true; } else { variableName = elem.getName(); typeName = processTypeName(elem, typeName); } if (variableName == null) { continue; } // Make sure the property name is not reserved. variableName = JavaUtils.getUniqueValue( helper.reservedPropNames, variableName); names.add(typeName); names.add(variableName); if (type.isSimpleType() && (variableName.endsWith("Value") || variableName.equals("_value"))) { simpleValueTypes.add(typeName); } // bug 19069: need to generate code that access member variables that // are enum types through the class interface, not the constructor // this util method returns non-null if the type at node is an enum if (null != Utils.getEnumerationBaseAndValues( elem.getType().getNode(), emitter.getSymbolTable())) { enumerationTypes.add(typeName); } } } if (enableMemberFields && SchemaUtils.isMixed(type.getNode())) { isMixed = true; if (!isAny && !parentIsAny && !parentIsMixed) { names.add("org.apache.axis.message.MessageElement []"); names.add(Constants.ANYCONTENT); } } // Add attribute names if (attributes != null) { for (int i = 0; i < attributes.size(); i++) { ContainedAttribute attr = (ContainedAttribute) attributes.get(i); String typeName = attr.getType().getName(); String variableName = getAttributeName(attr); // TODO - What about MinOccurs and Nillable? // Do they make sense here? if (attr.getOptional()) { typeName = Utils.getWrapperType(typeName); } // Make sure the property name is not reserved. variableName = JavaUtils.getUniqueValue( helper.reservedPropNames, variableName); names.add(typeName); names.add(variableName); if (type.isSimpleType() && (variableName.endsWith("Value") || variableName.equals("_value"))) { simpleValueTypes.add(typeName); } // bug 19069: need to generate code that access member variables that // are enum types through the class interface, not the constructor // this util method returns non-null if the type at node is an enum if (null != Utils.getEnumerationBaseAndValues(attr.getType().getNode(), emitter.getSymbolTable())) { enumerationTypes.add(typeName); } } } if ((extendType != null) && extendType.getDimensions().equals("[]")) { String typeName = extendType.getName(); String elemName = extendType.getQName().getLocalPart(); String variableName = JavaUtils.xmlNameToJava(elemName); names.add(typeName); names.add(variableName); } if((extendType != null) && (Utils.getEnumerationBaseAndValues( extendType.getNode(), emitter.getSymbolTable()) != null)){ enableDefaultConstructor = false; } // Check for duplicate names and make them unique // Start at index 2 and go by twos for (int i = 1; i < names.size(); i +=2) { int suffix = 2; // the number we append to the name String s = (String) names.elementAt(i); if (i < names.size() - 2) { int dup = names.indexOf(s, i+1); while (dup > 0) { // duplicate name, tack a number on the end names.set(dup, names.get(dup) + Integer.toString(suffix)); suffix++; // get out if we don't have more if (i >= names.size() - 2) break; dup = names.indexOf(s, dup+1); } } } } /** * generate a name for the attribute * @param attr * @return name */ private String getAttributeName(ContainedAttribute attr) { String variableName = attr.getName(); if (variableName == null) { variableName = Utils.getLastLocalPart(attr.getQName().getLocalPart()); } return variableName; } /** * Check if we need to use the wrapper type or MessageElement * * @param elem * @param typeName * @return type name */ private String processTypeName(ElementDecl elem, String typeName) { if (elem.getAnyElement()) { typeName = "org.apache.axis.message.MessageElement []"; } else if (elem.getType().getUnderlTypeNillable() || (elem.getNillable() && elem.getMaxOccursIsUnbounded())) { /* * Soapenc arrays with nillable underlying type or * nillable="true" maxOccurs="unbounded" elements * should be mapped to a wrapper type. */ typeName = Utils.getWrapperType(elem.getType()); } else if (elem.getMinOccursIs0() && elem.getMaxOccursIsExactlyOne() || elem.getNillable() || elem.getOptional()) { /* * Quote from JAX-RPC 1.1, Section 4.2.1: * There are a number of cases in which a built-in simple * XML data type must be mapped to the corresponding Java * wrapper class for the Java primitive type: * * an element declaration with the nillable attribute * set to true; * * an element declaration with the minOccurs attribute * set to 0 (zero) and the maxOccurs attribute set * to 1 (one) or absent; * * an attribute declaration with the use attribute set * to optional or absent and carrying neither * the default nor the fixed attribute; */ typeName = Utils.getWrapperType(typeName); } return typeName; } /** * Returns the class name that should be used to serialize and * deserialize this binary element */ protected String getBinaryTypeEncoderName(String elementName) { TypeEntry type = getElementDecl(elementName); if (type != null) { String typeName = type.getQName().getLocalPart(); if (typeName.equals("base64Binary")) return "org.apache.axis.encoding.Base64"; if (typeName.equals("hexBinary")) return "org.apache.axis.types.HexBinary"; throw new java.lang.RuntimeException("Unknown binary type " + typeName + " for element " + elementName); } throw new java.lang.RuntimeException("Unknown element " + elementName); } /** * Returns the TypeEntry of the given element */ protected TypeEntry getElementDecl(String elementName) { if (elements != null) { for (int i = 0; i < elements.size(); i++) { ElementDecl elem = (ElementDecl) elements.get(i); String variableName; if (elem.getAnyElement()) { variableName = Constants.ANYCONTENT; } else { variableName = elem.getName(); } if (variableName.equals(elementName)) return elem.getType(); } } return null; } /** * Returns the appropriate extends text * * @return "" or "abstract " */ protected String getClassModifiers() { Node node = type.getNode(); if (node != null) { if (JavaUtils.isTrueExplicitly(Utils.getAttribute(node, "abstract"))) { return super.getClassModifiers() + "abstract "; } } return super.getClassModifiers(); } // getClassModifiers /** * Returns the appropriate extends text * * @return "" or " extends &lt;class&gt; " */ protected String getExtendsText() { // See if this class extends another class String extendsText = ""; if ((extendType != null) && !isUnion() && (!type.isSimpleType() || !extendType.isBaseType()) && (extendType.getDimensions().length() == 0)) { extendsText = " extends " + extendType.getName() + " "; } return extendsText; } /** * Returns the appropriate implements text * * @return " implements &lt;classes&gt; " */ protected String getImplementsText() { // See if this class extends another class String implementsText = " implements java.io.Serializable"; if (type.isSimpleType() && (isUnion() || extendType == null || extendType.isBaseType())) { implementsText += ", org.apache.axis.encoding.SimpleType"; } if (isAny) { implementsText += ", org.apache.axis.encoding.AnyContentType"; } if (isMixed) { implementsText += ", org.apache.axis.encoding.MixedContentType"; } implementsText += " "; return implementsText; } /** * Writes the member fields. */ protected void writeMemberFields() { // Define the member element of the bean if (isUnion()) { pw.println(" private java.lang.String _value;"); return; } for (int i = 0; i < names.size(); i += 2) { // get comments for this field String comments = ""; if (elements != null) { if (elements != null && i < (elements.size()*2)) { ElementDecl elem = (ElementDecl)elements.get(i/2); comments = elem.getDocumentation(); } } String typeName = (String) names.get(i); String variable = (String) names.get(i + 1); // Declare the bean element if (comments != null && comments.trim().length() > 0) { String flatComments = getJavadocDescriptionPart(comments, true).substring(7); // it will be flat if it fits on one line pw.println(" /* " + flatComments.trim() + " */"); } pw.print(" private " + typeName + " " + variable + ";"); // label the attribute fields. if ((elements == null) || (i >= (elements.size() * 2))) { pw.println(" // attribute"); } else { pw.println(); } pw.println(); } } /** * Writes the default constructor. */ protected void writeDefaultConstructor() { // Define the default constructor pw.println(" public " + className + "() {"); pw.println(" }"); pw.println(); } /** * Write a constructor containing the fields in this class. * Will not write a construtor with more than 254 arguments as * the Java compiler will choke. */ protected void writeMinimalConstructor() { if (isUnion() || names.size() == 0 || names.size() > 254) { return; } pw.println(" public " + className + "("); for (int i = 0; i < names.size(); i += 2) { String typeName = (String) names.get(i); String variable = (String) names.get(i + 1); pw.print(" " + typeName + " " + variable); if (i >= names.size() - 2) { pw.println(") {"); } else { pw.println(","); } } for (int i = 0; i < names.size(); i += 2) { String variable = (String) names.get(i + 1); pw.println(" this." + variable + " = " + variable + ";"); if (i >= names.size() - 2) { break; } } pw.println(" }"); pw.println(); } /** * Writes the full constructor. * Note that this class is not recommended for * JSR 101 compliant beans, but is provided for * extended classes which may wish to generate a full * constructor. */ protected void writeFullConstructor() { if (type.isSimpleType()) { return; } // The constructor needs to consider all extended types Vector extendList = new Vector(); extendList.add(type); TypeEntry parent = extendType; while (parent != null) { if (parent.isSimpleType()) return; extendList.add(parent); parent = SchemaUtils.getComplexElementExtensionBase(parent.getNode(), emitter.getSymbolTable()); } // Now generate a list of names and types starting with // the oldest parent. (Attrs are considered before elements). Vector paramTypes = new Vector(); Vector paramNames = new Vector(); boolean gotAny = false; for (int i = extendList.size() - 1; i >= 0; i--) { TypeEntry te = (TypeEntry) extendList.elementAt(i); // The names of the inherited parms are mangled // in case they interfere with local parms. String mangle = ""; if (i > 0) { mangle = "_" + JavaUtils.xmlNameToJava(te.getQName().getLocalPart()) + "_"; } // Process the attributes Vector attributes = te.getContainedAttributes(); if (attributes != null) { for (int j = 0; j < attributes.size(); j += 1) { ContainedAttribute attr = (ContainedAttribute) attributes.get(j); String name = getAttributeName(attr); String typeName = attr.getType().getName(); // TODO - What about MinOccurs and Nillable? // Do they make sense here? if (attr.getOptional()) { typeName = Utils.getWrapperType(typeName); } paramTypes.add(typeName); paramNames.add(JavaUtils.getUniqueValue( helper.reservedPropNames, name)); } } // Process the elements Vector elements = te.getContainedElements(); if (elements != null) { for (int j = 0; j < elements.size(); j++) { ElementDecl elem = (ElementDecl) elements.get(j); if (elem.getAnyElement()) { if (!gotAny) { gotAny = true; paramTypes.add("org.apache.axis.message.MessageElement []"); paramNames.add(Constants.ANYCONTENT); } } else { paramTypes.add(processTypeName(elem,elem.getType().getName())); String name = elem.getName() == null ? ("param" + i) : elem.getName(); paramNames.add(JavaUtils.getUniqueValue( helper.reservedPropNames, name)); } } } } if (isMixed && !isAny && !parentIsAny && !parentIsMixed) { paramTypes.add("org.apache.axis.message.MessageElement []"); paramNames.add(Constants.ANYCONTENT); } // Set the index where the local params start int localParams = paramTypes.size() - names.size() / 2; // Now write the constructor signature if (paramTypes.size() > 0 && paramTypes.size() < 255) { // Prevent name clash between local parameters and the // parameters for the super class if(localParams > 0) { for (int j = 0; j < localParams; j++) { String name = (String) paramNames.elementAt(j); if(paramNames.indexOf(name, localParams)!=-1){ paramNames.set(j, "_" + name); } } } pw.println(" public " + className + "("); for (int i = 0; i < paramTypes.size(); i++) { pw.print(" " + paramTypes.elementAt(i) + " " + paramNames.elementAt(i)); if ((i + 1) < paramTypes.size()) { pw.println(","); } else { pw.println(") {"); } } // Call the extended constructor to set inherited fields if ((extendType != null) && (localParams > 0)) { pw.println(" super("); for (int j = 0; j < localParams; j++) { pw.print(" " + paramNames.elementAt(j)); if ((j + 1) < localParams) { pw.println(","); } else { pw.println(");"); } } } // Set local fields directly for (int j = localParams; j < paramNames.size(); j++) { pw.println(" this." + paramNames.elementAt(j) + " = " + paramNames.elementAt(j) + ";"); } pw.println(" }"); pw.println(); } } /** * Writes the constructors for SimpleTypes. * Writes a constructor accepting a string and * a constructor accepting the simple java type. */ protected void writeSimpleConstructors() { // If this is a simple type,need to emit a string // constructor and a value construtor. if (!type.isSimpleType()) return; pw.println(" // " + Messages.getMessage("needStringCtor")); // Simple types without simpleValueTypes are derived classes. // Inherit the simple constructor. if (simpleValueTypes.size() == 0) { if (extendType != null) { // Find the java type of the most base type. TypeEntry baseType = type; while (true) { TypeEntry superType = SchemaUtils.getBaseType( baseType, emitter.getSymbolTable()); if (superType == null) break; else baseType = superType; } String baseJavaType = baseType.getName(); pw.println(" public " + className + "(" + baseJavaType + " _value) {"); pw.println(" super(_value);"); pw.println(" }"); pw.println(); } } else if (isUnion() || simpleValueTypes.get(0).equals("java.lang.String")) { pw.println(" public " + className + "(java.lang.String _value) {"); pw.println(" this._value = _value;"); pw.println(" }"); int i = 0; for (Iterator iterator = simpleValueTypes.iterator(); iterator.hasNext();) { String typeName = (String) iterator.next(); if (typeName.equals("java.lang.String")) { i += 2; continue; } String capName = "_value"; if (isUnion()) { // names and simpleValueTypes should match as // union is over simple types String name = (String) names.get(i + 1); capName = Utils.capitalizeFirstChar(name); } pw.println(" public " + className + "(" + typeName + " _value) {"); pw.println(" set" + capName + "(_value);"); pw.println(" }"); pw.println(); i += 2; } } else if (simpleValueTypes.size() == 1) { pw.println(" public " + className + "(" + simpleValueTypes.get(0) + " _value) {"); pw.println(" this._value = _value;"); pw.println(" }"); pw.println(" public " + className + "(java.lang.String _value) {"); writeSimpleTypeGetter((String) simpleValueTypes.get(0), null, "this._value ="); pw.println(" }"); pw.println(); } } /** * Method writeSimpleTypeGetter * * @param simpleValueType * @param name * @param returnString */ protected void writeSimpleTypeGetter(String simpleValueType, String name, String returnString) { // Make sure we wrap base types with its Object type String wrapper = JavaUtils.getWrapper(simpleValueType); if (wrapper != null) { pw.println(" " + returnString + " new " + wrapper + "(_value)." + simpleValueType + "Value();"); } else { if (simpleValueType.equals("byte[]")) { String encoder = getBinaryTypeEncoderName ("_value"); pw.println(" " + returnString + " " + encoder + ".decode(_value);"); } else if (simpleValueType.equals("org.apache.axis.types.URI")) { pw.println(" try {"); pw.println(" " + returnString + " new org.apache.axis.types.URI(_value);"); pw.println(" }"); pw.println( " catch (org.apache.axis.types.URI.MalformedURIException mue) {"); pw.println( " throw new java.lang.RuntimeException(mue.toString());"); pw.println(" }"); } else if (simpleValueType.equals("java.util.Date")) { pw.println(" try {"); pw.println( " " + returnString + " (java.text.DateFormat.getDateTimeInstance()).parse(_value);"); pw.println(" }"); pw.println(" catch (java.text.ParseException e){"); pw.println( " throw new java.lang.RuntimeException(e.toString());"); pw.println(" }"); } else if (simpleValueType.equals("java.util.Calendar")) { pw.println(" java.util.Calendar cal ="); pw.println( " (java.util.Calendar) new org.apache.axis.encoding.ser.CalendarDeserializer("); pw.println( " java.lang.String.class, org.apache.axis.Constants.XSD_STRING).makeValue(_value);"); pw.println(" " + returnString + " cal;"); } else if (enumerationTypes.contains(simpleValueType)) { // we're generating code that will obtain a reference to an enumeration: use the // class forString interface, not the constructor. Bug 19069 pw.println(" " + returnString + " " + simpleValueType + ".fromString(_value);"); } else { pw.println(" " + returnString + " new " + simpleValueType + "(_value);"); } } } /** * Method isUnion * * @return */ private boolean isUnion() { return this.simpleValueTypes.size() > 1; } /** * Writes the toString method * Currently the toString method is only written for * simpleTypes. */ protected void writeToStringMethod() { // If this is a simple type, emit a toString if (simpleValueTypes.size() == 0) { return; } pw.println(" // " + Messages.getMessage("needToString")); pw.println(" public java.lang.String toString() {"); if (isUnion() || simpleValueTypes.get(0).equals("java.lang.String")) { pw.println(" return _value;"); } else { String wrapper = JavaUtils.getWrapper((String) simpleValueTypes.get(0)); if (wrapper != null) { pw.println(" return new " + wrapper + "(_value).toString();"); } else { String simpleValueType0 = (String)simpleValueTypes.get(0); if (simpleValueType0.equals("byte[]")) { String encoder = getBinaryTypeEncoderName ("_value"); pw.println( " return _value == null ? null : " + encoder + ".encode(_value);"); } else if (simpleValueType0.equals("java.util.Calendar")) { pw.println( " return _value == null ? null : new org.apache.axis.encoding.ser.CalendarSerializer().getValueAsString(_value, null);"); } else { pw.println( " return _value == null ? null : _value.toString();"); } } } pw.println(" }"); pw.println(); } /** * Method writeSimpleTypeSetter * * @param simpleValueType */ protected void writeSimpleTypeSetter(String simpleValueType) { String wrapper = JavaUtils.getWrapper(simpleValueType); if (wrapper != null) { pw.println(" this._value = new " + wrapper + "(_value).toString();"); } else { if (simpleValueType.equals("byte[]")) { String encoder = getBinaryTypeEncoderName ("_value"); pw.println( " this._value = _value == null ? null : " + encoder + ".encode(_value);"); } else if (simpleValueType.equals("java.util.Calendar")) { pw.println( " this._value = _value == null ? null : new org.apache.axis.encoding.ser.CalendarSerializer().getValueAsString(_value, null);"); } else { pw.println( " this._value = _value == null ? null : _value.toString();"); } } } /** * Writes the setter and getter methods */ protected void writeAccessMethods() { int j = 0; // Define getters and setters for the bean elements for (int i = 0; i < names.size(); i += 2, j++) { String typeName = (String) names.get(i); String name = (String) names.get(i + 1); String capName = Utils.capitalizeFirstChar(name); String documentation = ""; if (elements != null) { if (elements != null && i < (elements.size()*2)) { ElementDecl elem = (ElementDecl)elements.get(i/2); documentation = elem.getDocumentation(); } } String get = "get"; if (typeName.equals("boolean")) { get = "is"; } String comment = getJavadocDescriptionPart(documentation, true); if (comment.length() > 3) { // remove the " *" at the front of the first line comment = comment.substring(2); } if (enableGetters) { try { pw.println(); pw.println(" /**"); pw.println(" * Gets the " + name + " value for this " + getClassName() + "."); pw.println(" * "); pw.println(" * @return " + name + comment); pw.println(" */"); } catch (DOMException e) { // no comment } pw.println(" public " + typeName + " " + get + capName + "() {"); if (isUnion()) { writeSimpleTypeGetter(typeName, name, "return"); } else { pw.println(" return " + name + ";"); } pw.println(" }"); pw.println(); } if (enableSetters) { try { String nm = (isUnion()) ? "_value" : name; pw.println(); pw.println(" /**"); pw.println(" * Sets the " + nm + " value for this " + getClassName() + "."); pw.println(" * "); pw.println(" * @param " + nm + comment); pw.println(" */"); } catch (DOMException e) { // no comment } if (isUnion()) { pw.println(" public void set" + capName + "(" + typeName + " _value) {"); writeSimpleTypeSetter(typeName); } else { pw.println(" public void set" + capName + "(" + typeName + " " + name + ") {"); pw.println(" this." + name + " = " + name + ";"); } pw.println(" }"); pw.println(); } // If this is a special collection type, insert extra // java code so that the serializer/deserializer can recognize // the class. This is not JAX-RPC, and will be replaced with // compliant code when JAX-RPC determines how to deal with this case. // These signatures comply with Bean Indexed Properties which seems // like the reasonable approach to take for collection types. // (It may be more efficient to handle this with an ArrayList...but // for the initial support it was easier to use an actual array.) if ((elements != null) && (j < elements.size())) { ElementDecl elem = (ElementDecl) elements.get(j); if (elem.getType().getQName().getLocalPart().indexOf("[") > 0) { String compName = typeName.substring(0, typeName.lastIndexOf("[")); if (enableGetters) { pw.println(" public " + compName + " " + get + capName + "(int i) {"); pw.println(" return this." + name + "[i];"); pw.println(" }"); pw.println(); } if (enableSetters) { pw.println(" public void set" + capName + "(int i, " + compName + " _value) {"); // According to the section 7.2 of the JavaBeans // specification, the indexed setter should not // establish or grow the array. Thus the following // code is not generated for compliance purposes. /* * int bracketIndex = typeName.indexOf("["); * String newingName = typeName.substring(0, bracketIndex + 1); * String newingSuffix = typeName.substring(bracketIndex + 1); * * pw.println(" if (this." + name + " == null ||"); * pw.println(" this." + name + ".length <= i) {"); * pw.println(" " + typeName + " a = new " + * newingName + "i + 1" + newingSuffix + ";"); * pw.println(" if (this." + name + " != null) {"); * pw.println(" for(int j = 0; j < this." + name + * ".length; j++)"); * pw.println(" a[j] = this." + name + "[j];"); * pw.println(" }"); * pw.println(" this." + name + " = a;"); * pw.println(" }"); */ pw.println(" this." + name + "[i] = _value;"); pw.println(" }"); pw.println(); } } } } } /** * Writes a general purpose equals method */ protected void writeEqualsMethod() { // The __equalsCalc field and synchronized method are necessary // in case the object has direct or indirect references to itself. pw.println(" private java.lang.Object __equalsCalc = null;"); pw.println( " public synchronized boolean equals(java.lang.Object obj) {"); // First do the general comparison checks pw.println(" if (!(obj instanceof " + className + ")) return false;"); pw.println(" " + className + " other = (" + className + ") obj;"); pw.println(" if (this == obj) return true;"); // Have we been here before ? return true if yes otherwise false pw.println(" if (__equalsCalc != null) {"); pw.println(" return (__equalsCalc == obj);"); pw.println(" }"); pw.println(" __equalsCalc = obj;"); // Before checking the elements, check equality of the super class String truth = "true"; if ((extendType != null) && (!type.isSimpleType() || simpleValueTypes.size() == 0)) { truth = "super.equals(obj)"; } pw.println(" boolean _equals;"); if (names.size() == 0) { pw.println(" _equals = " + truth + ";"); } else if (isUnion()) { pw.println(" _equals = " + truth + " && " + " this.toString().equals(obj.toString());"); } else { pw.println(" _equals = " + truth + " && "); for (int i = 0; i < names.size(); i += 2) { String variableType = (String) names.get(i); String variable = (String) names.get(i + 1); String get = "get"; if (variableType.equals("boolean")) { get = "is"; } if (variableType.equals("int") || variableType.equals("long") || variableType.equals("short") || variableType.equals("float") || variableType.equals("double") || variableType.equals("boolean") || variableType.equals("byte")) { pw.print(" this." + variable + " == other." + get + Utils.capitalizeFirstChar(variable) + "()"); } else if (variableType.indexOf("[") >= 0) { // Use java.util.Arrays.equals to compare arrays. pw.println(" ((this." + variable + "==null && other." + get + Utils.capitalizeFirstChar(variable) + "()==null) || "); pw.println(" (this." + variable + "!=null &&"); pw.print(" java.util.Arrays.equals(this." + variable + ", other." + get + Utils.capitalizeFirstChar(variable) + "())))"); } else { pw.println(" ((this." + variable + "==null && other." + get + Utils.capitalizeFirstChar(variable) + "()==null) || "); pw.println(" (this." + variable + "!=null &&"); pw.print(" this." + variable + ".equals(other." + get + Utils.capitalizeFirstChar(variable) + "())))"); } if (i == (names.size() - 2)) { pw.println(";"); } else { pw.println(" &&"); } } } pw.println(" __equalsCalc = null;"); pw.println(" return _equals;"); pw.println(" }"); pw.println(""); } /** * Writes a general purpose hashCode method. */ protected void writeHashCodeMethod() { // The __hashCodeCalc field and synchronized method are necessary // in case the object has direct or indirect references to itself. pw.println(" private boolean __hashCodeCalc = false;"); pw.println(" public synchronized int hashCode() {"); pw.println(" if (__hashCodeCalc) {"); pw.println(" return 0;"); pw.println(" }"); pw.println(" __hashCodeCalc = true;"); // Get the hashCode of the super class String start = "1"; if ((extendType != null) && !type.isSimpleType()) { start = "super.hashCode()"; } pw.println(" int _hashCode = " + start + ";"); if (isUnion()) { pw.println(" if (this._value != null) {"); pw.println(" _hashCode += this._value.hashCode();"); pw.println(" }"); } for (int i = 0; !isUnion() && (i < names.size()); i += 2) { String variableType = (String) names.get(i); String variable = (String) names.get(i + 1); String get = "get"; if (variableType.equals("boolean")) { get = "is"; } if (variableType.equals("int") || variableType.equals("short") || variableType.equals("byte")) { pw.println(" _hashCode += " + get + Utils.capitalizeFirstChar(variable) + "();"); } else if (variableType.equals("boolean")) { pw.println(" _hashCode += (" + get + Utils.capitalizeFirstChar(variable) + "() ? Boolean.TRUE : Boolean.FALSE).hashCode();"); } else if (variableType.equals("long")) { pw.println(" _hashCode += new Long(" + get + Utils.capitalizeFirstChar(variable) + "()).hashCode();"); } else if (variableType.equals("float")) { pw.println(" _hashCode += new Float(" + get + Utils.capitalizeFirstChar(variable) + "()).hashCode();"); } else if (variableType.equals("double")) { pw.println(" _hashCode += new Double(" + get + Utils.capitalizeFirstChar(variable) + "()).hashCode();"); } else if (variableType.indexOf("[") >= 0) { // The hashCode calculation for arrays is complicated. // Wish there was a hashCode method in java.utils.Arrays ! // Get the hashCode for each element of the array which is not an array. pw.println(" if (" + get + Utils.capitalizeFirstChar(variable) + "() != null) {"); pw.println(" for (int i=0;"); pw.println( " i<java.lang.reflect.Array.getLength(" + get + Utils.capitalizeFirstChar(variable) + "());"); pw.println(" i++) {"); pw.println( " java.lang.Object obj = java.lang.reflect.Array.get(" + get + Utils.capitalizeFirstChar(variable) + "(), i);"); pw.println(" if (obj != null &&"); pw.println(" !obj.getClass().isArray()) {"); pw.println(" _hashCode += obj.hashCode();"); pw.println(" }"); pw.println(" }"); pw.println(" }"); } else { pw.println(" if (" + get + Utils.capitalizeFirstChar(variable) + "() != null) {"); pw.println(" _hashCode += " + get + Utils.capitalizeFirstChar(variable) + "().hashCode();"); pw.println(" }"); } } // Reset the __hashCodeCalc variable and return pw.println(" __hashCodeCalc = false;"); pw.println(" return _hashCode;"); pw.println(" }"); pw.println(""); } /** Generate a java source file and/or helper source file. * If the emitter works in deploy mode and the class already exists, only the helper is generated. * Otherwise, the java bean and helper source are generated. */ public void generate() throws IOException { String fqcn = getPackage() + "." + getClassName(); if (emitter.isDeploy() && emitter.doesExist(fqcn)) { if (emitter.isHelperWanted()) { helper.generate(); } } else { super.generate(); } } } // class JavaBeanWriter
6,868
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaClassWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.Version; import org.apache.axis.utils.Messages; import java.io.File; import java.io.IOException; import java.io.PrintWriter; /** * Emitter knows about WSDL writers, one each for PortType, Binding, Service, * Definition, Type. But for some of these WSDL types, Wsdl2java generates * multiple files. Each of these files has a corresponding writer that extends * JavaWriter. So the Java WSDL writers (JavaPortTypeWriter, JavaBindingWriter, * etc.) each calls a file writer (JavaStubWriter, JavaSkelWriter, etc.) for * each file that that WSDL generates. * <p>For example, when Emitter calls JavaWriterFactory for a Binding Writer, it * returns a JavaBindingWriter. JavaBindingWriter, in turn, contains a * JavaStubWriter, JavaSkelWriter, and JavaImplWriter since a Binding may cause * a stub, skeleton, and impl template to be generated. * <p>Note that the writers that are given to Emitter by JavaWriterFactory DO NOT * extend JavaWriter. They simply implement Writer and delegate the actual * task of writing to extensions of JavaWriter. * <p>All of Wsdl2java's Writer implementations follow a common behaviour. * JavaWriter is the abstract base class that dictates this common behaviour. * Many of the files generated are .java files, so this abstract class - * JavaClassWriter - exists. It extends JavaWriter and adds a bit of Java- * relative behaviour. This behaviour is primarily placed within the generate * method. The generate method calls, in succession (note: the starred methods * are the ones you are probably most interested in): * <dl> * <dt> getFileName * <dd> This method is abstract in JavaWriter, but JavaClassWriter implements * this method. Subclasses should have no need to override it. It * returns the fully-qualified file name based on the fully-qualified * classname + ".java". * <dt> isFileGenerated(file) * <dd> You should not need to override this method. It checks to see whether * this file is in the List returned by emitter.getGeneratedFileNames. * <dt> registerFile(file) * <dd> You should not need to override this method. It registers this file by * calling emitter.getGeneratedFileInfo().add(...). * <dt> * verboseMessage(file) * <dd> You may override this method if you want to provide more information. * The generate method only calls verboseMessage if verbose is turned on. * <dt> getPrintWriter(file) * <dd> You should not need to override this method. Given the file name, it * creates a PrintWriter for it. * <dt> writeFileHeader(pw) * <dd> JavaClassWriter implements this method, so you should not need to * override it. This method generates a javadoc giving the filename and * a comment stating that this file is generated by WSDL2Java, and it * generates the class definition including the opening curly brace.. * <dt> * writeFileBody(pw) * <dd> This is an abstract method that must be implemented by the subclass. * This is where the body of a file is generated. * <dt> * writeFileFooter(pw) * <dd> JavaClassWriter implements this method, so you should not need to * override it. It generates the closing curly brace for the class. * <dt> closePrintWriter(pw) * <dd> You should not need to override this method. It simply closes the * PrintWriter. * </dl> * <p> * Additional behaviour that JavaClassWriter introduces beyond JavaWriter is * related to the class header and definition: * <dl> * <dt> writeHeaderComments * <dd> Write the header comments, such as the file name and that the file was * generated by WSDL2Java. You need not override this method unless you * want a tailored comment. * <dt> writePackage * <dd> Write the package statement, if necessary. You should not need to * override this method. * <dt> getClassModifiers * <dd> Modifiers, such as "public", "final", "abstract" would be returned by * this method. The default implementation only generates "public ", so * any subclass that needs more must override this method. * <dt> getClassText * <dd> This simply returns "class ". If anything else is desired, for * instance, JavaInterfaceWriter prefers "interface ", then this method * must be overridden. * <dt> getExtendsText * <dd> The default implementation returns "". If a subclass desires to list * a set of classes this one extends, then this method must be overridden. * <dt> getImplementsText * <dd> Same as getExtendsText except for the implements clause. * </dl> */ public abstract class JavaClassWriter extends JavaWriter { /** Field namespaces */ protected Namespaces namespaces; /** Field className */ protected String className; /** Field packageName */ protected String packageName; /** * Constructor. * * @param emitter The emitter instance * @param fullClassName The fully qualified class name of the class * to be generated. * @param type */ protected JavaClassWriter(Emitter emitter, String fullClassName, String type) { super(emitter, type); this.namespaces = emitter.getNamespaces(); this.packageName = Utils.getJavaPackageName(fullClassName); this.className = Utils.getJavaLocalName(fullClassName); } // ctor /** * Return the file name as a string of the form: * "&lt;directory-ized fully-qualified classname&gt;.java" * * @return */ protected String getFileName() { return namespaces.toDir(packageName) + className + ".java"; } // getFileName /** * You should not need to override this method. * It registers the given file by calling * emitter.getGeneratedFileInfo().add(...). * JavaClassWriter overrides this method from JavaWriter because * it add class name to the registration information. * * @param file */ protected void registerFile(String file) { final String pkg = getPackage(); String fqClass; if (pkg != null && pkg.length() > 0) { fqClass = pkg + '.' + getClassName(); } else { fqClass = getClassName(); } emitter.getGeneratedFileInfo().add(file, fqClass, type); } // registerFile /** * Write a common header, including the package name, the class * declaration, and the opening curly brace. * * @param pw * @throws IOException */ protected void writeFileHeader(PrintWriter pw) throws IOException { writeHeaderComments(pw); writePackage(pw); // print class declaration pw.println(getClassModifiers() + getClassText() + getClassName() + ' ' + getExtendsText() + getImplementsText() + "{"); } // writeFileHeader /** * Write the header comments. * * @param pw * @throws IOException */ protected void writeHeaderComments(PrintWriter pw) throws IOException { String localFile = getFileName(); int lastSepChar = localFile.lastIndexOf(File.separatorChar); if (lastSepChar >= 0) { localFile = localFile.substring(lastSepChar + 1); } pw.println("/**"); pw.println(" * " + localFile); pw.println(" *"); pw.println(" * " + Messages.getMessage("wsdlGenLine00")); pw.println(" * " + Messages.getMessage("wsdlGenLine01", Version.getVersionText())); pw.println(" */"); pw.println(); } // writeHeaderComments /** * Write the package declaration statement. * * @param pw * @throws IOException */ protected void writePackage(PrintWriter pw) throws IOException { final String pkg = getPackage(); if (pkg != null && pkg.length() > 0) { pw.println("package " + pkg + ";"); pw.println(); } } // writePackage /** * Return "public ". If more modifiers are needed, this method must be * overridden. * * @return */ protected String getClassModifiers() { return "public "; } // getClassModifiers /** * Return "class ". If "interface " is needed instead, this method must be * overridden. * * @return */ protected String getClassText() { return "class "; } // getClassString /** * Returns the appropriate extends clause. This default implementation * simply returns "", but if you want "extends &lt;class/interface list&gt; " * then you must override this method. * * @return "" */ protected String getExtendsText() { return ""; } // getExtendsText /** * Returns the appropriate implements clause. This default implementation * simply returns "", but if you want "implements &lt;interface list&gt; " then * you must override this method. * * @return "" */ protected String getImplementsText() { return ""; } // getImplementsText /** * Returns the package name. * * @return */ protected String getPackage() { return packageName; } // getPackage /** * Returns the class name. * * @return */ protected String getClassName() { return className; } // getClassName /** * Generate the closing curly brace. * * @param pw * @throws IOException */ protected void writeFileFooter(PrintWriter pw) throws IOException { super.writeFileFooter(pw); pw.println('}'); } // writeFileFooter } // abstract class JavaClassWriter
6,869
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaFaultWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.constants.Use; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Message; import java.io.IOException; import java.io.PrintWriter; import java.util.Vector; /** * This is Wsdl2java's Fault Writer. It writes the &lt;faultName&gt;.java file. * <p> * NOTE: This only writes simple type faults, the JavaTypeWriter emits * faults that are complex types. */ public class JavaFaultWriter extends JavaClassWriter { /** Field faultMessage */ private Message faultMessage; /** Field symbolTable */ private SymbolTable symbolTable; /** Field literal */ private boolean literal; /** Field faultName */ private String faultName; /** * Constructor. * * @param emitter * @param symbolTable * @param faultInfo */ protected JavaFaultWriter(Emitter emitter, SymbolTable symbolTable, FaultInfo faultInfo) { super(emitter, Utils.getFullExceptionName(faultInfo.getMessage(), symbolTable), "fault"); this.literal = faultInfo.getUse().equals(Use.LITERAL); this.faultMessage = faultInfo.getMessage(); this.symbolTable = symbolTable; this.faultName = faultInfo.getName(); } // ctor /** * Return "extends org.apache.axis.AxisFault ". * * @return */ protected String getExtendsText() { return "extends org.apache.axis.AxisFault "; } // getExtendsText /** * Write the body of the Fault file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { Vector params = new Vector(); symbolTable.getParametersFromParts(params, faultMessage.getOrderedParts(null), literal, faultName, null); // Write data members of the exception and getter methods for them for (int i = 0; i < params.size(); i++) { Parameter param = (Parameter) params.get(i); String type = param.getType().getName(); String variable = JavaUtils.xmlNameToJava(param.getName()); pw.println(" public " + type + " " + variable + ";"); pw.println(" public " + type + " get" + Utils.capitalizeFirstChar(variable) + "() {"); pw.println(" return this." + variable + ";"); pw.println(" }"); } // Default contructor pw.println(); pw.println(" public " + className + "() {"); pw.println(" }"); pw.println(); // Additional contructors pw.println(" public " + className + "(java.lang.Exception target) {"); pw.println(" super(target);"); pw.println(" }"); pw.println(); pw.println(" public " + className + "(java.lang.String message, java.lang.Throwable t) {"); pw.println(" super(message, t);"); pw.println(" }"); pw.println(); // contructor that initializes data if (params.size() > 0) { pw.print(" public " + className + "("); for (int i = 0; i < params.size(); i++) { if (i != 0) { pw.print(", "); } Parameter param = (Parameter) params.get(i); String type = param.getType().getName(); String variable = JavaUtils.xmlNameToJava(param.getName()); pw.print(type + " " + variable); } pw.println(") {"); for (int i = 0; i < params.size(); i++) { Parameter param = (Parameter) params.get(i); String variable = JavaUtils.xmlNameToJava(param.getName()); pw.println(" this." + variable + " = " + variable + ";"); } pw.println(" }"); } // Method that serializes exception data (writeDetail) // The QName of the element is passed in by the runtime and is found // via the fault meta-data in the WSDD. // NOTE: This function is also written in JavaBeanFaultWriter.java pw.println(); pw.println(" /**"); pw.println(" * Writes the exception data to the faultDetails"); pw.println(" */"); pw.println( " public void writeDetails(javax.xml.namespace.QName qname, org.apache.axis.encoding.SerializationContext context) throws java.io.IOException {"); for (int i = 0; i < params.size(); i++) { Parameter param = (Parameter) params.get(i); String variable = JavaUtils.xmlNameToJava(param.getName()); pw.println(" context.serialize(qname, null, " + Utils.wrapPrimitiveType(param.getType(), variable) + ");"); } pw.println(" }"); } // writeFileBody } // class JavaFaultWriter
6,870
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBindingWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Binding; import java.io.IOException; /** * This is Wsdl2java's Binding Writer. It writes the following files, as appropriate: * &lt;bindingName&gt;Stub.java, &lt;bindingName&gt;Skeleton.java, &lt;bindingName&gt;Impl.java. */ public class JavaBindingWriter implements Generator { /** Field stubWriter */ protected Generator stubWriter = null; /** Field skelWriter */ protected Generator skelWriter = null; /** Field implWriter */ protected Generator implWriter = null; /** Field interfaceWriter */ protected Generator interfaceWriter = null; /** Field emitter */ protected Emitter emitter; /** Field binding */ protected Binding binding; /** Field symbolTable */ protected SymbolTable symbolTable; // This is the dynamic var key for the SEI (Service Endpoint // Interface) name. This name could either be derived from // the portType or the binding. The generatorPass fills // this dynamic var in and it is used in the writers that // need this SEI name. /** Field INTERFACE_NAME */ public static String INTERFACE_NAME = "interface name"; /** * Constructor. * * @param emitter * @param binding * @param symbolTable */ public JavaBindingWriter(Emitter emitter, Binding binding, SymbolTable symbolTable) { this.emitter = emitter; this.binding = binding; this.symbolTable = symbolTable; } // ctor /** * getJavaInterfaceWriter * * @param emitter * @param ptEntry * @param bEntry * @param st * @return */ protected Generator getJavaInterfaceWriter(Emitter emitter, PortTypeEntry ptEntry, BindingEntry bEntry, SymbolTable st) { return new JavaInterfaceWriter(emitter, ptEntry, bEntry, st); } /** * getJavaStubWriter * * @param emitter * @param bEntry * @param st * @return */ protected Generator getJavaStubWriter(Emitter emitter, BindingEntry bEntry, SymbolTable st) { return new JavaStubWriter(emitter, bEntry, st); } /** * getJavaSkelWriter * * @param emitter * @param bEntry * @param st * @return */ protected Generator getJavaSkelWriter(Emitter emitter, BindingEntry bEntry, SymbolTable st) { return new JavaSkelWriter(emitter, bEntry, st); } /** * getJavaImplWriter * * @param emitter * @param bEntry * @param st * @return */ protected Generator getJavaImplWriter(Emitter emitter, BindingEntry bEntry, SymbolTable st) { return new JavaImplWriter(emitter, bEntry, st); } /** * Write all the binding bindings: stub, skeleton, and impl. * * @throws IOException */ public void generate() throws IOException { setGenerators(); postSetGenerators(); if (interfaceWriter != null) { interfaceWriter.generate(); } if (stubWriter != null) { stubWriter.generate(); } if (skelWriter != null) { skelWriter.generate(); } if (implWriter != null) { implWriter.generate(); } } // generate /** * setGenerators * Logic to set the generators that are based on the Binding * This logic was moved from the constructor so extended interfaces * can more effectively use the hooks. */ protected void setGenerators() { BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); // Interface writer PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(binding.getPortType().getQName()); if (ptEntry.isReferenced()) { interfaceWriter = getJavaInterfaceWriter(emitter, ptEntry, bEntry, symbolTable); } if (bEntry.isReferenced()) { // Stub writer stubWriter = getJavaStubWriter(emitter, bEntry, symbolTable); // Skeleton and Impl writers if (emitter.isServerSide()) { if (emitter.isSkeletonWanted()) { skelWriter = getJavaSkelWriter(emitter, bEntry, symbolTable); } // Use custom implementation classname if available String fileName = emitter.getImplementationClassName(); if ( fileName == null) fileName = Utils.getJavaLocalName(bEntry.getName()) + "Impl.java"; else fileName = Utils.getJavaLocalName(fileName) + ".java"; try { if (Utils.fileExists(fileName, binding.getQName().getNamespaceURI(), emitter.getNamespaces())) { if (!emitter.isQuiet()) { System.out.println( Messages.getMessage("wontOverwrite", fileName)); } } else { implWriter = getJavaImplWriter(emitter, bEntry, symbolTable); } } catch (IOException ioe) { System.err.println(Messages.getMessage("fileExistError00", fileName)); } } } } /** * Set the writer based on the other condition after generate() is called. */ protected void postSetGenerators() { if (emitter.isDeploy()) { interfaceWriter = null; stubWriter = null; skelWriter = null; implWriter = null; } } } // class JavaBindingWriter
6,871
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/NamespaceSelector.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.wsdl.toJava; /** This class is used within the context of a FactorySpec to express namespaces that should be either included and/or excluded from source code generation. The ability to include/exclude specific namespaces from wsdl2java generation allows certain namespaces to be mapped to custom bean classes, have wsdl-generated stubs/skeletons declared to pass those types, and not have the wsdl2java process generate classes which would conflict with the externally developed custom beans. @author Jim Stafford (jim.stafford@raba.com) */ public class NamespaceSelector { private String namespace_ = ""; public NamespaceSelector() {} public NamespaceSelector(String namespace) { namespace_ = namespace; } public void setNamespace(String value) { namespace_ = value; } public String getNamespace() { return namespace_; } public String toString() { if (namespace_ != null) { return "namespace=" + namespace_; } else { return ""; } } public boolean equals(Object value) { boolean isEqual = false; if (value == null) { isEqual = false; } else if (value instanceof String) { isEqual = ((String)value).equals(namespace_); } else if (value instanceof NamespaceSelector) { isEqual = ((NamespaceSelector)value).namespace_.equals(namespace_); } return isEqual; } }
6,872
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaDefinitionWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.MessageEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Import; import javax.wsdl.Message; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * This is Wsdl2java's Definition Writer. * It currently writes the following files: * Faults as needed. */ public class JavaDefinitionWriter implements Generator { /** Field emitter */ protected Emitter emitter; /** Field definition */ protected Definition definition; /** Field symbolTable */ protected SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param definition * @param symbolTable */ public JavaDefinitionWriter(Emitter emitter, Definition definition, SymbolTable symbolTable) { this.emitter = emitter; this.definition = definition; this.symbolTable = symbolTable; } // ctor /** * Write other items from the definition as needed. * * @throws IOException */ public void generate() throws IOException { writeFaults(); } // generate /** * Write all the simple type faults. * The complexType Faults are automatically handled by JavaTypeWriter. * The fault name is derived from the fault message name per JAX-RPC * * @throws IOException */ protected void writeFaults() throws IOException { ArrayList faults = new ArrayList(); collectFaults(definition, faults); // Fault classes we're actually writing (for dup checking) HashSet generatedFaults = new HashSet(); // iterate over fault list, emitting code. Iterator fi = faults.iterator(); while (fi.hasNext()) { FaultInfo faultInfo = (FaultInfo) fi.next(); Message message = faultInfo.getMessage(); String name = Utils.getFullExceptionName(message, symbolTable); if (generatedFaults.contains(name)) { continue; } generatedFaults.add(name); // Generate the 'Simple' Faults. // The complexType Faults are automatically handled // by JavaTypeWriter. MessageEntry me = symbolTable.getMessageEntry(message.getQName()); if (me == null || !Utils.isFaultComplex(me)) { try { JavaFaultWriter writer = new JavaFaultWriter(emitter, symbolTable, faultInfo); // Go write the file writer.generate(); } catch (DuplicateFileException dfe) { System.err.println(Messages.getMessage("fileExistError00", dfe.getFileName())); } } } } // writeFaults /** Collect all of the faults used in this definition. */ private HashSet importedFiles = new HashSet(); /** * Method collectFaults * * @param def * @param faults * @throws IOException */ private void collectFaults(Definition def, ArrayList faults) throws IOException { Map imports = def.getImports(); Object[] importValues = imports.values().toArray(); for (int i = 0; i < importValues.length; ++i) { Vector v = (Vector) importValues[i]; for (int j = 0; j < v.size(); ++j) { Import imp = (Import) v.get(j); if (!importedFiles.contains(imp.getLocationURI())) { importedFiles.add(imp.getLocationURI()); Definition importDef = imp.getDefinition(); if (importDef != null) { collectFaults(importDef, faults); } } } } // Traverse the bindings to find faults Map bindings = def.getBindings(); Iterator bindi = bindings.values().iterator(); while (bindi.hasNext()) { Binding binding = (Binding) bindi.next(); BindingEntry entry = symbolTable.getBindingEntry(binding.getQName()); if (entry.isReferenced()) { // use the map of bindingOperation -> fault info // created in SymbolTable Map faultMap = entry.getFaults(); Iterator it = faultMap.values().iterator(); while (it.hasNext()) { ArrayList list = (ArrayList) it.next(); // Accumulate total list of faults faults.addAll(list); } } } } // collectFaults } // class JavaDefinitionWriter
6,873
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaInterfaceWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Operation; import javax.wsdl.PortType; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; /** * This is Wsdl2java's PortType Writer. It writes the &lt;portTypeName&gt;.java file * which contains the &lt;portTypeName&gt; interface. */ public class JavaInterfaceWriter extends JavaClassWriter { /** Field portType */ protected PortType portType; /** Field bEntry */ protected BindingEntry bEntry; /** * Constructor. * * @param emitter * @param ptEntry * @param bEntry * @param symbolTable */ protected JavaInterfaceWriter(Emitter emitter, PortTypeEntry ptEntry, BindingEntry bEntry, SymbolTable symbolTable) { super(emitter, (String) bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME), "interface"); this.portType = ptEntry.getPortType(); this.bEntry = bEntry; } // ctor /** * Override generate method to prevent duplicate interfaces because * of two bindings referencing the same portType * * @throws IOException */ public void generate() throws IOException { String fqClass = getPackage() + "." + getClassName(); // Do not emit the same portType/interface twice if (!emitter.getGeneratedFileInfo().getClassNames().contains(fqClass)) { super.generate(); } } // generate /** * Returns "interface ". * * @return */ protected String getClassText() { return "interface "; } // getClassString /** * Returns "extends java.rmi.Remote ". * * @return */ protected String getExtendsText() { return "extends java.rmi.Remote "; } // getExtendsText /** * Write the body of the portType interface file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { Iterator operations = portType.getOperations().iterator(); while (operations.hasNext()) { Operation operation = (Operation) operations.next(); writeOperation(pw, operation); } } // writeFileBody /** * This method generates the interface signatures for the given operation. * * @param pw * @param operation * @throws IOException */ protected void writeOperation(PrintWriter pw, Operation operation) throws IOException { writeComment(pw, operation.getDocumentationElement(), true); Parameters parms = bEntry.getParameters(operation); pw.println(parms.signature + ";"); } // writeOperation } // class JavaInterfaceWriter
6,874
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/Utils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.symbolTable.*; import org.apache.commons.logging.Log; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.wsdl.BindingOperation; import javax.wsdl.Message; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.soap.SOAPOperation; import javax.wsdl.extensions.soap12.SOAP12Operation; import javax.xml.namespace.QName; import javax.xml.rpc.holders.BooleanHolder; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; /** * Class Utils * * @version %I%, %G% */ public class Utils extends org.apache.axis.wsdl.symbolTable.Utils { /** Field log */ protected static Log log = LogFactory.getLog(Utils.class.getName()); /** * @see #holder(Parameter, Emitter) */ public static String holder(TypeEntry type, Emitter emitter) { Parameter arg = new Parameter(); // For other fields the default values will do. arg.setType(type); return holder(arg, emitter); } /** * Given a type, return the Java mapping of that type's holder. * * @param p parameter whose holder class name we want to obtain. * @param emitter the only {@link Emitter} object embodying the running * instance of WSDL2Java. * @return the name of the holder class for <tt>p</tt>. */ public static String holder(Parameter p, Emitter emitter) { String mimeType = (p.getMIMEInfo() == null) ? null : p.getMIMEInfo().getType(); String mimeDimensions = (mimeType == null) ? "" : p.getMIMEInfo().getDimensions(); // Add the holders that JAX-RPC forgot about - the MIME type holders. if (mimeType != null) { if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) { return "org.apache.axis.holders.ImageHolder" + mimeDimensions; } else if (mimeType.equals("text/plain")) { return "javax.xml.rpc.holders.StringHolder" + mimeDimensions; } else if (mimeType.startsWith("multipart/")) { return "org.apache.axis.holders.MimeMultipartHolder" + mimeDimensions; } else if (mimeType.startsWith("application/octetstream") || mimeType.startsWith("application/octet-stream")) { return "org.apache.axis.holders.OctetStreamHolder" + mimeDimensions; } else if (mimeType.equals("text/xml") || mimeType.equals("application/xml")) { return "org.apache.axis.holders.SourceHolder" + mimeDimensions; } else { return "org.apache.axis.holders.DataHandlerHolder" + mimeDimensions; } } TypeEntry type = p.getType(); String typeValue = type.getName(); // For base types that are nillable and are mapped to primitives, // need to switch to the corresponding wrapper types. if ((p.isOmittable() && p.getType().getDimensions().equals("")) || (p.getType() instanceof CollectionType && ((CollectionType) p.getType()).isWrapped()) || p.getType().getUnderlTypeNillable()) { typeValue = getWrapperType(type); } // byte[] has a reserved holders. if (typeValue.equals("byte[]") && type.isBaseType()) { return "javax.xml.rpc.holders.ByteArrayHolder"; } // Anything else with [] gets its holder from the qname else if (typeValue.endsWith("[]")) { String name = emitter.getJavaName(type.getQName()); String packagePrefix = ""; // Make sure that holders for arrays of either primitive Java types // or their wrappers are generated at a predictable location. if ((type instanceof CollectionType) && (type.getRefType() instanceof BaseType)) { String uri = type.getRefType().getQName().getNamespaceURI(); // Capitalize the first character for primitive type // array holder classes if (TYPES.get(JavaUtils.replace(name,"[]","")) != null) { name = capitalizeFirstChar(name); } // For wrapped primitive array holder classes append 'Wrapper' to name if (((CollectionType) type).isWrapped() && !typeValue.equals(type.getName())) { name = name + "Wrapper"; } packagePrefix = emitter.getNamespaces().getCreate(uri, false); if (packagePrefix == null) { packagePrefix = ""; } else { packagePrefix += '.'; } } name = JavaUtils.replace(name, "java.lang.", ""); // This could be a special QName for a indexed property. // If so, change the [] to Array. name = JavaUtils.replace(name, "[]", "Array"); name = addPackageName(name, "holders"); return packagePrefix + name + "Holder"; } // String also has a reserved holder else if (typeValue.equals("String")) { return "javax.xml.rpc.holders.StringHolder"; } else if (typeValue.equals("java.lang.String")) { return "javax.xml.rpc.holders.StringHolder"; } // Object also has a reserved holder else if (typeValue.equals("Object")) { return "javax.xml.rpc.holders.ObjectHolder"; } else if (typeValue.equals("java.lang.Object")) { return "javax.xml.rpc.holders.ObjectHolder"; } // Java primitive types have reserved holders else if (typeValue.equals("int") || typeValue.equals("long") || typeValue.equals("short") || typeValue.equals("float") || typeValue.equals("double") || typeValue.equals("boolean") || typeValue.equals("byte")) { return "javax.xml.rpc.holders." + capitalizeFirstChar(typeValue) + "Holder"; } // Java language classes have reserved holders (with ClassHolder) else if (typeValue.startsWith("java.lang.")) { return "javax.xml.rpc.holders" + typeValue.substring(typeValue.lastIndexOf(".")) + "WrapperHolder"; } else if (typeValue.indexOf(".") < 0) { return "javax.xml.rpc.holders" + typeValue + "WrapperHolder"; } // The classes have reserved holders because they // represent schema/soap encoding primitives else if (typeValue.equals("java.math.BigDecimal")) { return "javax.xml.rpc.holders.BigDecimalHolder"; } else if (typeValue.equals("java.math.BigInteger")) { return "javax.xml.rpc.holders.BigIntegerHolder"; } else if (typeValue.equals("java.util.Date")) { return "org.apache.axis.holders.DateHolder"; } else if (typeValue.equals("java.util.Calendar")) { return "javax.xml.rpc.holders.CalendarHolder"; } else if (typeValue.equals("javax.xml.namespace.QName")) { return "javax.xml.rpc.holders.QNameHolder"; } else if (typeValue.equals("javax.activation.DataHandler")) { return "org.apache.axis.holders.DataHandlerHolder"; } // Check for Axis specific types and return their holders else if (typeValue.startsWith("org.apache.axis.types.")) { int i = typeValue.lastIndexOf('.'); String t = typeValue.substring(i + 1); return "org.apache.axis.holders." + t + "Holder"; } // For everything else add "holders" package and append // holder to the class name. else { return addPackageName(typeValue, "holders") + "Holder"; } } // holder /** * Add package to name * * @param className full name of the class. * @param newPkg name of the package to append * @return String name with package name added */ public static String addPackageName(String className, String newPkg) { int index = className.lastIndexOf("."); if (index >= 0) { return className.substring(0, index) + "." + newPkg + className.substring(index); } else { return newPkg + "." + className; } } /** * Given a fault message, return the fully qualified Java class name * of the exception to be generated from this fault * * @param faultMessage The WSDL fault message * @param symbolTable the current symbol table * @return A Java class name for the fault */ public static String getFullExceptionName(Message faultMessage, SymbolTable symbolTable) { MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName()); return (String) me.getDynamicVar( JavaGeneratorFactory.EXCEPTION_CLASS_NAME); } // getFullExceptionName /** * Given a fault message, return the XML type of the exception data. * * @param faultMessage The WSDL fault message object * @param symbolTable the current symbol table * @return A QName for the XML type of the data */ public static QName getFaultDataType(Message faultMessage, SymbolTable symbolTable) { MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName()); return (QName) me.getDynamicVar( JavaGeneratorFactory.EXCEPTION_DATA_TYPE); } // getFaultDataType /** * Given a fault message, return TRUE if the fault is a complex type fault * * @param faultMessage The WSDL fault message object * @param symbolTable the current symbol table * @return A Java class name for the fault */ public static boolean isFaultComplex(Message faultMessage, SymbolTable symbolTable) { return isFaultComplex(symbolTable.getMessageEntry(faultMessage.getQName())); } // isFaultComplex static boolean isFaultComplex(SymTabEntry entry) { Boolean value = (Boolean) entry.getDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT); return value != null && value.booleanValue(); } /** * If the specified node represents a supported JAX-RPC enumeration, * a Vector is returned which contains the base type and the enumeration values. * The first element in the vector is the base type (an TypeEntry). * Subsequent elements are values (Strings). * If this is not an enumeration, null is returned. * * @param node * @param symbolTable * @return */ public static Vector getEnumerationBaseAndValues(Node node, SymbolTable symbolTable) { if (node == null) { return null; } // If the node kind is an element, dive into it. QName nodeKind = Utils.getNodeQName(node); if ((nodeKind != null) && nodeKind.getLocalPart().equals("element") && Constants.isSchemaXSD(nodeKind.getNamespaceURI())) { NodeList children = node.getChildNodes(); Node simpleNode = null; for (int j = 0; (j < children.getLength()) && (simpleNode == null); j++) { QName simpleKind = Utils.getNodeQName(children.item(j)); if ((simpleKind != null) && simpleKind.getLocalPart().equals("simpleType") && Constants.isSchemaXSD( simpleKind.getNamespaceURI())) { simpleNode = children.item(j); node = simpleNode; } } } // Get the node kind, expecting a schema simpleType nodeKind = Utils.getNodeQName(node); if ((nodeKind != null) && nodeKind.getLocalPart().equals("simpleType") && Constants.isSchemaXSD(nodeKind.getNamespaceURI())) { // Under the simpleType there should be a restriction. // (There may be other #text nodes, which we will ignore). NodeList children = node.getChildNodes(); Node restrictionNode = null; for (int j = 0; (j < children.getLength()) && (restrictionNode == null); j++) { QName restrictionKind = Utils.getNodeQName(children.item(j)); if ((restrictionKind != null) && restrictionKind.getLocalPart().equals("restriction") && Constants.isSchemaXSD( restrictionKind.getNamespaceURI())) { restrictionNode = children.item(j); } } // The restriction node indicates the type being restricted // (the base attribute contains this type). // The base type must be a simple type, and not boolean TypeEntry baseEType = null; if (restrictionNode != null) { QName baseType = Utils.getTypeQName(restrictionNode, new BooleanHolder(), false); baseEType = symbolTable.getType(baseType); if (baseEType != null) { String javaName = baseEType.getName(); if (javaName.equals("boolean") || !SchemaUtils.isSimpleSchemaType( baseEType.getQName())) { baseEType = null; } } } // Process the enumeration elements underneath the restriction node if ((baseEType != null) && (restrictionNode != null)) { Vector v = new Vector(); NodeList enums = restrictionNode.getChildNodes(); for (int i = 0; i < enums.getLength(); i++) { QName enumKind = Utils.getNodeQName(enums.item(i)); if ((enumKind != null) && enumKind.getLocalPart().equals("enumeration") && Constants.isSchemaXSD( enumKind.getNamespaceURI())) { // Put the enum value in the vector. Node enumNode = enums.item(i); String value = Utils.getAttribute(enumNode, "value"); if (value != null) { v.add(value); } } } // is this really an enumeration? if (v.isEmpty()) { return null; } // The first element in the vector is the base type (an TypeEntry). v.add(0, baseEType); return v; } } return null; } /** * Capitalize the first character of the name. * * @param name * @return */ public static String capitalizeFirstChar(String name) { if ((name == null) || name.equals("")) { return name; } char start = name.charAt(0); if (Character.isLowerCase(start)) { start = Character.toUpperCase(start); return start + name.substring(1); } return name; } // capitalizeFirstChar /** * Prepend an underscore to the name * * @param name * @return */ public static String addUnderscore(String name) { if ((name == null) || name.equals("")) { return name; } return "_" + name; } /** * @deprecated Use {@link JavaUtils#xmlNameToJava(String)} instead. */ public static String xmlNameToJava(String name) { return JavaUtils.xmlNameToJava(name); } /** * Map an XML name to a valid Java identifier w/ capitolized first letter * * @param name * @return */ public static String xmlNameToJavaClass(String name) { return capitalizeFirstChar(JavaUtils.xmlNameToJava(name)); } /** * Method makePackageName * * @param namespace * @return */ public static String makePackageName(String namespace) { String hostname = null; String path = ""; // get the target namespace of the document try { URL u = new URL(namespace); hostname = u.getHost(); path = u.getPath(); } catch (MalformedURLException e) { if (namespace.indexOf(":") > -1) { hostname = namespace.substring(namespace.indexOf(":") + 1); if (hostname.indexOf("/") > -1) { hostname = hostname.substring(0, hostname.indexOf("/")); } } else { hostname = namespace; } } // if we didn't file a hostname, bail if (hostname == null) { return null; } // convert illegal java identifier hostname = hostname.replace('-', '_'); path = path.replace('-', '_'); // chomp off last forward slash in path, if necessary if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) { path = path.substring(0, path.length() - 1); } // tokenize the hostname and reverse it StringTokenizer st = new StringTokenizer(hostname, ".:"); String[] words = new String[st.countTokens()]; for (int i = 0; i < words.length; ++i) { words[i] = st.nextToken(); } StringBuffer sb = new StringBuffer(namespace.length()); for (int i = words.length - 1; i >= 0; --i) { addWordToPackageBuffer(sb, words[i], (i == words.length - 1)); } // tokenize the path StringTokenizer st2 = new StringTokenizer(path, "/"); while (st2.hasMoreTokens()) { addWordToPackageBuffer(sb, st2.nextToken(), false); } return sb.toString(); } /** * Massage <tt>word</tt> into a form suitable for use in a Java package name. * Append it to the target string buffer with a <tt>.</tt> delimiter iff * <tt>word</tt> is not the first word in the package name. * * @param sb the buffer to append to * @param word the word to append * @param firstWord a flag indicating whether this is the first word */ private static void addWordToPackageBuffer(StringBuffer sb, String word, boolean firstWord) { if (JavaUtils.isJavaKeyword(word)) { word = JavaUtils.makeNonJavaKeyword(word); } // separate with dot after the first word if (!firstWord) { sb.append('.'); } // prefix digits with underscores if (Character.isDigit(word.charAt(0))) { sb.append('_'); } // replace periods with underscores if (word.indexOf('.') != -1) { char[] buf = word.toCharArray(); for (int i = 0; i < word.length(); i++) { if (buf[i] == '.') { buf[i] = '_'; } } word = new String(buf); } sb.append(word); } /** * Query Java Local Name * * @param fullName * @return */ public static String getJavaLocalName(String fullName) { return fullName.substring(fullName.lastIndexOf('.') + 1); } // getJavaLocalName /** * Query Java Package Name * * @param fullName * @return */ public static String getJavaPackageName(String fullName) { if (fullName.lastIndexOf('.') > 0) { return fullName.substring(0, fullName.lastIndexOf('.')); } else { return ""; } } // getJavaPackageName /** * Does the given file already exist in the given namespace? * * @param name * @param namespace * @param namespaces * @return * @throws IOException */ public static boolean fileExists( String name, String namespace, Namespaces namespaces) throws IOException { String packageName = namespaces.getAsDir(namespace); String fullName = packageName + name; return new File(fullName).exists(); } // fileExists /** * Return a string with "var" wrapped as an Object type if needed * * @param type * @param var * @return */ public static String wrapPrimitiveType(TypeEntry type, String var) { String objType = (type == null) ? null : (String) TYPES.get(type.getName()); if (objType != null) { return "new " + objType + "(" + var + ")"; } else if ((type != null) && type.getName().equals("byte[]") && type.getQName().getLocalPart().equals("hexBinary")) { // Need to wrap byte[] in special HexBinary object to get the correct serialization return "new org.apache.axis.types.HexBinary(" + var + ")"; } else { return var; } } // wrapPrimitiveType /** * Return the Object variable 'var' cast to the appropriate type * doing the right thing for the primitive types. * * @param var * @return */ public static String getResponseString(Parameter param, String var) { if (param.getType() == null) { return ";"; } String typeName = param.getType().getName(); MimeInfo mimeInfo = param.getMIMEInfo(); String mimeType = (mimeInfo == null) ? null : mimeInfo.getType(); String mimeDimensions = (mimeInfo == null) ? "" : mimeInfo.getDimensions(); if (mimeType != null) { if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) { return "(java.awt.Image" + mimeDimensions + ") " + var + ";"; } else if (mimeType.equals("text/plain")) { return "(java.lang.String" + mimeDimensions + ") " + var + ";"; } else if (mimeType.equals("text/xml") || mimeType.equals("application/xml")) { return "(javax.xml.transform.Source" + mimeDimensions + ") " + var + ";"; } else if (mimeType.startsWith("multipart/")) { return "(javax.mail.internet.MimeMultipart" + mimeDimensions + ") " + var + ";"; } else if (mimeType.startsWith("application/octetstream") || mimeType.startsWith("application/octet-stream")) { //the hyphenated test is new and RFC compliant; the old one was retained //for backwards compatibility. return "(org.apache.axis.attachments.OctetStream" + mimeDimensions + ") " + var + ";"; } else { return "(javax.activation.DataHandler" + mimeDimensions + ") " + var + ";"; } } // If minOccurs="0" and singular or array with nillable underlying // type get the corresponding wrapper type. if ((param.isOmittable() && param.getType().getDimensions().equals("")) || (param.getType() instanceof CollectionType && ((CollectionType) param.getType()).isWrapped()) || param.getType().getUnderlTypeNillable()) { typeName = getWrapperType(param.getType()); } String objType = (String) TYPES.get(typeName); if (objType != null) { return "((" + objType + ") " + var + ")." + typeName + "Value();"; } return "(" + typeName + ") " + var + ";"; } // getResponseString /** * Method isPrimitiveType * * @param type * @return */ public static boolean isPrimitiveType(TypeEntry type) { return TYPES.get(type.getName()) != null; } // isPrimitiveType /** * Returns a "wrapper" type for the given TypeEntry. * * @param type * @return the name of a java wrapper class for the type, or the type's * name if it's not a primitive. */ public static String getWrapperType(TypeEntry type) { String dims = type.getDimensions(); if (!dims.equals("")) { TypeEntry te = type.getRefType(); if (te != null && !te.getDimensions().equals("")) { return getWrapperType(te) + dims; } if (te instanceof BaseType || te instanceof DefinedElement && te.getRefType() instanceof BaseType) { return getWrapperType(te) + dims; } } return getWrapperType(type.getName()); } /** * Return the SOAPAction (if any) of this binding operation * * @param bindingOper the operation to look at * @return the SOAPAction or null if not found */ public static String getOperationSOAPAction(BindingOperation bindingOper) { // Find the SOAPAction. List elems = bindingOper.getExtensibilityElements(); Iterator it = elems.iterator(); boolean found = false; String action = null; while (!found && it.hasNext()) { ExtensibilityElement elem = (ExtensibilityElement) it.next(); if (elem instanceof SOAPOperation) { SOAPOperation soapOp = (SOAPOperation) elem; action = soapOp.getSoapActionURI(); found = true; } else if (elem instanceof SOAP12Operation) { SOAP12Operation soapOp = (SOAP12Operation) elem; action = soapOp.getSoapActionURI(); found = true; } } return action; } /** * Common code for generating a QName in emitted code. Note that there's * no semicolon at the end, so we can use this in a variety of contexts. * * @param qname * @return */ public static String getNewQName(javax.xml.namespace.QName qname) { return "new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() + "\", \"" + qname.getLocalPart() + "\")"; } public static String getNewQNameWithLastLocalPart(javax.xml.namespace.QName qname) { return "new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() + "\", \"" + getLastLocalPart(qname.getLocalPart()) + "\")"; } /** * Get the parameter type name. If this is a MIME type, then * figure out the appropriate type from the MIME type, otherwise * use the name of the type itself. * * @param parm * @return */ public static String getParameterTypeName(Parameter parm) { String ret; if (parm.getMIMEInfo() == null) { ret = parm.getType().getName(); // If minOccurs="0" and singular or array with nillable underlying // type get the corresponding wrapper type. if ((parm.isOmittable() && parm.getType().getDimensions().equals("")) || (parm.getType() instanceof CollectionType && ((CollectionType) parm.getType()).isWrapped()) || parm.getType().getUnderlTypeNillable()) { ret = getWrapperType(parm.getType()); } } else { String mime = parm.getMIMEInfo().getType(); ret = JavaUtils.mimeToJava(mime); if (ret == null) { ret = parm.getType().getName(); } else { ret += parm.getMIMEInfo().getDimensions(); } } return ret; } // getParameterTypeName /** Field constructorMap */ private static HashMap constructorMap = new HashMap(50); /** Field constructorThrowMap */ private static HashMap constructorThrowMap = new HashMap(50); static { // Type maps to a valid initialization value for that type // Type var = new Type(arg) // Where "Type" is the key and "new Type(arg)" is the string stored // Used in emitting test cases and server skeletons. constructorMap.put("int", "0"); constructorMap.put("float", "0"); constructorMap.put("boolean", "true"); constructorMap.put("double", "0"); constructorMap.put("byte", "(byte)0"); constructorMap.put("short", "(short)0"); constructorMap.put("long", "0"); constructorMap.put("java.lang.Boolean", "new java.lang.Boolean(false)"); constructorMap.put("java.lang.Byte", "new java.lang.Byte((byte)0)"); constructorMap.put("java.lang.Double", "new java.lang.Double(0)"); constructorMap.put("java.lang.Float", "new java.lang.Float(0)"); constructorMap.put("java.lang.Integer", "new java.lang.Integer(0)"); constructorMap.put("java.lang.Long", "new java.lang.Long(0)"); constructorMap.put("java.lang.Short", "new java.lang.Short((short)0)"); constructorMap.put("java.math.BigDecimal", "new java.math.BigDecimal(0)"); constructorMap.put("java.math.BigInteger", "new java.math.BigInteger(\"0\")"); constructorMap.put("java.lang.Object", "new java.lang.String()"); constructorMap.put("byte[]", "new byte[0]"); constructorMap.put("java.util.Calendar", "java.util.Calendar.getInstance()"); constructorMap.put( "javax.xml.namespace.QName", "new javax.xml.namespace.QName(\"http://double-double\", \"toil-and-trouble\")"); constructorMap.put( "org.apache.axis.types.NonNegativeInteger", "new org.apache.axis.types.NonNegativeInteger(\"0\")"); constructorMap.put("org.apache.axis.types.PositiveInteger", "new org.apache.axis.types.PositiveInteger(\"1\")"); constructorMap.put( "org.apache.axis.types.NonPositiveInteger", "new org.apache.axis.types.NonPositiveInteger(\"0\")"); constructorMap.put("org.apache.axis.types.NegativeInteger", "new org.apache.axis.types.NegativeInteger(\"-1\")"); // These constructors throw exception constructorThrowMap.put( "org.apache.axis.types.Time", "new org.apache.axis.types.Time(\"15:45:45.275Z\")"); constructorThrowMap.put("org.apache.axis.types.UnsignedLong", "new org.apache.axis.types.UnsignedLong(0)"); constructorThrowMap.put("org.apache.axis.types.UnsignedInt", "new org.apache.axis.types.UnsignedInt(0)"); constructorThrowMap.put("org.apache.axis.types.UnsignedShort", "new org.apache.axis.types.UnsignedShort(0)"); constructorThrowMap.put("org.apache.axis.types.UnsignedByte", "new org.apache.axis.types.UnsignedByte(0)"); constructorThrowMap.put( "org.apache.axis.types.URI", "new org.apache.axis.types.URI(\"urn:testing\")"); constructorThrowMap.put("org.apache.axis.types.Year", "new org.apache.axis.types.Year(2000)"); constructorThrowMap.put("org.apache.axis.types.Month", "new org.apache.axis.types.Month(1)"); constructorThrowMap.put("org.apache.axis.types.Day", "new org.apache.axis.types.Day(1)"); constructorThrowMap.put("org.apache.axis.types.YearMonth", "new org.apache.axis.types.YearMonth(2000,1)"); constructorThrowMap.put("org.apache.axis.types.MonthDay", "new org.apache.axis.types.MonthDay(1, 1)"); } /** * Return a constructor for the provided Parameter * This string will be suitable for assignment: * <p> * Foo var = <i>string returned</i> * <p> * Handles basic java types (int, float, etc), wrapper types (Integer, etc) * and certain java.math (BigDecimal, BigInteger) types. * Will also handle all Axis specific types (org.apache.axis.types.*) * <p> * Caller should expect to wrap the construction in a try/catch block * if bThrow is set to <i>true</i>. * * @param param info about the parameter we need a constructor for * @param symbolTable used to lookup enumerations * @param bThrow set to true if contructor needs try/catch block * @return */ public static String getConstructorForParam(Parameter param, SymbolTable symbolTable, BooleanHolder bThrow) { String paramType = param.getType().getName(); // For base types that are nillable and are mapped to primitives, // need to switch to the corresponding wrapper types. if ((param.isOmittable() && param.getType().getDimensions().equals("")) || (param.getType() instanceof CollectionType && ((CollectionType) param.getType()).isWrapped()) || param.getType().getUnderlTypeNillable()) { paramType = getWrapperType(param.getType()); } String mimeType = (param.getMIMEInfo() == null) ? null : param.getMIMEInfo().getType(); String mimeDimensions = (param.getMIMEInfo() == null) ? "" : param.getMIMEInfo().getDimensions(); String out = null; // Handle mime types if (mimeType != null) { if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) { return "null"; } else if (mimeType.equals("text/xml") || mimeType.equals("application/xml")) { if (mimeDimensions.length() <= 0) { return "new javax.xml.transform.stream.StreamSource()"; } else { return "new javax.xml.transform.stream.StreamSource[0]"; } } else if (mimeType.equals("application/octet-stream")|| mimeType.equals("application/octetstream")) { if (mimeDimensions.length() <= 0) { return "new org.apache.axis.attachments.OctetStream()"; } else { return "new org.apache.axis.attachments.OctetStream[0]"; } } else { return "new " + Utils.getParameterTypeName(param) + "()"; } } // Look up paramType in the table out = (String) constructorMap.get(paramType); if (out != null) { return out; } // Look up paramType in the table of constructors that can throw exceptions out = (String) constructorThrowMap.get(paramType); if (out != null) { bThrow.value = true; return out; } // Handle arrays if (paramType.endsWith("[]")) { return "new " + JavaUtils.replace(paramType, "[]", "[0]"); } /** * We have some constructed type. */ // Check for enumeration Vector v = Utils.getEnumerationBaseAndValues(param.getType().getNode(), symbolTable); if (v != null) { // This constructed type is an enumeration. Use the first one. String enumeration = (String) JavaEnumTypeWriter.getEnumValueIds(v).get(0); return paramType + "." + enumeration; } if(param.getType().getRefType()!= null){ // Check for enumeration Vector v2 = Utils.getEnumerationBaseAndValues(param.getType().getRefType().getNode(), symbolTable); if (v2 != null) { // This constructed type is an enumeration. Use the first one. String enumeration = (String) JavaEnumTypeWriter.getEnumValueIds(v2).get(0); return paramType + "." + enumeration; } } // This constructed type is a normal type, instantiate it. return "new " + paramType + "()"; } public static boolean shouldEmit(TypeEntry type) { // 1) Don't register types that are base (primitive) types // or attributeGroups or xs:groups. // If the baseType != null && getRefType() != null this // is a simpleType that must be registered. // 2) Don't register the special types for collections // (indexed properties) or elements // 3) Don't register types that are not referenced // or only referenced in a literal context. return (!(((type.getBaseType() != null) && (type.getRefType() == null)) || (type instanceof CollectionTE) || (type instanceof Element) || !type.isReferenced() || type.isOnlyLiteralReferenced() || ((type.getNode() != null) && (isXsNode(type.getNode(), "group") || isXsNode(type.getNode(), "attributeGroup"))))); } public static QName getItemQName(TypeEntry te) { if (te instanceof DefinedElement) { te = te.getRefType(); } return te.getItemQName(); } public static QName getItemType(TypeEntry te) { if (te instanceof DefinedElement) { te = te.getRefType(); } return te.getComponentType(); } } // class Utils
6,875
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaSkelWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Binding; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.BindingOutput; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.extensions.soap.SOAPBody; import javax.wsdl.extensions.soap.SOAPOperation; import javax.wsdl.extensions.soap12.SOAP12Body; import javax.wsdl.extensions.soap12.SOAP12Operation; import javax.xml.namespace.QName; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This is Wsdl2java's skeleton writer. It writes the &lt;BindingName&gt;Skeleton.java * file which contains the &lt;bindingName&gt;Skeleton class. */ public class JavaSkelWriter extends JavaClassWriter { /** Field bEntry */ private BindingEntry bEntry; /** Field binding */ private Binding binding; /** Field symbolTable */ private SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param bEntry * @param symbolTable */ protected JavaSkelWriter(Emitter emitter, BindingEntry bEntry, SymbolTable symbolTable) { super(emitter, bEntry.getName() + "Skeleton", "skeleton"); this.bEntry = bEntry; this.binding = bEntry.getBinding(); this.symbolTable = symbolTable; } // ctor /** * Returns "implements &lt;SEI&gt;, org.apache.axis.wsdl.Skeleton ". * * @return */ protected String getImplementsText() { return "implements " + bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME) + ", org.apache.axis.wsdl.Skeleton "; } // getImplementsText /** * Write the body of the binding's stub file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { String portTypeName = (String) bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME); String implType = portTypeName + " impl"; // Declare private impl and skeleton base delegates pw.println(" private " + implType + ";"); pw.println( " private static java.util.Map _myOperations = new java.util.Hashtable();"); pw.println( " private static java.util.Collection _myOperationsList = new java.util.ArrayList();"); pw.println(); pw.println(" /**"); pw.println( " * Returns List of OperationDesc objects with this name"); pw.println(" */"); pw.println( " public static java.util.List getOperationDescByName(java.lang.String methodName) {"); pw.println( " return (java.util.List)_myOperations.get(methodName);"); pw.println(" }"); pw.println(); pw.println(" /**"); pw.println(" * Returns Collection of OperationDescs"); pw.println(" */"); pw.println( " public static java.util.Collection getOperationDescs() {"); pw.println(" return _myOperationsList;"); pw.println(" }"); pw.println(); // Initialize operation parameter names pw.println(" static {"); pw.println(" org.apache.axis.description.OperationDesc _oper;"); pw.println(" org.apache.axis.description.FaultDesc _fault;"); pw.println( " org.apache.axis.description.ParameterDesc [] _params;"); List operations = binding.getBindingOperations(); for (int i = 0; i < operations.size(); ++i) { BindingOperation bindingOper = (BindingOperation) operations.get(i); Operation operation = bindingOper.getOperation(); OperationType type = operation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { continue; } Parameters parameters = bEntry.getParameters(bindingOper.getOperation()); if (parameters != null) { // The invoked java name of the bindingOper is stored. String opName = bindingOper.getOperation().getName(); String javaOpName = JavaUtils.xmlNameToJava(opName); pw.println( " _params = new org.apache.axis.description.ParameterDesc [] {"); for (int j = 0; j < parameters.list.size(); j++) { Parameter p = (Parameter) parameters.list.get(j); String modeStr; switch (p.getMode()) { case Parameter.IN: modeStr = "org.apache.axis.description.ParameterDesc.IN"; break; case Parameter.OUT: modeStr = "org.apache.axis.description.ParameterDesc.OUT"; break; case Parameter.INOUT: modeStr = "org.apache.axis.description.ParameterDesc.INOUT"; break; default : throw new IOException( Messages.getMessage( "badParmMode00", (new Byte(p.getMode())).toString())); } // Get the QNames representing the parameter name and type QName paramName = p.getQName(); QName paramType = Utils.getXSIType(p); // Is this parameter a header? String inHeader = p.isInHeader() ? "true" : "false"; String outHeader = p.isOutHeader() ? "true" : "false"; pw.println( " " + "new org.apache.axis.description.ParameterDesc(" + Utils.getNewQNameWithLastLocalPart(paramName) + ", " + modeStr + ", " + Utils.getNewQName(paramType) + ", " + Utils.getParameterTypeName(p) + ".class" + ", " + inHeader + ", " + outHeader + "), "); } pw.println(" };"); // Get the return name QName and type QName retName = null; QName retType = null; if (parameters.returnParam != null) { retName = parameters.returnParam.getQName(); retType = Utils.getXSIType(parameters.returnParam); } String returnStr; if (retName != null) { returnStr = Utils.getNewQNameWithLastLocalPart(retName); } else { returnStr = "null"; } pw.println( " _oper = new org.apache.axis.description.OperationDesc(\"" + javaOpName + "\", _params, " + returnStr + ");"); if (retType != null) { pw.println(" _oper.setReturnType(" + Utils.getNewQName(retType) + ");"); if ((parameters.returnParam != null) && parameters.returnParam.isOutHeader()) { pw.println(" _oper.setReturnHeader(true);"); } } // If we need to know the QName (if we have a namespace or // the actual method name doesn't match the XML we expect), // record it in the OperationDesc QName elementQName = Utils.getOperationQName(bindingOper, bEntry, symbolTable); if (elementQName != null) { pw.println(" _oper.setElementQName(" + Utils.getNewQName(elementQName) + ");"); } // Find the SOAPAction. String action = Utils.getOperationSOAPAction(bindingOper); if (action != null) { pw.println(" _oper.setSoapAction(\"" + action + "\");"); } pw.println(" _myOperationsList.add(_oper);"); pw.println(" if (_myOperations.get(\"" + javaOpName + "\") == null) {"); pw.println(" _myOperations.put(\"" + javaOpName + "\", new java.util.ArrayList());"); pw.println(" }"); pw.println(" ((java.util.List)_myOperations.get(\"" + javaOpName + "\")).add(_oper);"); } // Now generate FaultDesc if (bEntry.getFaults() != null) { ArrayList faults = (ArrayList) bEntry.getFaults().get(bindingOper); if (faults != null) { // Operation was not created if there were no parameters if (parameters == null) { String opName = bindingOper.getOperation().getName(); String javaOpName = JavaUtils.xmlNameToJava(opName); pw.println( " _oper = " + "new org.apache.axis.description.OperationDesc();"); pw.println(" _oper.setName(\"" + javaOpName + "\");"); } // Create FaultDesc items for each fault Iterator it = faults.iterator(); while (it.hasNext()) { FaultInfo faultInfo = (FaultInfo) it.next(); QName faultQName = faultInfo.getQName(); QName faultXMLType = faultInfo.getXMLType(); String faultName = faultInfo.getName(); String className = Utils.getFullExceptionName(faultInfo.getMessage(), symbolTable); pw.println( " _fault = " + "new org.apache.axis.description.FaultDesc();"); if (faultName != null) { pw.println(" _fault.setName(\"" + faultName + "\");"); } if (faultQName != null) { pw.println(" _fault.setQName(" + Utils.getNewQName(faultQName) + ");"); } if (className != null) { pw.println(" _fault.setClassName(\"" + className + "\");"); } if (faultXMLType != null) { pw.println(" _fault.setXmlType(" + Utils.getNewQName(faultXMLType) + ");"); } pw.println(" _oper.addFault(_fault);"); } } } } pw.println(" }"); pw.println(); // Skeleton constructors pw.println(" public " + className + "() {"); // Use custom implementation class if available. String implementationClassName = emitter.getImplementationClassName(); if ( implementationClassName == null) implementationClassName = bEntry.getName() + "Impl"; pw.println(" this.impl = new " + implementationClassName + "();"); pw.println(" }"); pw.println(); pw.println(" public " + className + "(" + implType + ") {"); pw.println(" this.impl = impl;"); pw.println(" }"); // Now write each of the operation methods for (int i = 0; i < operations.size(); ++i) { BindingOperation operation = (BindingOperation) operations.get(i); Parameters parameters = bEntry.getParameters(operation.getOperation()); // Get the soapAction from the <soap:operation> String soapAction = ""; Iterator operationExtensibilityIterator = operation.getExtensibilityElements().iterator(); for (; operationExtensibilityIterator.hasNext();) { Object obj = operationExtensibilityIterator.next(); if (obj instanceof SOAPOperation) { soapAction = ((SOAPOperation) obj).getSoapActionURI(); break; } else if (obj instanceof SOAP12Operation) { soapAction = ((SOAP12Operation) obj).getSoapActionURI(); break; } } // Get the namespace for the operation from the <soap:body> // RJB: is this the right thing to do? String namespace = ""; Iterator bindingMsgIterator = null; BindingInput input = operation.getBindingInput(); BindingOutput output; if (input != null) { bindingMsgIterator = input.getExtensibilityElements().iterator(); } else { output = operation.getBindingOutput(); if (output != null) { bindingMsgIterator = output.getExtensibilityElements().iterator(); } } if (bindingMsgIterator != null) { for (; bindingMsgIterator.hasNext();) { Object obj = bindingMsgIterator.next(); if (obj instanceof SOAPBody) { namespace = ((SOAPBody) obj).getNamespaceURI(); if (namespace == null) { namespace = symbolTable.getDefinition().getTargetNamespace(); } if (namespace == null) { namespace = ""; } break; } else if (obj instanceof SOAP12Body) { namespace = ((SOAP12Body) obj).getNamespaceURI(); if (namespace == null) { namespace = symbolTable.getDefinition().getTargetNamespace(); } if (namespace == null) { namespace = ""; } break; } } } Operation ptOperation = operation.getOperation(); OperationType type = ptOperation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { pw.println(parameters.signature); pw.println(); } else { writeOperation(pw, operation, parameters, soapAction, namespace); } } } // writeFileBody /** * Write the skeleton code for the given operation. * * @param pw * @param operation * @param parms * @param soapAction * @param namespace */ protected void writeOperation(PrintWriter pw, BindingOperation operation, Parameters parms, String soapAction, String namespace) { writeComment(pw, operation.getDocumentationElement(), true); // The skeleton used to have specialized operation signatures. // now the same signature is used as the portType pw.println(parms.signature); pw.println(" {"); // Note: The holders are now instantiated by the runtime and passed // in as parameters. // Call the real implementation if (parms.returnParam == null) { pw.print(" "); } else { pw.print(" " + Utils.getParameterTypeName(parms.returnParam) + " ret = "); } String call = "impl." + JavaUtils.xmlNameToJava(operation.getName()) + "("; boolean needComma = false; for (int i = 0; i < parms.list.size(); ++i) { if (needComma) { call = call + ", "; } else { needComma = true; } Parameter p = (Parameter) parms.list.get(i); call = call + JavaUtils.xmlNameToJava(p.getName()); } call = call + ")"; pw.println(call + ";"); if (parms.returnParam != null) { pw.println(" return ret;"); } pw.println(" }"); pw.println(); } // writeSkeletonOperation } // class JavaSkelWriter
6,876
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaUndeployWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Definition; import javax.wsdl.Port; import javax.wsdl.Service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; /** * This is Wsdl2java's deploy Writer. It writes the deploy.java file. */ public class JavaUndeployWriter extends JavaWriter { /** Field definition */ protected Definition definition; /** * Constructor. * * @param emitter * @param definition * @param notUsed */ public JavaUndeployWriter(Emitter emitter, Definition definition, SymbolTable notUsed) { super(emitter, "undeploy"); this.definition = definition; } // ctor /** * Generate undeploy.wsdd. Only generate it if the emitter * is generating server-side mappings. * * @throws IOException */ public void generate() throws IOException { if (emitter.isServerSide()) { super.generate(); } } // generate /** * Return the fully-qualified name of the undeploy.wsdd file * to be generated. * * @return */ protected String getFileName() { String dir = emitter.getNamespaces().getAsDir(definition.getTargetNamespace()); return dir + "undeploy.wsdd"; } // getFileName /** * Replace the default file header with the deployment doc file header. * * @param pw * @throws IOException */ protected void writeFileHeader(PrintWriter pw) throws IOException { pw.println(Messages.getMessage("deploy01")); pw.println(Messages.getMessage("deploy02")); pw.println(Messages.getMessage("deploy04")); pw.println(Messages.getMessage("deploy05")); pw.println(Messages.getMessage("deploy06")); pw.println(Messages.getMessage("deploy08")); pw.println(Messages.getMessage("deploy09")); pw.println(); pw.println("<undeployment"); pw.println(" xmlns=\"" + WSDDConstants.URI_WSDD + "\">"); } // writeFileHeader /** * Write the body of the deploy.wsdd file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { writeDeployServices(pw); pw.println("</undeployment>"); } // writeFileBody /** * Write out deployment and undeployment instructions for each WSDL service * * @param pw * @throws IOException */ protected void writeDeployServices(PrintWriter pw) throws IOException { // deploy the ports on each service Map serviceMap = definition.getServices(); for (Iterator mapIterator = serviceMap.values().iterator(); mapIterator.hasNext();) { Service myService = (Service) mapIterator.next(); pw.println(); pw.println( " <!-- " + Messages.getMessage( "wsdlService00", myService.getQName().getLocalPart()) + " -->"); pw.println(); for (Iterator portIterator = myService.getPorts().values().iterator(); portIterator.hasNext();) { Port myPort = (Port) portIterator.next(); writeDeployPort(pw, myPort); } } } // writeDeployServices /** * Write out deployment and undeployment instructions for given WSDL port * * @param pw * @param port * @throws IOException */ protected void writeDeployPort(PrintWriter pw, Port port) throws IOException { String serviceName = port.getName(); pw.println(" <service name=\"" + serviceName + "\"/>"); } // writeDeployPort /** * Method getPrintWriter * * @param filename * @return * @throws IOException */ protected PrintWriter getPrintWriter(String filename) throws IOException { File file = new File(filename); File parent = new File(file.getParent()); parent.mkdirs(); FileOutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); return new PrintWriter(writer); } } // class JavaUndeployWriter
6,877
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaServiceImplWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.WSDLUtils; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.BackslashUtil; import javax.wsdl.Binding; import javax.wsdl.Port; import javax.wsdl.Service; import javax.xml.namespace.QName; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; /** * This is Wsdl2java's service implementation writer. * It writes the &lt;serviceName&gt;Locator.java file. */ public class JavaServiceImplWriter extends JavaClassWriter { /** Field sEntry */ private ServiceEntry sEntry; /** Field symbolTable */ private SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param sEntry * @param symbolTable */ protected JavaServiceImplWriter(Emitter emitter, ServiceEntry sEntry, SymbolTable symbolTable) { super(emitter, sEntry.getName() + "Locator", "service"); this.sEntry = sEntry; this.symbolTable = symbolTable; } // ctor /** * Returns "extends org.apache.axis.client.Service ". * * @return */ protected String getExtendsText() { return "extends org.apache.axis.client.Service "; } // getExtendsText /** * Returns "implements &lt;serviceInterface&gt;". * * @return */ protected String getImplementsText() { return "implements " + sEntry.getName() + ' '; } // getImplementsText /** * Write the body of the service file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { Service service = sEntry.getService(); // output comments writeComment(pw, service.getDocumentationElement(), false); // Used to construct the getPort(Class) method. Vector getPortIfaces = new Vector(); Vector getPortStubClasses = new Vector(); Vector getPortPortNames = new Vector(); Vector getPortPortXmlNames = new Vector(); boolean printGetPortNotice = false; // get ports Map portMap = service.getPorts(); Iterator portIterator = portMap.values().iterator(); //Write the constructor for <servicename>Locator writeConstructors(pw); // write a get method for each of the ports with a SOAP binding while (portIterator.hasNext()) { Port p = (Port) portIterator.next(); Binding binding = p.getBinding(); if (binding == null) { throw new IOException(Messages.getMessage("emitFailNoBinding01", new String[]{ p.getName()})); } BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); if (bEntry == null) { throw new IOException( Messages.getMessage( "emitFailNoBindingEntry01", new String[]{binding.getQName().toString()})); } PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(binding.getPortType().getQName()); if (ptEntry == null) { throw new IOException( Messages.getMessage( "emitFailNoPortType01", new String[]{ binding.getPortType().getQName().toString()})); } // If this isn't an SOAP binding, skip it if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } // JSR 101 indicates that the name of the port used // in the java code is the name of the wsdl:port. It // does not indicate what should occur if the // wsdl:port name is not a java identifier. The // TCK depends on the case-sensitivity being preserved, // and the interop tests have port names that are not // valid java identifiers. Thus the following code. // java port <--> wsdl port mapping String portXmlName = p.getName(); String portName = (String) bEntry.getDynamicVar(JavaServiceWriter.PORT_NAME + ":" + p.getName()); if (portName == null) { portName = p.getName(); } if (!JavaUtils.isJavaId(portName)) { portName = Utils.xmlNameToJavaClass(portName); } String stubClass = bEntry.getName() + "Stub"; String bindingType = (String) bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME); // getPort(Class) must return a stub for an interface. Collect all // the port interfaces so the getPort(Class) method can be constructed. if (getPortIfaces.contains(bindingType)) { printGetPortNotice = true; } getPortIfaces.add(bindingType); getPortPortXmlNames.add(portXmlName); getPortStubClasses.add(stubClass); getPortPortNames.add(portName); // Get endpoint address and validate it String address = WSDLUtils.getAddressFromPort(p); if (address == null) { // now what? throw new IOException(Messages.getMessage("emitFail02", portName, className)); } try { new java.net.URL(address); } catch (MalformedURLException e) { // this exception may be due to an unrecognized protocol // so try to instantiate the protocol handler directly // and use that to create the URL java.net.URL url = null; java.net.URLStreamHandler handler = null; String handlerPkgs = System.getProperty("java.protocol.handler.pkgs"); if (handlerPkgs != null) { int protIndex = address.indexOf(":"); if (protIndex > 0) { String protocol = address.substring(0, protIndex); StringTokenizer st = new StringTokenizer(handlerPkgs, "|"); while (st.hasMoreTokens()) { String pkg = st.nextToken(); String handlerClass = pkg + "." + protocol + ".Handler"; try { Class c = Class.forName(handlerClass); handler = (java.net.URLStreamHandler) c.newInstance(); url = new java.net.URL(null, address, handler); break; } catch (Exception e2) { url = null; } } } } if (url == null) { if (emitter.isAllowInvalidURL()) { // Unchecked URL mode System.err.println(Messages.getMessage("emitWarnInvalidURL01", new String[] {portName, className, address})); } else { // Checked URL mode : // URL invalid -> Exception throw new IOException(Messages.getMessage("emitFail03", new String[]{ portName, className, address})); } } } writeAddressInfo(pw, portName, address, p); String wsddServiceName = portName + "WSDDServiceName"; writeWSDDServiceNameInfo(pw, wsddServiceName, portName, portXmlName); writeGetPortName(pw, bindingType, portName); writeGetPortNameURL(pw, bindingType, portName, stubClass, wsddServiceName); writeSetPortEndpointAddress(pw, portName); } writeGetPortClass(pw, getPortIfaces, getPortStubClasses, getPortPortNames, printGetPortNotice); writeGetPortQNameClass(pw, getPortPortNames, getPortPortXmlNames); writeGetServiceName(pw, sEntry.getQName()); writeGetPorts(pw, sEntry.getQName().getNamespaceURI(), getPortPortXmlNames); writeSetEndpointAddress(pw, getPortPortNames); } // writeFileBody /** * write Constructors * * @param pw */ protected void writeConstructors(PrintWriter pw) { //Write the default constructor pw.println(); pw.println(" public " + Utils.getJavaLocalName(sEntry.getName()) + "Locator() {"); pw.println(" }"); pw.println(); //Write a constructor that accepts an Engine Configuration pw.println(); pw.println(" public " + Utils.getJavaLocalName(sEntry.getName()) + "Locator(org.apache.axis.EngineConfiguration config) {"); pw.println(" super(config);"); pw.println(" }"); //Write a constructor that accepts String wsdl location + Service QName pw.println(); pw.println(" public " + Utils.getJavaLocalName(sEntry.getName()) + "Locator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) " + "throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println(" super(wsdlLoc, sName);"); pw.println(" }"); } /** * Write the private address field for this port and the public getter for it. * * @param pw * @param portName * @param address * @param p */ protected void writeAddressInfo(PrintWriter pw, String portName, String address, Port p) { // Write the private address field for this port pw.println(); pw.println(" // " + Messages.getMessage("getProxy00", portName)); writeComment(pw, p.getDocumentationElement(), true); pw.println(" private java.lang.String " + portName + "_address = \"" + address + "\";"); // Write the public address getter for this field pw.println(); pw.println(" public java.lang.String get" + portName + "Address() {"); pw.println(" return " + portName + "_address;"); pw.println(" }"); pw.println(); } // writeAddressInfo /** * Write the private WSDD service name field and the public accessors for it. * * @param pw * @param wsddServiceName * @param portName */ protected void writeWSDDServiceNameInfo(PrintWriter pw, String wsddServiceName, String portName, String portXmlName) { // Write the private WSDD service name field pw.println(" // " + Messages.getMessage("wsddServiceName00")); pw.println(" private java.lang.String " + wsddServiceName + " = \"" + portXmlName + "\";"); pw.println(); // Write the public accessors for the WSDD service name pw.println(" public java.lang.String get" + wsddServiceName + "() {"); pw.println(" return " + wsddServiceName + ";"); pw.println(" }"); pw.println(); pw.println(" public void set" + wsddServiceName + "(java.lang.String name) {"); pw.println(" " + wsddServiceName + " = name;"); pw.println(" }"); pw.println(); } // writeWSDDServiceNameInfo /** * Write the get&lt;portName&gt;() method. * * @param pw * @param bindingType * @param portName */ protected void writeGetPortName(PrintWriter pw, String bindingType, String portName) { pw.println(" public " + bindingType + " get" + portName + "() throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println(" java.net.URL endpoint;"); pw.println(" try {"); pw.println(" endpoint = new java.net.URL(" + portName + "_address);"); pw.println(" }"); pw.println(" catch (java.net.MalformedURLException e) {"); pw.println(" throw new javax.xml.rpc.ServiceException(e);"); pw.println(" }"); pw.println(" return get" + portName + "(endpoint);"); pw.println(" }"); pw.println(); } // writeGetPortName /** * Write the get&lt;portName&gt;(URL) method. * * @param pw * @param bindingType * @param portName * @param stubClass * @param wsddServiceName */ protected void writeGetPortNameURL(PrintWriter pw, String bindingType, String portName, String stubClass, String wsddServiceName) { pw.println(" public " + bindingType + " get" + portName + "(java.net.URL portAddress) throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println(" try {"); pw.println(" " + stubClass + " _stub = new " + stubClass + "(portAddress, this);"); pw.println(" _stub.setPortName(get" + wsddServiceName + "());"); pw.println(" return _stub;"); pw.println(" }"); pw.println(" catch (org.apache.axis.AxisFault e) {"); pw.println(" return null;"); pw.println(" }"); pw.println(" }"); pw.println(); } // writeGetPortNameURL /** * Write the set&lt;portName&gt;EndpointAddress(String) method. * * @param pw * @param portName */ protected void writeSetPortEndpointAddress(PrintWriter pw, String portName) { pw.println(" public void set" + portName + "EndpointAddress(java.lang.String address) {"); pw.println(" " + portName + "_address = address;"); pw.println(" }"); pw.println(); } // writeSetPortEndpointAddress /** * Write the getPort(Class serviceInterfaceWriter) method. * * @param pw * @param getPortIfaces * @param getPortStubClasses * @param getPortPortNames * @param printGetPortNotice */ protected void writeGetPortClass(PrintWriter pw, Vector getPortIfaces, Vector getPortStubClasses, Vector getPortPortNames, boolean printGetPortNotice) { pw.println(" /**"); pw.println(" * " + Messages.getMessage("getPortDoc00")); pw.println(" * " + Messages.getMessage("getPortDoc01")); pw.println(" * " + Messages.getMessage("getPortDoc02")); if (printGetPortNotice) { pw.println(" * " + Messages.getMessage("getPortDoc03")); pw.println(" * " + Messages.getMessage("getPortDoc04")); } pw.println(" */"); pw.println( " public java.rmi.Remote getPort(Class serviceEndpointInterface) throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); if (getPortIfaces.size() == 0) { pw.println( " throw new " + javax.xml.rpc.ServiceException.class.getName() + "(\"" + Messages.getMessage("noStub") + " \" + (serviceEndpointInterface == null ? \"null\" : serviceEndpointInterface.getName()));"); } else { pw.println(" try {"); for (int i = 0; i < getPortIfaces.size(); ++i) { String iface = (String) getPortIfaces.get(i); String stubClass = (String) getPortStubClasses.get(i); String portName = (String) getPortPortNames.get(i); pw.println( " if (" + iface + ".class.isAssignableFrom(serviceEndpointInterface)) {"); pw.println(" " + stubClass + " _stub = new " + stubClass + "(new java.net.URL(" + portName + "_address), this);"); pw.println(" _stub.setPortName(get" + portName + "WSDDServiceName());"); pw.println(" return _stub;"); pw.println(" }"); } pw.println(" }"); pw.println(" catch (java.lang.Throwable t) {"); pw.println(" throw new " + javax.xml.rpc.ServiceException.class.getName() + "(t);"); pw.println(" }"); pw.println( " throw new " + javax.xml.rpc.ServiceException.class.getName() + "(\"" + Messages.getMessage("noStub") + " \" + (serviceEndpointInterface == null ? \"null\" : serviceEndpointInterface.getName()));"); } pw.println(" }"); pw.println(); } // writeGetPortClass /** * Write the getPort(QName portName, Class serviceInterfaceWriter) method. * * @param pw * @param getPortPortNames */ protected void writeGetPortQNameClass(PrintWriter pw, Vector getPortPortNames, Vector getPortPortXmlNames) { pw.println(" /**"); pw.println(" * " + Messages.getMessage("getPortDoc00")); pw.println(" * " + Messages.getMessage("getPortDoc01")); pw.println(" * " + Messages.getMessage("getPortDoc02")); pw.println(" */"); pw.println( " public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println(" if (portName == null) {"); pw.println(" return getPort(serviceEndpointInterface);"); pw.println(" }"); pw.println(" java.lang.String inputPortName = portName.getLocalPart();"); pw.print(" "); for (int i = 0; i < getPortPortNames.size(); ++i) { String portName = (String) getPortPortNames.get(i); String portXmlName = (String) getPortPortXmlNames.get(i); pw.println("if (\"" + portXmlName + "\".equals(inputPortName)) {"); pw.println(" return get" + portName + "();"); pw.println(" }"); pw.print(" else "); } pw.println(" {"); pw.println( " java.rmi.Remote _stub = getPort(serviceEndpointInterface);"); pw.println( " ((org.apache.axis.client.Stub) _stub).setPortName(portName);"); pw.println(" return _stub;"); pw.println(" }"); pw.println(" }"); pw.println(); } // writeGetPortQNameClass /** * Write the getServiceName method. * * @param pw * @param qname */ protected void writeGetServiceName(PrintWriter pw, QName qname) { String originalServiceName = null; QName qNameWithDifferentLocal = null; QName qNameWithBackslashedLocal = null; originalServiceName = sEntry.getOriginalServiceName(); qNameWithDifferentLocal = BackslashUtil.getQNameWithDifferentLocal(qname, originalServiceName); qNameWithBackslashedLocal = BackslashUtil.getQNameWithBackslashedLocal(qNameWithDifferentLocal); pw.println(" public javax.xml.namespace.QName getServiceName() {"); pw.println(" return " + Utils.getNewQName(qNameWithBackslashedLocal) + ";"); pw.println(" }"); pw.println(); } // writeGetServiceName /** * Write the getPorts method. * * @param pw * @param portNames */ protected void writeGetPorts(PrintWriter pw, String namespaceURI, Vector portNames) { pw.println(" private java.util.HashSet ports = null;"); pw.println(); pw.println(" public java.util.Iterator getPorts() {"); pw.println(" if (ports == null) {"); pw.println(" ports = new java.util.HashSet();"); for (int i = 0; i < portNames.size(); ++i) { pw.println(" ports.add(new javax.xml.namespace.QName(\"" + namespaceURI + "\", \"" + portNames.get(i) + "\"));"); } pw.println(" }"); pw.println(" return ports.iterator();"); pw.println(" }"); pw.println(); } // writeGetPorts /** * Write the setEndpointAddress(String portName, String newAddress) * and setEndpointAddress(QName portName, String newAddress) methods. * * @param pw * @param portNames */ protected void writeSetEndpointAddress(PrintWriter pw, Vector portNames) { if (portNames.isEmpty()) { return; } // String method pw.println(" /**"); pw.println(" * " + Messages.getMessage("setEndpointDoc00")); pw.println(" */"); pw.println( " public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println(" "); for (Iterator p = portNames.iterator(); p.hasNext();) { String name = (String) p.next(); pw.println("if (\"" + name + "\".equals(portName)) {"); pw.println(" set" + name + "EndpointAddress(address);"); pw.println(" }"); pw.println(" else "); } pw.println("{ // Unknown Port Name"); pw.println(" throw new " + javax.xml.rpc.ServiceException.class.getName() + "(\" " + Messages.getMessage("unknownPortName") + "\" + portName);"); pw.println(" }"); pw.println(" }"); pw.println(); // QName method pw.println(" /**"); pw.println(" * " + Messages.getMessage("setEndpointDoc00")); pw.println(" */"); pw.println( " public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws " + javax.xml.rpc.ServiceException.class.getName() + " {"); pw.println( " setEndpointAddress(portName.getLocalPart(), address);"); pw.println(" }"); pw.println(); } // writeSetEndpointAddress } // class JavaServiceImplWriter
6,878
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaEnumTypeWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.TypeEntry; import java.io.IOException; import java.io.PrintWriter; import java.util.Vector; /** * This is Wsdl2java's Complex Type Writer. It writes the &lt;typeName&gt;.java file. */ public class JavaEnumTypeWriter extends JavaClassWriter { /** Field elements */ private Vector elements; /** Field type */ private TypeEntry type; /** * Constructor. * * @param emitter * @param type * @param elements */ protected JavaEnumTypeWriter(Emitter emitter, TypeEntry type, Vector elements) { super(emitter, type.getName(), "enumType"); this.elements = elements; this.type = type; } // ctor /** * Return "implements java.io.Serializable ". * * @return */ protected String getImplementsText() { return "implements java.io.Serializable "; } // getImplementsText /** * Generate the binding for the given enumeration type. * The values vector contains the base type (first index) and * the values (subsequent Strings) * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { // Get the java name of the type String javaName = getClassName(); // The first index is the base type. // The base type could be a non-object, if so get the corresponding Class. String baseType = ((TypeEntry) elements.get(0)).getName(); String baseClass = baseType; if (baseType.indexOf("int") == 0) { baseClass = "java.lang.Integer"; } else if (baseType.indexOf("char") == 0) { baseClass = "java.lang.Character"; } else if (baseType.indexOf("short") == 0) { baseClass = "java.lang.Short"; } else if (baseType.indexOf("long") == 0) { baseClass = "java.lang.Long"; } else if (baseType.indexOf("double") == 0) { baseClass = "java.lang.Double"; } else if (baseType.indexOf("float") == 0) { baseClass = "java.lang.Float"; } else if (baseType.indexOf("byte") == 0) { baseClass = "java.lang.Byte"; } // Create a list of the literal values. Vector values = new Vector(); for (int i = 1; i < elements.size(); i++) { String value = (String) elements.get(i); if (baseClass.equals("java.lang.String")) { value = "\"" + value + "\""; // Surround literal with double quotes } else if (baseClass.equals("java.lang.Character")) { value = "'" + value + "'"; } else if (baseClass.equals("java.lang.Float")) { if (!value.endsWith("F") && // Indicate float literal so javac !value.endsWith( "f")) { // doesn't complain about precision. value += "F"; } } else if (baseClass.equals("java.lang.Long")) { if (!value.endsWith("L") && // Indicate float literal so javac !value.endsWith( "l")) { // doesn't complain about precision. value += "L"; } } else if (baseClass.equals("javax.xml.namespace.QName")) { value = org.apache.axis.wsdl.symbolTable.Utils.getQNameFromPrefixedName(type.getNode(), value).toString(); value = "javax.xml.namespace.QName.valueOf(\"" + value + "\")"; } else if (baseClass.equals(baseType)) { // Construct baseClass object with literal string value = "new " + baseClass + "(\"" + value + "\")"; } values.add(value); } // Create a list of ids Vector ids = getEnumValueIds(elements); // Each object has a private _value_ variable to store the base value pw.println(" private " + baseType + " _value_;"); // The enumeration values are kept in a hashtable pw.println( " private static java.util.HashMap _table_ = new java.util.HashMap();"); pw.println(""); // A protected constructor is used to create the static enumeration values pw.println(" // " + Messages.getMessage("ctor00")); pw.println(" protected " + javaName + "(" + baseType + " value) {"); pw.println(" _value_ = value;"); if (baseClass.equals("java.lang.String") || baseClass.equals(baseType)) { pw.println(" _table_.put(_value_,this);"); } else { pw.println(" _table_.put(new " + baseClass + "(_value_),this);"); } pw.println(" }"); pw.println(""); // A public static variable of the base type is generated for each enumeration value. // Each variable is preceded by an _. for (int i = 0; i < ids.size(); i++) { // Need to catch the checked MalformedURIException for URI base types if(baseType.equals("org.apache.axis.types.URI")) { pw.println(" public static final " + baseType + " _" + ids.get(i) + ";"); pw.println(" static {"); pw.println(" try {"); pw.println(" _" + ids.get(i) + " = " + values.get(i) + ";"); pw.println(" }"); pw.println(" catch (org.apache.axis.types.URI.MalformedURIException mue) {"); pw.println(" throw new java.lang.RuntimeException(mue.toString());"); pw.println(" }"); pw.println(" }"); pw.println(""); } else { pw.println(" public static final " + baseType + " _" + ids.get(i) + " = " + values.get(i) + ";"); } } // A public static variable is generated for each enumeration value. for (int i = 0; i < ids.size(); i++) { pw.println(" public static final " + javaName + " " + ids.get(i) + " = new " + javaName + "(_" + ids.get(i) + ");"); } // Getter that returns the base value of the enumeration value pw.println(" public " + baseType + " getValue() { return _value_;}"); // FromValue returns the unique enumeration value object from the table pw.println(" public static " + javaName + " fromValue(" + baseType + " value)"); pw.println(" throws java.lang.IllegalArgumentException {"); pw.println(" " + javaName + " enumeration = (" + javaName + ")"); if (baseClass.equals("java.lang.String") || baseClass.equals(baseType)) { pw.println(" _table_.get(value);"); } else { pw.println(" _table_.get(new " + baseClass + "(value));"); } pw.println( " if (enumeration==null) throw new java.lang.IllegalArgumentException();"); pw.println(" return enumeration;"); pw.println(" }"); // FromString returns the unique enumeration value object from a string representation pw.println(" public static " + javaName + " fromString(java.lang.String value)"); pw.println(" throws java.lang.IllegalArgumentException {"); if (baseClass.equals("java.lang.String")) { pw.println(" return fromValue(value);"); } else if (baseClass.equals("javax.xml.namespace.QName")) { pw.println(" try {"); pw.println(" return fromValue(javax.xml.namespace.QName.valueOf" + "(value));"); pw.println(" } catch (Exception e) {"); pw.println( " throw new java.lang.IllegalArgumentException();"); pw.println(" }"); } else if (baseClass.equals(baseType)) { pw.println(" try {"); pw.println(" return fromValue(new " + baseClass + "(value));"); pw.println(" } catch (Exception e) {"); pw.println( " throw new java.lang.IllegalArgumentException();"); pw.println(" }"); } else if (baseClass.equals("java.lang.Character")) { pw.println(" if (value != null && value.length() == 1);"); pw.println(" return fromValue(value.charAt(0));"); pw.println( " throw new java.lang.IllegalArgumentException();"); } else if (baseClass.equals("java.lang.Integer")) { pw.println(" try {"); pw.println( " return fromValue(java.lang.Integer.parseInt(value));"); pw.println(" } catch (Exception e) {"); pw.println( " throw new java.lang.IllegalArgumentException();"); pw.println(" }"); } else { String parse = "parse" + baseClass.substring(baseClass.lastIndexOf(".") + 1); pw.println(" try {"); pw.println(" return fromValue(" + baseClass + "." + parse + "(value));"); pw.println(" } catch (Exception e) {"); pw.println( " throw new java.lang.IllegalArgumentException();"); pw.println(" }"); } pw.println(" }"); // Equals == to determine equality value. // Since enumeration values are singletons, == is appropriate for equals() pw.println( " public boolean equals(java.lang.Object obj) {return (obj == this);}"); // Provide a reasonable hashCode method (hashCode of the string value of the enumeration) pw.println( " public int hashCode() { return toString().hashCode();}"); // toString returns a string representation of the enumerated value if (baseClass.equals("java.lang.String")) { pw.println( " public java.lang.String toString() { return _value_;}"); } else if (baseClass.equals(baseType)) { pw.println( " public java.lang.String toString() { return _value_.toString();}"); } else { pw.println( " public java.lang.String toString() { return java.lang.String.valueOf(_value_);}"); } pw.println( " public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}"); pw.println( " public static org.apache.axis.encoding.Serializer getSerializer("); pw.println(" java.lang.String mechType, "); pw.println(" java.lang.Class _javaType, "); pw.println(" javax.xml.namespace.QName _xmlType) {"); pw.println(" return "); pw.println( " new org.apache.axis.encoding.ser.EnumSerializer("); pw.println(" _javaType, _xmlType);"); pw.println(" }"); pw.println( " public static org.apache.axis.encoding.Deserializer getDeserializer("); pw.println(" java.lang.String mechType, "); pw.println(" java.lang.Class _javaType, "); pw.println(" javax.xml.namespace.QName _xmlType) {"); pw.println(" return "); pw.println( " new org.apache.axis.encoding.ser.EnumDeserializer("); pw.println(" _javaType, _xmlType);"); pw.println(" }"); pw.println(" // " + Messages.getMessage("typeMeta")); pw.println( " private static org.apache.axis.description.TypeDesc typeDesc ="); pw.println(" new org.apache.axis.description.TypeDesc(" + Utils.getJavaLocalName(type.getName()) + ".class);"); pw.println(); pw.println(" static {"); pw.println(" typeDesc.setXmlType(" + Utils.getNewQName(type.getQName()) + ");"); pw.println(" }"); pw.println(" /**"); pw.println(" * " + Messages.getMessage("returnTypeMeta")); pw.println(" */"); pw.println( " public static org.apache.axis.description.TypeDesc getTypeDesc() {"); pw.println(" return typeDesc;"); pw.println(" }"); pw.println(); } // writeFileBody /** * Get the enumeration names for the values. * The name is affected by whether all of the values of the enumeration * can be expressed as valid java identifiers. * * @param bv Vector base and values vector from getEnumerationBaseAndValues * @return Vector names of enum value identifiers. */ public static Vector getEnumValueIds(Vector bv) { boolean validJava = true; // Assume all enum values are valid ids // Walk the values looking for invalid ids for (int i = 1; (i < bv.size()) && validJava; i++) { String value = (String) bv.get(i); if (!JavaUtils.isJavaId(value)) { validJava = false; } } // Build the vector of ids Vector ids = new Vector(); for (int i = 1; i < bv.size(); i++) { // If any enum values are not valid java, then // all of the ids are of the form value<1..N>. if (!validJava) { ids.add("value" + i); } else { ids.add((String) bv.get(i)); } } return ids; } /** Generate a java source file for enum class. * If the emitter works in deploy mode and the class already exists, the source wull not be generated. */ public void generate() throws IOException { String fqcn = getPackage() + "." + getClassName(); if (emitter.isDeploy()) { if (!emitter.doesExist(fqcn)) { super.generate(); } } else { super.generate(); } } } // class JavaEnumTypeWriter
6,879
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/Namespaces.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; /** * This class is essentially a HashMap of &lt;namespace, package name&gt; pairs with * a few extra wizzbangs. */ public class Namespaces extends HashMap { /** Field root */ private String root; /** Field defaultPackage */ private String defaultPackage = null; /** Toknens in a namespace that are treated as package name part separators. */ private static final char[] pkgSeparators = {'.', ':'}; /** Field javaPkgSeparator */ private static final char javaPkgSeparator = pkgSeparators[0]; /** Field pkg2Namespaces : reverse mapping of Namespaces */ private Map pkg2NamespacesMap = new HashMap(); /** * Method normalizePackageName * * @param pkg * @param separator * @return */ private static String normalizePackageName(String pkg, char separator) { for (int i = 0; i < pkgSeparators.length; i++) { pkg = pkg.replace(pkgSeparators[i], separator); } return pkg; } /** * Instantiate a Namespaces object whose packages will all reside under root. * * @param root */ public Namespaces(String root) { super(); this.root = root; } // ctor /** * Instantiate a clone of an existing Namespaces object. * * @param clone */ private Namespaces(Namespaces clone) { super(clone); this.root = clone.root; this.defaultPackage = clone.defaultPackage; } // ctor /** * Instantiate a clone of this Namespaces object. * * @return */ public Object clone() { return new Namespaces(this); } // clone /** * Get the package name for the given namespace. If there is no entry in the HashMap for * this namespace, create one. * * @param key * @return */ public String getCreate(String key) { return getCreate(key, true); } // getCreate /** * Get the package name for the given namespace. If there is no entry in the HashMap for * this namespace, create one if create flag is on, return <tt>null</tt> otherwise. * * @param key * @param create * @return */ String getCreate(String key, boolean create) { if (defaultPackage != null) { put(key, defaultPackage); return defaultPackage; } String value = (String) super.get(key); if ((value == null) && create) { value = normalizePackageName((String) Utils.makePackageName(key), javaPkgSeparator); put(key, value); } return (String) value; } // getCreate /** * Get the package name in directory format (dots replaced by slashes). If the package name * doesn't exist in the HashMap, return "". * * @param key * @return */ public String getAsDir(String key) { if (defaultPackage != null) { return toDir(defaultPackage); } String pkg = (String) get(key); return toDir(pkg); } // getAsDir /** * Return the given package name in directory format (dots replaced by slashes). If pkg is null, * "" is returned. * * @param pkg * @return */ public String toDir(String pkg) { String dir = null; if (pkg != null) { pkg = normalizePackageName(pkg, File.separatorChar); } if (root == null) { dir = pkg; } else { dir = root + File.separatorChar + pkg; } return (dir == null) ? "" : dir + File.separatorChar; } // toDir /** * Like HashMap's putAll, this adds the given map's contents to this map. But it * also makes sure the value strings are javified. * * @param map */ public void putAll(Map map) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); Object key = entry.getKey(); String pkg = (String) entry.getValue(); pkg = javify(pkg); put(key, pkg); } } // putAll /** * Make sure each package name doesn't conflict with a Java keyword. * Ie., org.apache.import.test becomes org.apache.import_.test. * * @param pkg * @return */ private String javify(String pkg) { StringTokenizer st = new StringTokenizer(pkg, "."); pkg = ""; while (st.hasMoreTokens()) { String token = st.nextToken(); if (JavaUtils.isJavaKeyword(token)) { token = JavaUtils.makeNonJavaKeyword(token); } pkg = pkg + token; if (st.hasMoreTokens()) { pkg = pkg + '.'; } } return pkg; } // javify /** * Make a directory for the given package under root. * * @param pkg */ public void mkdir(String pkg) { String pkgDirString = toDir(pkg); File packageDir = new File(pkgDirString); packageDir.mkdirs(); } // mkdir /** * Set a package name that overrides the namespace map * * @param defaultPackage a java package name (e.g. com.foo) */ public void setDefaultPackage(String defaultPackage) { this.defaultPackage = defaultPackage; } public Object put(Object key, Object value) { // Store pakcage->namespaces vector mapping Vector v = null; if (!pkg2NamespacesMap.containsKey(value)) { v = new Vector(); } else { v = (Vector)pkg2NamespacesMap.get(value); } // NOT need to add an input key (namespace value) to v (package vector) if (!v.contains(key)) { v.add(key); } pkg2NamespacesMap.put(value, v); return super.put(key, value); } public Map getPkg2NamespacesMap() { return pkg2NamespacesMap; } } // class Namespaces
6,880
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBuildFileWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Definition; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; /** * <p>This is Wsdl2java's build file Writer. It writes the build.xml file. * The build.xml file is a ant build file. After run the WSDL2Java and filling * the implementation the user just have to cd to the out dir and type * and "ant" (of course you must have ant installed). Then the ant will genarate a * jar file which named after the wsdl file you used for WSDL2Java. * (named after wsdl file ??? I do not get anything better .. the wsdl file may have * more than one service ect ... so we can use them.)</p> * * <p>This build file work on the where it is created ... User can not move the genarated code * to another mechine and try to build. (class path is broken). But of cource user can * move genarated build file at his will.</p> * * <p>deploy the webservice using the AdminClient and drop the jar to servlet Container. * We might even add another task to deploy the WS as well.</p> * * <p>This feature can be on and off using the -B option default is off</p> * @author Srinath Perera(hemapani@opensource.lk) */ public class JavaBuildFileWriter extends JavaWriter { protected Definition definition; /** Field symbolTable */ protected SymbolTable symbolTable; /** * Constructor */ public JavaBuildFileWriter(Emitter emitter, Definition definition, SymbolTable symbolTable) { super(emitter, "build"); this.definition = definition; this.symbolTable = symbolTable; } protected String getFileName() { String dir = emitter.getOutputDir(); if (dir == null) { dir = "."; } return dir + "/build.xml"; } protected void writeFileBody(PrintWriter out) throws IOException { out.write("<?xml version=\"1.0\"?>\n"); out.write("<project basedir=\".\" default=\"jar\">\n"); out.write(" <property name=\"src\" location=\".\"/>\n"); out.write(" <property name=\"build.classes\" location=\"classes\"/>\n"); out.write(" <path id=\"classpath\">\n"); StringTokenizer tok = getClasspathComponets(); while (tok.hasMoreTokens()) { out.write(" <pathelement location=\"" + tok.nextToken() + "\"/>\n"); } out.write(" </path>\n"); out.write(" <target name=\"compile\">\n"); out.write(" <mkdir dir=\"${build.classes}\"/>\n"); out.write(" <javac destdir=\"${build.classes}\" debug=\"on\">\n"); out.write(" <classpath refid=\"classpath\" />\n"); out.write(" <src path=\"${src}\"/>\n"); out.write(" </javac>\n"); out.write(" </target>\n"); out.write(" <target name=\"jar\" depends=\"compile\">\n"); out.write(" <copy todir=\"${build.classes}\">\n"); out.write(" <fileset dir=\".\" casesensitive=\"yes\" >\n"); out.write(" <include name=\"**/*.wsdd\"/>\n"); out.write(" </fileset>\n"); out.write(" </copy>\n"); out.write(" <jar jarfile=\"" + getJarFileName(symbolTable.getWSDLURI()) + ".jar\" basedir=\"${build.classes}\" >\n"); out.write(" <include name=\"**\" />\n"); out.write(" <manifest>\n"); out.write(" <section name=\"org/apache/ws4j2ee\">\n"); out.write(" <attribute name=\"Implementation-Title\" value=\"Apache Axis\"/>\n"); out.write(" <attribute name=\"Implementation-Vendor\" value=\"Apache Web Services\"/>\n"); out.write(" </section>\n"); out.write(" </manifest>\n"); out.write(" </jar>\n"); out.write(" <delete dir=\"${build.classes}\"/>\n"); out.write(" </target>\n"); out.write("</project>\n"); out.close(); } private StringTokenizer getClasspathComponets() { String classpath = System.getProperty("java.class.path"); String spearator = ";"; if (classpath.indexOf(';') < 0) { //t hen it is UNIX spearator = ":"; } return new StringTokenizer(classpath, spearator); } private String getJarFileName(String wsdlFile) { int index = 0; if ((index = wsdlFile.lastIndexOf("/")) > 0) { wsdlFile = wsdlFile.substring(index + 1); } if ((index = wsdlFile.lastIndexOf("?")) > 0) { wsdlFile = wsdlFile.substring(0, index); } if ((index = wsdlFile.indexOf('.')) != -1) { return wsdlFile.substring(0, index); } else { return wsdlFile; } } /* (non-Javadoc) * @see org.apache.axis.wsdl.gen.Generator#generate() */ public void generate() throws IOException { if (emitter.isBuildFileWanted()) { super.generate(); } } }
6,881
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaTestCaseWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import javax.wsdl.Binding; import javax.wsdl.Fault; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.xml.rpc.holders.BooleanHolder; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; /** * This is Wsdl2java's TestCase writer. It writes the &lt;serviceName&gt;TestCase.java file. */ public class JavaTestCaseWriter extends JavaClassWriter { /** Field sEntry */ protected final ServiceEntry sEntry; /** Field symbolTable */ private SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param sEntry * @param symbolTable */ protected JavaTestCaseWriter(Emitter emitter, ServiceEntry sEntry, SymbolTable symbolTable) { super(emitter, sEntry.getName() + "TestCase", "testCase"); this.sEntry = sEntry; this.symbolTable = symbolTable; } // ctor /** * Returns "extends junit.framework.TestCase ". * * @return */ protected String getExtendsText() { return "extends junit.framework.TestCase "; } // getExtendsText /** * Write the body of the TestCase file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { // Write the constructor pw.print(" public "); pw.print(getClassName()); pw.println("(java.lang.String name) {"); pw.println(" super(name);"); pw.println(" }"); pw.println(""); // get ports Map portMap = sEntry.getService().getPorts(); Iterator portIterator = portMap.values().iterator(); while (portIterator.hasNext()) { Port p = (Port) portIterator.next(); Binding binding = p.getBinding(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); // If this isn't an SOAP binding, skip it if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } // JSR 101 indicates that the name of the port used // in the java code is the name of the wsdl:port. It // does not indicate what should occur if the // wsdl:port name is not a java identifier. The // TCK depends on the case-sensitivity being preserved, // and the interop tests have port names that are not // valid java identifiers. Thus the following code. String portName = p.getName(); if (!JavaUtils.isJavaId(portName)) { portName = Utils.xmlNameToJavaClass(portName); } pw.println(" public void test"+portName+"WSDL() throws Exception {"); writeWSDLTestCode(pw, portName); pw.println(" }"); pw.println(""); PortType portType = binding.getPortType(); writeComment(pw, p.getDocumentationElement(), true); writeServiceTestCode(pw, portName, portType, bEntry); } } // writeFileBody protected void writeWSDLTestCode(PrintWriter pw, String portName) { pw.println(" javax.xml.rpc.ServiceFactory serviceFactory = javax.xml.rpc.ServiceFactory.newInstance();"); pw.println(" java.net.URL url = new java.net.URL(new " + sEntry.getName() + "Locator" + "().get" + portName + "Address() + \"?WSDL\");"); pw.println(" javax.xml.rpc.Service service = serviceFactory.createService(url, new " + sEntry.getName() + "Locator().getServiceName());"); pw.println(" assertTrue(service != null);"); } // Methods may be overloaded. If we just grab the method name // for the test method names, we could end up with duplicates. // The quick-and-easy solution is to have a test counter so that // each test method has a number. /** Field counter */ private int counter = 1; /** * Method writeServiceTestCode * * @param pw * @param portName * @param portType * @param bEntry */ protected void writeServiceTestCode( PrintWriter pw, String portName, PortType portType, BindingEntry bEntry) { Iterator ops = portType.getOperations().iterator(); while (ops.hasNext()) { Operation op = (Operation) ops.next(); OperationType type = op.getStyle(); Parameters params = bEntry.getParameters(op); // did we emit a constructor that throws? BooleanHolder bThrow = new BooleanHolder(false); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { pw.println(" " + params.signature); continue; } String javaOpName = Utils.xmlNameToJavaClass(op.getName()); String testMethodName = "test" + counter++ + portName + javaOpName; pw.println(" public void " + testMethodName + "() throws Exception {"); String bindingType = bEntry.getName() + "Stub"; writeBindingAssignment(pw, bindingType, portName); pw.println(" // Test operation"); String indent = ""; Map faultMap = op.getFaults(); if ((faultMap != null) && (faultMap.size() > 0)) { // we are going to catch fault Exceptions pw.println(" try {"); indent = " "; } Parameter returnParam = params.returnParam; if (returnParam != null) { TypeEntry returnType = returnParam.getType(); pw.print(" " + indent); pw.print(Utils.getParameterTypeName(returnParam)); pw.print(" value = "); if ((returnParam.getMIMEInfo() == null) && !returnParam.isOmittable() && Utils.isPrimitiveType(returnType)) { if ("boolean".equals(returnType.getName())) { pw.println("false;"); } else { pw.println("-3;"); } } else { pw.println("null;"); } } pw.print(" " + indent); if (returnParam != null) { pw.print("value = "); } pw.print("binding."); pw.print(JavaUtils.xmlNameToJava(op.getName())); pw.print("("); Iterator iparam = params.list.iterator(); boolean isFirst = true; while (iparam.hasNext()) { if (isFirst) { isFirst = false; } else { pw.print(", "); } Parameter param = (Parameter) iparam.next(); String suffix = ""; // if we have an out or in/out, we are passing in a holder if (param.getMode() != Parameter.IN) { pw.print("new " + Utils.holder(param, emitter) + "("); suffix = ")"; } // if we have an in or in/out, write the constructor if (param.getMode() != Parameter.OUT) { String constructorString = Utils.getConstructorForParam(param, symbolTable, bThrow); pw.print(constructorString); } pw.print(suffix); } pw.println(");"); if ((faultMap != null) && (faultMap.size() > 0)) { pw.println(" }"); } if (faultMap != null) { Iterator i = faultMap.values().iterator(); int count = 0; while (i.hasNext()) { count++; Fault f = (Fault) i.next(); pw.print(" catch ("); pw.print(Utils.getFullExceptionName(f.getMessage(), symbolTable)); pw.println(" e" + count + ") {"); pw.print(" "); pw.println( "throw new junit.framework.AssertionFailedError(\"" + f.getName() + " Exception caught: \" + e" + count + ");"); pw.println(" }"); } } pw.println(" " + indent + "// TBD - validate results"); /* * pw.println(" catch (java.rmi.RemoteException re) {"); * pw.print(" "); * pw.println("throw new junit.framework.AssertionFailedError(\"Remote Exception caught: \" + re);"); * pw.println(" }"); * if (bThrow.value) { * pw.println(" catch (Exception e) {"); * pw.println(" // Unsigned constructors can throw - ignore"); * pw.println(" }"); * } */ pw.println(" }"); pw.println(); } } // writeServiceTestCode /** * Method writeBindingAssignment * * @param pw * @param bindingType * @param portName */ public void writeBindingAssignment( PrintWriter pw, String bindingType, String portName) { pw.println(" " + bindingType + " binding"); pw.println(" = (" + bindingType + ")"); pw.print(" new " + sEntry.getName()); pw.println("Locator" + "().get" + portName + "();"); pw.println(" assertNotNull(\"" + Messages.getMessage("null00", "binding") + "\", binding);"); pw.println(); pw.println(" // Time out after a minute"); pw.println(" binding.setTimeout(60000);"); pw.println(); } // writeBindingAssignment } // class JavaTestCasepw
6,882
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaServiceIfaceWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Binding; import javax.wsdl.Port; import javax.wsdl.Service; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; /** * This is Wsdl2java's service writer. It writes the &lt;serviceName&gt;.java file. */ public class JavaServiceIfaceWriter extends JavaClassWriter { /** Field service */ private Service service; /** Field symbolTable */ private SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param sEntry * @param symbolTable */ protected JavaServiceIfaceWriter(Emitter emitter, ServiceEntry sEntry, SymbolTable symbolTable) { super(emitter, sEntry.getName(), "service"); this.service = sEntry.getService(); this.symbolTable = symbolTable; } // ctor /** * Returns "interface ". * * @return */ protected String getClassText() { return "interface "; } // getClassString /** * Returns "extends javax.xml.rpc.Service ". * * @return */ protected String getExtendsText() { return "extends javax.xml.rpc.Service "; } // getExtendsText /** * Write the body of the service file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { // output comments writeComment(pw, service.getDocumentationElement(), false); // get ports Map portMap = service.getPorts(); Iterator portIterator = portMap.values().iterator(); // write a get method for each of the ports with a SOAP binding while (portIterator.hasNext()) { Port p = (Port) portIterator.next(); Binding binding = p.getBinding(); if (binding == null) { throw new IOException(Messages.getMessage("emitFailNoBinding01", new String[]{ p.getName()})); } BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); if (bEntry == null) { throw new IOException( Messages.getMessage( "emitFailNoBindingEntry01", new String[]{binding.getQName().toString()})); } PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(binding.getPortType().getQName()); if (ptEntry == null) { throw new IOException( Messages.getMessage( "emitFailNoPortType01", new String[]{ binding.getPortType().getQName().toString()})); } // If this isn't an SOAP binding, skip it if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } // JSR 101 indicates that the name of the port used // in the java code is the name of the wsdl:port. It // does not indicate what should occur if the // wsdl:port name is not a java identifier. The // TCK depends on the case-sensitivity being preserved, // and the interop tests have port names that are not // valid java identifiers. Thus the following code. // java port <--> wsdl port mapping String portName = (String) bEntry.getDynamicVar(JavaServiceWriter.PORT_NAME + ":" + p.getName()); if (portName == null) { portName = p.getName(); } if (!JavaUtils.isJavaId(portName)) { portName = Utils.xmlNameToJavaClass(portName); } // If there is not literal use, the interface name is the portType name. // Otherwise it is the binding name. String bindingType = (String) bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME); // Write out the get<PortName> methods pw.println(" public java.lang.String get" + portName + "Address();"); pw.println(); pw.println(" public " + bindingType + " get" + portName + "() throws " + javax.xml.rpc.ServiceException.class.getName() + ";"); pw.println(); pw.println(" public " + bindingType + " get" + portName + "(java.net.URL portAddress) throws " + javax.xml.rpc.ServiceException.class.getName() + ";"); } } // writeFileBody } // class JavaServiceIfaceWriter
6,883
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/DuplicateFileException.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import java.io.IOException; /** * Class DuplicateFileException * * @version %I%, %G% */ public class DuplicateFileException extends IOException { /** Field filename */ private String filename = null; /** * Constructor DuplicateFileException * * @param message * @param filename */ public DuplicateFileException(String message, String filename) { super(message); this.filename = filename; } /** * Method getFileName * * @return */ public String getFileName() { return this.filename; } }
6,884
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanHelperWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.ContainedAttribute; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.symbolTable.DefinedElement; import org.apache.axis.wsdl.symbolTable.DefinedType; import org.apache.axis.wsdl.symbolTable.ElementDecl; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.axis.wsdl.symbolTable.CollectionTE; import javax.xml.namespace.QName; import java.io.IOException; import java.io.PrintWriter; import java.util.Vector; import java.util.Set; /** * This is Wsdl2java's Helper Type Writer. It writes the &lt;typeName&gt;.java file. */ public class JavaBeanHelperWriter extends JavaClassWriter { /** Field type */ protected TypeEntry type; /** Field elements */ protected Vector elements; /** Field attributes */ protected Vector attributes; /** Field extendType */ protected TypeEntry extendType; /** Field wrapperPW */ protected PrintWriter wrapperPW = null; /** Field elementMetaData */ protected Vector elementMetaData = null; /** Field canSearchParents */ protected boolean canSearchParents; /** Field reservedPropNames */ protected Set reservedPropNames; /** * Constructor. * * @param emitter * @param type The type representing this class * @param elements Vector containing the Type and name of each property * @param extendType The type representing the extended class (or null) * @param attributes Vector containing the attribute types and names */ protected JavaBeanHelperWriter(Emitter emitter, TypeEntry type, Vector elements, TypeEntry extendType, Vector attributes, Set reservedPropNames) { super(emitter, type.getName() + "_Helper", "helper"); this.type = type; this.elements = elements; this.attributes = attributes; this.extendType = extendType; this.reservedPropNames = reservedPropNames; // is this a complex type that is derived from other types // by restriction? if so, set the policy of the generated // TypeDescription to ignore metadata associated with // superclasses, as restricted types are required to // define their entire content model. Hence the type // description associated with the current type provides // all of the types (and only those types) allowed in // the restricted derivation. if ((null != extendType) && (null != SchemaUtils.getComplexElementRestrictionBase( type.getNode(), emitter.getSymbolTable()))) { this.canSearchParents = false; } else { this.canSearchParents = true; } } // ctor /** * The bean helper class may be its own class, or it may be * embedded within the bean class. If it's embedded within the * bean class, the JavaBeanWriter will set JavaBeanHelperWriter's * PrintWriter to its own. * * @param pw */ protected void setPrintWriter(PrintWriter pw) { this.wrapperPW = pw; } // setPrintWriter /** * The default behaviour (of super.getPrintWriter) is, given the * file name, create a PrintWriter for it. If the bean helper * that this class is generating is embedded within a bean, then * the PrintWriter returned by this method is the JavaBeanWriter's * PrintWriter. Otherwise super.getPrintWriter is called. * * @param filename * @return * @throws IOException */ protected PrintWriter getPrintWriter(String filename) throws IOException { return (wrapperPW == null) ? super.getPrintWriter(filename) : wrapperPW; } // getPrintWriter /** * Only register the filename if the bean helper is not wrapped * within a bean. * * @param file */ protected void registerFile(String file) { if (wrapperPW == null) { super.registerFile(file); } } // registerFile /** * Return the string: "Generating &lt;file&gt;". * only if we are going to generate a new file. * * @param file * @return */ protected String verboseMessage(String file) { if (wrapperPW == null) { return super.verboseMessage(file); } else { return null; } } // verboseMessage /** * Only write the file header if the bean helper is not wrapped * within a bean. * * @param pw * @throws IOException */ protected void writeFileHeader(PrintWriter pw) throws IOException { if (wrapperPW == null) { super.writeFileHeader(pw); } } // writeFileHeader /** * Generate the file body for the bean helper. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { writeMetaData(pw); writeSerializer(pw); writeDeserializer(pw); } // writeFileBody /** * Only write the file footer if the bean helper is not * wrapped within a bean. * * @param pw * @throws IOException */ protected void writeFileFooter(PrintWriter pw) throws IOException { if (wrapperPW == null) { super.writeFileFooter(pw); } } // writeFileFooter /** * Only close the PrintWriter if the PrintWriter belongs to * this class. If the bean helper is embedded within a bean * then the PrintWriter belongs to JavaBeanWriter and THAT * class is responsible for closing the PrintWriter. * * @param pw */ protected void closePrintWriter(PrintWriter pw) { // If the output of this writer is wrapped within // another writer (JavaBeanWriter), then THAT // writer will close the PrintWriter, not this one. if (wrapperPW == null) { pw.close(); } } // closePrintWriter /** * write MetaData code * * @param pw * @throws IOException */ protected void writeMetaData(PrintWriter pw) throws IOException { // Collect elementMetaData if (elements != null) { for (int i = 0; i < elements.size(); i++) { ElementDecl elem = (ElementDecl) elements.get(i); // String elemName = elem.getName().getLocalPart(); // String javaName = Utils.xmlNameToJava(elemName); // Changed the code to write meta data // for all of the elements in order to // support sequences. Defect 9060 // Meta data is needed if the default serializer // action cannot map the javaName back to the // element's qname. This occurs if: // - the javaName and element name local part are different. // - the javaName starts with uppercase char (this is a wierd // case and we have several problems with the mapping rules. // Seems best to gen meta data in this case.) // - the element name is qualified (has a namespace uri) // its also needed if: // - the element has the minoccurs flag set // if (!javaName.equals(elemName) || // Character.isUpperCase(javaName.charAt(0)) || // !elem.getName().getNamespaceURI().equals("") || // elem.getMinOccursIs0()) { // If we did some mangling, make sure we'll write out the XML // the correct way. if (elementMetaData == null) { elementMetaData = new Vector(); } elementMetaData.add(elem); // } } } pw.println(" // " + Messages.getMessage("typeMeta")); pw.println( " private static org.apache.axis.description.TypeDesc typeDesc ="); pw.println(" new org.apache.axis.description.TypeDesc(" + Utils.getJavaLocalName(type.getName()) + ".class, " + (this.canSearchParents ? "true" : "false") + ");"); pw.println(); pw.println(" static {"); pw.println(" typeDesc.setXmlType(" + Utils.getNewQName(type.getQName()) + ");"); // Add attribute and element field descriptors if ((attributes != null) || (elementMetaData != null)) { if (attributes != null) { boolean wroteAttrDecl = false; for (int i = 0; i < attributes.size(); i++) { ContainedAttribute attr = (ContainedAttribute) attributes.get(i); TypeEntry te = attr.getType(); QName attrName = attr.getQName(); String fieldName = getAsFieldName(attr.getName()); QName attrXmlType = te.getQName(); pw.print(" "); if (!wroteAttrDecl) { pw.print("org.apache.axis.description.AttributeDesc "); wroteAttrDecl = true; } pw.println( "attrField = new org.apache.axis.description.AttributeDesc();"); pw.println(" attrField.setFieldName(\"" + fieldName + "\");"); pw.println(" attrField.setXmlName(" + Utils.getNewQNameWithLastLocalPart(attrName) + ");"); if (attrXmlType != null) { pw.println(" attrField.setXmlType(" + Utils.getNewQName(attrXmlType) + ");"); } pw.println(" typeDesc.addFieldDesc(attrField);"); } } if (elementMetaData != null) { boolean wroteElemDecl = false; for (int i = 0; i < elementMetaData.size(); i++) { ElementDecl elem = (ElementDecl) elementMetaData.elementAt(i); if (elem.getAnyElement()) { continue; } String fieldName = getAsFieldName(elem.getName()); QName xmlName = elem.getQName(); // Some special handling for arrays. TypeEntry elemType = elem.getType(); QName xmlType = null; if ((elemType.getDimensions().length() > 1) && (elemType.getClass() == DefinedType.class)) { // If we have a DefinedType with dimensions, it must // be a SOAP array derived type. In this case, use // the refType's QName for the metadata. elemType = elemType.getRefType(); } else if (elemType.getClass() == DefinedElement.class && elemType.getRefType() != null) { // If we have a DefinedElement which references other element // (eg. <element ref="aRefEleme"/>) // use the refType's QName for the metadata (which can be anonymous type.) // see the schema of test/wsdl/axis2098 elemType = elemType.getRefType(); } else if (elemType.isSimpleType() && elemType.getRefType() != null) { // see wsdl in AXIS-2138 elemType = elemType.getRefType(); } else { // Otherwise, use the first non-Collection type we // encounter up the ref chain. while (elemType instanceof CollectionTE) { elemType = elemType.getRefType(); } } xmlType = elemType.getQName(); pw.print(" "); if (!wroteElemDecl) { pw.print("org.apache.axis.description.ElementDesc "); wroteElemDecl = true; } pw.println( "elemField = new org.apache.axis.description.ElementDesc();"); pw.println(" elemField.setFieldName(\"" + fieldName + "\");"); pw.println(" elemField.setXmlName(" + Utils.getNewQNameWithLastLocalPart(xmlName) + ");"); if (xmlType != null) { pw.println(" elemField.setXmlType(" + Utils.getNewQName(xmlType) + ");"); } if (elem.getMinOccursIs0()) { pw.println(" elemField.setMinOccurs(0);"); } if (elem.getNillable()) { pw.println(" elemField.setNillable(true);"); } else { pw.println(" elemField.setNillable(false);"); } if(elem.getMaxOccursIsUnbounded()) { pw.println(" elemField.setMaxOccursUnbounded(true);"); } QName itemQName = elem.getType().getItemQName(); if (itemQName != null) { pw.println(" elemField.setItemQName(" + Utils.getNewQName(itemQName) + ");"); } pw.println(" typeDesc.addFieldDesc(elemField);"); } } } pw.println(" }"); pw.println(); pw.println(" /**"); pw.println(" * " + Messages.getMessage("returnTypeMeta")); pw.println(" */"); pw.println( " public static org.apache.axis.description.TypeDesc getTypeDesc() {"); pw.println(" return typeDesc;"); pw.println(" }"); pw.println(); } /** * Utility function to get the bean property name (as will be returned * by the Introspector) for a given field name. This just means * we capitalize the first character if the second character is * capitalized. Example: a field named "fOO" will turn into * getter/setter methods "getFOO()/setFOO()". So when the Introspector * looks at that bean, the property name will be "FOO", not "fOO" due * to the rules in the JavaBeans spec. So this makes sure the * metadata will match. <p> * * The method also makes sure that the returned property name is not in * the set of reserved properties as defined by {@link #reservedPropNames}. * * @param fieldName * @return */ private String getAsFieldName(String fieldName) { // If there's a second character, and it is uppercase, then the // bean property name will have a capitalized first character // (because setURL() maps to a property named "URL", not "uRL") if ((fieldName.length() > 1) && Character.isUpperCase(fieldName.charAt(1))) { fieldName = Utils.capitalizeFirstChar(fieldName); } // Make sure the property name is not reserved. return JavaUtils.getUniqueValue(reservedPropNames, fieldName); } /** * write Serializer getter code and pass in meta data to avoid * undo introspection. * * @param pw * @throws IOException */ protected void writeSerializer(PrintWriter pw) throws IOException { String typeDesc = "typeDesc"; String ser = " org.apache.axis.encoding.ser.BeanSerializer"; if (type.isSimpleType()) { ser = " org.apache.axis.encoding.ser.SimpleSerializer"; } pw.println(" /**"); pw.println(" * Get Custom Serializer"); pw.println(" */"); pw.println( " public static org.apache.axis.encoding.Serializer getSerializer("); pw.println(" java.lang.String mechType, "); pw.println(" java.lang.Class _javaType, "); pw.println(" javax.xml.namespace.QName _xmlType) {"); pw.println(" return "); pw.println(" new " + ser + "("); pw.println(" _javaType, _xmlType, " + typeDesc + ");"); pw.println(" }"); pw.println(); } /** * write Deserializer getter code and pass in meta data to avoid * undo introspection. * * @param pw * @throws IOException */ protected void writeDeserializer(PrintWriter pw) throws IOException { String typeDesc = "typeDesc"; String dser = " org.apache.axis.encoding.ser.BeanDeserializer"; if (type.isSimpleType()) { dser = " org.apache.axis.encoding.ser.SimpleDeserializer"; } pw.println(" /**"); pw.println(" * Get Custom Deserializer"); pw.println(" */"); pw.println( " public static org.apache.axis.encoding.Deserializer getDeserializer("); pw.println(" java.lang.String mechType, "); pw.println(" java.lang.Class _javaType, "); pw.println(" javax.xml.namespace.QName _xmlType) {"); pw.println(" return "); pw.println(" new " + dser + "("); pw.println(" _javaType, _xmlType, " + typeDesc + ");"); pw.println(" }"); pw.println(); } } // class JavaBeanHelperWriter
6,885
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaHolderWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.symbolTable.CollectionType; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import java.io.IOException; import java.io.PrintWriter; /** * This is Wsdl2java's Holder Writer. It writes the &lt;typeName&gt;Holder.java file. */ public class JavaHolderWriter extends JavaClassWriter { /** Field type */ private TypeEntry type; /** * Constructor. * * @param emitter * @param type */ protected JavaHolderWriter(Emitter emitter, TypeEntry type) { super(emitter, Utils.holder(type, emitter), "holder"); this.type = type; } // ctor /** * Return "public final ". * * @return */ protected String getClassModifiers() { return super.getClassModifiers() + "final "; } // getClassModifiers /** * Return "implements javax.xml.rpc.holders.Holder ". * * @return */ protected String getImplementsText() { return "implements javax.xml.rpc.holders.Holder "; } // getImplementsText /** * Generate the holder for the given complex type. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { String holderType = type.getName(); if ((type instanceof CollectionType && ((CollectionType) type).isWrapped()) || type.getUnderlTypeNillable()) { /* * For soapenc arrays or elements with maxOccurs="unbounded" * having a primitive type and nillable="true" the holderType * should be the corresponding wrapped type. */ holderType = Utils.getWrapperType(type); } pw.println(" public " + holderType + " value;"); pw.println(); pw.println(" public " + className + "() {"); pw.println(" }"); pw.println(); pw.println(" public " + className + "(" + holderType + " value) {"); pw.println(" this.value = value;"); pw.println(" }"); pw.println(); } // writeOperation /** Generate a java source file for the holder class. * If the emitter works in deploy mode and the class already exists, the source wull not be generated. */ public void generate() throws IOException { String fqcn = getPackage() + "." + getClassName(); if (emitter.isDeploy()) { if (!emitter.doesExist(fqcn)) { super.generate(); } } else { super.generate(); } } } // class JavaHolderWriter
6,886
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaImplWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import javax.wsdl.Binding; import javax.wsdl.BindingOperation; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.xml.rpc.holders.BooleanHolder; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; /** * This is Wsdl2java's implementation template writer. It writes the &lt;BindingName&gt;Impl.java * file which contains the &lt;bindingName&gt;Impl class. */ public class JavaImplWriter extends JavaClassWriter { /** Field binding */ protected Binding binding; /** Field symbolTable */ protected SymbolTable symbolTable; /** Field bEntry */ protected BindingEntry bEntry; /** * Constructor. * * @param emitter * @param bEntry * @param symbolTable */ protected JavaImplWriter(Emitter emitter, BindingEntry bEntry, SymbolTable symbolTable) { super(emitter, ( emitter.getImplementationClassName() == null ? bEntry.getName() + "Impl" : emitter.getImplementationClassName()), "templateImpl"); this.binding = bEntry.getBinding(); this.symbolTable = symbolTable; this.bEntry = bEntry; } // ctor /** * Write the body of the binding's stub file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { List operations = binding.getBindingOperations(); for (int i = 0; i < operations.size(); ++i) { BindingOperation operation = (BindingOperation) operations.get(i); Operation ptOperation = operation.getOperation(); OperationType type = ptOperation.getStyle(); Parameters parameters = bEntry.getParameters(operation.getOperation()); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { pw.println(parameters.signature); pw.println(); } else { writeOperation(pw, parameters); } } } // writeFileBody /** * Returns the appropriate implements text * * @return " implements &lt;classes&gt;" */ protected String getImplementsText() { String portTypeName = (String) bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME); String implementsText = "implements " + portTypeName; return implementsText; } /** * Write the implementation template for the given operation. * * @param pw * @param parms * @throws IOException */ protected void writeOperation(PrintWriter pw, Parameters parms) throws IOException { pw.println(parms.signature + " {"); // Fill in any out parameter holders Iterator iparam = parms.list.iterator(); while (iparam.hasNext()) { Parameter param = (Parameter) iparam.next(); if (param.getMode() == Parameter.OUT) { // write a constructor for each of the parameters BooleanHolder bThrow = new BooleanHolder(false); String constructorString = Utils.getConstructorForParam(param, symbolTable, bThrow); if (bThrow.value) { pw.println(" try {"); } pw.println(" " + JavaUtils.xmlNameToJava(param.getName()) + ".value = " + constructorString + ";"); if (bThrow.value) { pw.println(" } catch (Exception e) {"); pw.println(" }"); } } } // Print the return statement Parameter returnParam = parms.returnParam; if (returnParam != null) { TypeEntry returnType = returnParam.getType(); pw.print(" return "); if (!returnParam.isOmittable() && Utils.isPrimitiveType(returnType)) { String returnString = returnType.getName(); if ("boolean".equals(returnString)) { pw.println("false;"); } else if ("byte".equals(returnString)) { pw.println("(byte)-3;"); } else if ("short".equals(returnString)) { pw.println("(short)-3;"); } else { pw.println("-3;"); } } else { pw.println("null;"); } } pw.println(" }"); pw.println(); } // writeOperation } // class JavaImplWriter
6,887
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.gen.Generator; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.*; import java.util.StringTokenizer; /** * Emitter knows about WSDL writers, one each for PortType, Binding, Service, * Definition, Type. But for some of these WSDL types, Wsdl2java generates * multiple files. Each of these files has a corresponding writer that extends * JavaWriter. So the Java WSDL writers (JavaPortTypeWriter, JavaBindingWriter, * etc.) each calls a file writer (JavaStubWriter, JavaSkelWriter, etc.) for * each file that that WSDL generates. * <p>For example, when Emitter calls JavaWriterFactory for a Binding Writer, it * returns a JavaBindingWriter. JavaBindingWriter, in turn, contains a * JavaStubWriter, JavaSkelWriter, and JavaImplWriter since a Binding may cause * a stub, skeleton, and impl template to be generated. * <p>Note that the writers that are given to Emitter by JavaWriterFactory DO NOT * extend JavaWriter. They simply implement Writer and delegate the actual * task of writing to extensions of JavaWriter. * <p>All of Wsdl2java's Writer implementations follow a common behaviour. * JavaWriter is the abstract base class that dictates this common behaviour. * This behaviour is primarily placed within the generate method. The generate * method calls, in succession (note: the starred methods are the ones you are * probably most interested in): * <dl> * <dt> * getFileName * <dd> This is an abstract method that must be implemented by the subclass. * It returns the fully-qualified file name. * <dt> isFileGenerated(file) * <dd> You should not need to override this method. It checks to see whether * this file is in the List returned by emitter.getGeneratedFileNames. * <dt> registerFile(file) * <dd> You should not need to override this method. It registers this file by * calling emitter.getGeneratedFileInfo().add(...). * <dt> * verboseMessage(file) * <dd> You may override this method if you want to provide more information. * The generate method only calls verboseMessage if verbose is turned on. * <dt> getPrintWriter(file) * <dd> You should not need to override this method. Given the file name, it * creates a PrintWriter for it. * <dt> * writeFileHeader(pw) * <dd> You may want to override this method. The default implementation * generates nothing. * <dt> * writeFileBody(pw) * <dd> This is an abstract method that must be implemented by the subclass. * This is where the body of a file is generated. * <dt> * writeFileFooter(pw) * <dd> You may want to override this method. The default implementation * generates nothing. * <dt> closePrintWriter(pw) * <dd> You should not need to override this method. It simply closes the * PrintWriter. * </dl> */ public abstract class JavaWriter implements Generator { private static final Log log = LogFactory.getLog(JavaWriter.class.getName()); /** This controls how many characters per line for javadoc comments */ protected final static int LINE_LENGTH = 65; /** Field emitter */ protected Emitter emitter; /** Field type */ protected String type; /** * Constructor. * * @param emitter * @param type */ protected JavaWriter(Emitter emitter, String type) { this.emitter = emitter; this.type = type; } // ctor /** * Generate a file. * * @throws IOException */ public void generate() throws IOException { String file = getFileName(); if (isFileGenerated(file)) { throw new DuplicateFileException( Messages.getMessage("duplicateFile00", file), file); } registerFile(file); if (emitter.isVerbose()) { String msg = verboseMessage(file); if (msg != null) { System.out.println(msg); } } if (log.isDebugEnabled()) { log.debug("Start generating file " + file); } PrintWriter pw = getPrintWriter(file); writeFileHeader(pw); writeFileBody(pw); writeFileFooter(pw); closePrintWriter(pw); } // generate /** * This method must be implemented by a subclass. It * returns the fully-qualified name of the file to be * generated. * * @return */ protected abstract String getFileName(); /** * You should not need to override this method. It checks * to see whether the given file is in the List returned * by emitter.getGeneratedFileNames. * * @param file * @return */ protected boolean isFileGenerated(String file) { return emitter.getGeneratedFileNames().contains(file); } // isFileGenerated /** * You should not need to override this method. * It registers the given file by calling * emitter.getGeneratedFileInfo().add(...). * * @param file */ protected void registerFile(String file) { emitter.getGeneratedFileInfo().add(file, null, type); } // registerFile /** * Return the string: "Generating &lt;file&gt;". Override this * method if you want to provide more information. * * @param file * @return */ protected String verboseMessage(String file) { return Messages.getMessage("generating", file); } // verboseMessage /** * You should not need to override this method. * Given the file name, it creates a PrintWriter for it. * * @param filename * @return * @throws IOException */ protected PrintWriter getPrintWriter(String filename) throws IOException { File file = new File(filename); File parent = new File(file.getParent()); parent.mkdirs(); FileOutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); return new PrintWriter(writer); } // getPrintWriter /** * This method is intended to be overridden as necessary * to generate file header information. This default * implementation does nothing. * * @param pw * @throws IOException */ protected void writeFileHeader(PrintWriter pw) throws IOException { } // writeFileHeader /** * This method must be implemented by a subclass. This * is where the body of a file is generated. * * @param pw * @throws IOException */ protected abstract void writeFileBody(PrintWriter pw) throws IOException; /** * You may want to override this method. This default * implementation generates nothing. * * @param pw * @throws IOException */ protected void writeFileFooter(PrintWriter pw) throws IOException { } // writeFileFooter /** * Close the print writer. * * @param pw */ protected void closePrintWriter(PrintWriter pw) { pw.close(); } // closePrintWriter /** * Takes out new lines and wraps at Javadoc tags * @param documentation the raw comments from schema * @param addTab if true adds a tab character when wrapping (methods) */ protected String getJavadocDescriptionPart(String documentation, boolean addTab) { if (documentation == null) { return ""; } String doc = documentation.trim(); if (documentation.trim().length() == 0) { //nothing to do return doc; } // make @ tags start a new line (for javadoc tags mostly) StringTokenizer st = new StringTokenizer(doc, "@"); StringBuffer newComments; if (st.hasMoreTokens()) { String token = st.nextToken(); boolean startLine = Character.isWhitespace(token.charAt(token.length() - 1)) && (token.charAt(token.length() - 1) != '\n'); newComments = new StringBuffer(token); while (st.hasMoreTokens()) { token = st.nextToken(); // don't span links across lines if (startLine) { newComments.append('\n'); } newComments.append('@'); startLine = Character.isWhitespace(token.charAt(token.length() - 1)) & (token.charAt(token.length() - 1) != '\n'); newComments.append(token); } } else { newComments = new StringBuffer(doc); } newComments.insert(0, addTab ? " * " : " * "); // tweak comment ending tags by insterting a // space between the star and the slash, BUG13407 int pos = newComments.toString().indexOf("*/"); while (pos >= 0) { newComments.insert(pos + 1, ' '); pos = newComments.toString().indexOf("*/"); } // now pretty it up based on column length int lineStart = 0; int newlinePos = 0; while (lineStart < newComments.length()) { newlinePos = newComments.toString().indexOf("\n", lineStart); if (newlinePos == -1) { newlinePos = newComments.length(); } if ((newlinePos - lineStart) > LINE_LENGTH) { // find first whitespace after length lineStart += LINE_LENGTH; while ((lineStart < newComments.length()) && !Character.isWhitespace(newComments.charAt(lineStart))) { lineStart++; } if (lineStart < newComments.length()) { // don't insert if line wold break at EOF char next = newComments.charAt(lineStart); // insert new line header if ((next == '\r') || (next == '\n')) { //newline exists at the break point, don't put in another one newComments.insert(lineStart + 1, addTab ? " * " : " * "); lineStart += addTab ? 8 : 4; } else { newComments.insert(lineStart, addTab ? "\n * " : "\n * "); lineStart += addTab ? 8 : 4; } } // chew up witespace after newline while ((lineStart < newComments.length()) && (newComments.charAt(lineStart) == ' ')) { // only chew up simple spaces newComments.delete(lineStart, lineStart + 1); } } else { if (++newlinePos < newComments.length()) { newComments.insert(newlinePos, addTab ? " * " : " * "); } lineStart = newlinePos; lineStart += addTab ? 7 : 3; } } return newComments.toString(); } /** * Output a documentation element as a Java comment. * * @param pw * @param element */ protected void writeComment(PrintWriter pw, Element element) { writeComment(pw, element, true); } /** * Output a documentation element as a Java comment. * * @param pw * @param element * @param addTab */ protected void writeComment(PrintWriter pw, Element element, boolean addTab) { if (element == null) { return; } Node child = element.getFirstChild(); if (child == null) { return; } String comment = child.getNodeValue(); if (comment != null) { int start = 0; pw.println(); // blank line pw.println(addTab ? " /**" : "/**"); pw.println(getJavadocDescriptionPart(comment, addTab)); pw.println(addTab ? " */" : " */"); } } // writeComment } // abstract class JavaWriter
6,888
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaTypeWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.Type; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.w3c.dom.Node; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Vector; import java.util.Collections; /** * This is Wsdl2java's Type Writer. It writes the following files, as appropriate: * &lt;typeName&gt;.java, &lt;typeName&gt;Holder.java. */ public class JavaTypeWriter implements Generator { /** Field HOLDER_IS_NEEDED */ public static final String HOLDER_IS_NEEDED = "Holder is needed"; /** Field typeWriter */ private Generator typeWriter = null; /** Field holderWriter */ private Generator holderWriter = null; /** * Constructor. * * @param emitter * @param type * @param symbolTable */ public JavaTypeWriter(Emitter emitter, TypeEntry type, SymbolTable symbolTable) { if (type.isReferenced() && !type.isOnlyLiteralReferenced()) { // Determine what sort of type this is and instantiate // the appropriate Writer. Node node = type.getNode(); boolean isSimpleList = SchemaUtils.isListWithItemType(node); // If it's an array, don't emit a class if (!type.getName().endsWith("[]") && !isSimpleList) { // Generate the proper class for either "complex" or "enumeration" types Vector v = Utils.getEnumerationBaseAndValues(node, symbolTable); if (v != null) { typeWriter = getEnumTypeWriter(emitter, type, v); } else { TypeEntry base = SchemaUtils.getComplexElementExtensionBase(node, symbolTable); if (base == null) { base = SchemaUtils.getComplexElementRestrictionBase( node, symbolTable); } if (base == null) { QName baseQName = SchemaUtils.getSimpleTypeBase(node); if (baseQName != null) { base = symbolTable.getType(baseQName); } } typeWriter = getBeanWriter(emitter, type, base); } } // If the holder is needed (ie., something uses this type as an out or inout // parameter), instantiate the holder writer. if (holderIsNeeded(type)) { holderWriter = getHolderWriter(emitter, type); } if (typeWriter != null && type instanceof Type) { ((Type)type).setGenerated(true); } } } // ctor /** * Write all the service bindnigs: service and testcase. * * @throws IOException */ public void generate() throws IOException { if (typeWriter != null) { typeWriter.generate(); } if (holderWriter != null) { holderWriter.generate(); } } // generate /** * Does anything use this type as an inout/out parameter? Query the Type dynamicVar * * @param entry * @return */ private boolean holderIsNeeded(SymTabEntry entry) { Boolean holderIsNeeded = (Boolean) entry.getDynamicVar(HOLDER_IS_NEEDED); return ((holderIsNeeded != null) && holderIsNeeded.booleanValue()); } // holderIsNeeded /** * getEnumWriter * * @param emitter * @param type * @param v * @return */ protected JavaWriter getEnumTypeWriter(Emitter emitter, TypeEntry type, Vector v) { return new JavaEnumTypeWriter(emitter, type, v); } /** * getBeanWriter * * @param emitter * @param type * @param base * @return */ protected JavaWriter getBeanWriter(Emitter emitter, TypeEntry type, TypeEntry base) { // CONTAINED_ELEM_AND_ATTR Vector elements = type.getContainedElements(); Vector attributes = type.getContainedAttributes(); // If this complexType is referenced in a // fault context, emit a bean-like exception // class if (Utils.isFaultComplex(type)) { return new JavaBeanFaultWriter(emitter, type, elements, base, attributes, getBeanHelperWriter(emitter, type, elements, base, attributes, true)); } return new JavaBeanWriter(emitter, type, elements, base, attributes, getBeanHelperWriter(emitter, type, elements, base, attributes, false)); } /** * getHelperWriter * * @param emitter * @param type * @param elements * @param base * @param attributes * @return */ protected JavaWriter getBeanHelperWriter( Emitter emitter, TypeEntry type, Vector elements, TypeEntry base, Vector attributes, boolean forException) { return new JavaBeanHelperWriter( emitter, type, elements, base, attributes, forException ? JavaBeanFaultWriter.RESERVED_PROPERTY_NAMES : Collections.EMPTY_SET); } /** * getHolderWriter * * @param emitter * @param type * @return */ protected Generator getHolderWriter(Emitter emitter, TypeEntry type) { return new JavaHolderWriter(emitter, type); } public String toString() { return "JavaTypeWriter[typeWriter=" + typeWriter + ",holderWriter=" + holderWriter + "]"; } } // class JavaTypeWriter
6,889
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaGeneratorFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.gen.GeneratorFactory; import org.apache.axis.wsdl.gen.NoopGenerator; import org.apache.axis.wsdl.symbolTable.BaseTypeMapping; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.ContainedAttribute; import org.apache.axis.wsdl.symbolTable.Element; import org.apache.axis.wsdl.symbolTable.ElementDecl; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.MessageEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.PortTypeEntry; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.Type; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.commons.logging.Log; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Fault; import javax.wsdl.Message; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.xml.namespace.QName; import javax.xml.rpc.holders.BooleanHolder; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; /** * This is Wsdl2java's implementation of the GeneratorFactory */ public class JavaGeneratorFactory implements GeneratorFactory { private static final Log log = LogFactory.getLog(JavaGeneratorFactory.class.getName()); /** Field emitter */ protected Emitter emitter; /** Field symbolTable */ protected SymbolTable symbolTable; /** Field COMPLEX_TYPE_FAULT */ public static String COMPLEX_TYPE_FAULT = "ComplexTypeFault"; /** Field EXCEPTION_CLASS_NAME */ public static String EXCEPTION_CLASS_NAME = "ExceptionClassName"; /** Field EXCEPTION_DATA_TYPE */ public static String EXCEPTION_DATA_TYPE = "ExceptionDataType"; /* Name suffixes for collision */ private static final String SERVICE_SUFFIX = "_Service"; private static final String PORT_TYPE_SUFFIX = "_PortType"; // "_Port" (Axis classic) --> "_PortType" (JAX-RPC 1.1) private static final String TYPE_SUFFIX = "_Type"; private static final String ELEMENT_SUFFIX = "_Element"; // "_ElemType (Axis classic) --> "_Element" (JAX-RPC 1.1) private static final String EXCEPTION_SUFFIX = "_Exception"; private static final String BINDING_SUFFIX = "_Binding"; /** * Default constructor. Note that this class is unusable until setEmitter * is called. */ public JavaGeneratorFactory() { addGenerators(); } // ctor /** * Constructor JavaGeneratorFactory * * @param emitter */ public JavaGeneratorFactory(Emitter emitter) { this.emitter = emitter; addGenerators(); } // ctor /** * Method setEmitter * * @param emitter */ public void setEmitter(Emitter emitter) { this.emitter = emitter; } // setEmitter /** * Method addGenerators */ private void addGenerators() { addMessageGenerators(); addPortTypeGenerators(); addBindingGenerators(); addServiceGenerators(); addTypeGenerators(); addDefinitionGenerators(); } // addGenerators /** * These addXXXGenerators are called by the constructor. * If an extender of this factory wants to CHANGE the set * of generators that are called per WSDL construct, they * should override these addXXXGenerators methods. If all * an extender wants to do is ADD a generator, then the * extension should simply call addGenerator. * (NOTE: It doesn't quite work this way, yet. Only the * Definition generators fit this model at this point in * time.) */ protected void addMessageGenerators() { } // addMessageGenerators /** * Method addPortTypeGenerators */ protected void addPortTypeGenerators() { } // addPortTypeGenerators /** * Method addBindingGenerators */ protected void addBindingGenerators() { } // addBindingGenerators /** * Method addServiceGenerators */ protected void addServiceGenerators() { } // addServiceGenerators /** * Method addTypeGenerators */ protected void addTypeGenerators() { } // addTypeGenerators /** * Method addDefinitionGenerators */ protected void addDefinitionGenerators() { addGenerator(Definition.class, JavaDefinitionWriter.class); // for faults addGenerator(Definition.class, JavaDeployWriter.class); // for deploy.wsdd addGenerator(Definition.class, JavaUndeployWriter.class); // for undeploy.wsdd addGenerator(Definition.class, JavaBuildFileWriter.class); //add a build file writer } // addDefinitionGenerators /** * Do the Wsdl2java generator pass: * - resolve name clashes * - construct signatures * * @param def * @param symbolTable */ public void generatorPass(Definition def, SymbolTable symbolTable) { this.symbolTable = symbolTable; javifyNames(symbolTable); setFaultContext(symbolTable); resolveNameClashes(symbolTable); determineInterfaceNames(symbolTable); if (emitter.isAllWanted()) { setAllReferencesToTrue(); } else { ignoreNonSOAPBindings(symbolTable); } constructSignatures(symbolTable); determineIfHoldersNeeded(symbolTable); } // generatorPass /** Since Wsdl2java doesn't emit anything for Messages, return the No-op generator. */ private Writers messageWriters = new Writers(); /** * Method getGenerator * * @param message * @param symbolTable * @return */ public Generator getGenerator(Message message, SymbolTable symbolTable) { if (include(message.getQName())) { MessageEntry mEntry = symbolTable.getMessageEntry(message.getQName()); messageWriters.addStuff(new NoopGenerator(), mEntry, symbolTable); return messageWriters; } else { return new NoopGenerator(); } } // getGenerator /** Return Wsdl2java's JavaPortTypeWriter object. */ private Writers portTypeWriters = new Writers(); /** * Method getGenerator * * @param portType * @param symbolTable * @return */ public Generator getGenerator(PortType portType, SymbolTable symbolTable) { if (include(portType.getQName())) { PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(portType.getQName()); portTypeWriters.addStuff(new NoopGenerator(), ptEntry, symbolTable); return portTypeWriters; } else { return new NoopGenerator(); } } // getGenerator /** Return Wsdl2java's JavaBindingWriter object. */ protected Writers bindingWriters = new Writers(); /** * Method getGenerator * * @param binding * @param symbolTable * @return */ public Generator getGenerator(Binding binding, SymbolTable symbolTable) { if (include(binding.getQName())) { Generator writer = new JavaBindingWriter(emitter, binding, symbolTable); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); bindingWriters.addStuff(writer, bEntry, symbolTable); return bindingWriters; } else { return new NoopGenerator(); } } // getGenerator /** Return Wsdl2java's JavaServiceWriter object. */ protected Writers serviceWriters = new Writers(); /** * Method getGenerator * * @param service * @param symbolTable * @return */ public Generator getGenerator(Service service, SymbolTable symbolTable) { if (include(service.getQName())) { Generator writer = new JavaServiceWriter(emitter, service, symbolTable); ServiceEntry sEntry = symbolTable.getServiceEntry(service.getQName()); serviceWriters.addStuff(writer, sEntry, symbolTable); return serviceWriters; } else { return new NoopGenerator(); } } // getGenerator /** Return Wsdl2java's JavaTypeWriter object. */ private Writers typeWriters = new Writers(); /** * Method getGenerator * * @param type * @param symbolTable * @return */ public Generator getGenerator(TypeEntry type, SymbolTable symbolTable) { if (include(type.getQName())) { Generator writer = new JavaTypeWriter(emitter, type, symbolTable); typeWriters.addStuff(writer, type, symbolTable); return typeWriters; } else { return new NoopGenerator(); } } // getGenerator /** Return Wsdl2java's JavaDefinitionWriter object. */ private Writers defWriters = new Writers(); /** * Method getGenerator * * @param definition * @param symbolTable * @return */ public Generator getGenerator(Definition definition, SymbolTable symbolTable) { if (include(definition.getQName())) { defWriters.addStuff(null, definition, symbolTable); return defWriters; } else { return new NoopGenerator(); } } // getGenerator // Hack class just to play with the idea of adding writers /** * Class Writers * * @version %I%, %G% */ protected class Writers implements Generator { /** Field writers */ Vector writers = new Vector(); /** Field symbolTable */ SymbolTable symbolTable = null; /** Field baseWriter */ Generator baseWriter = null; // entry or def, but not both, will be a parameter. /** Field entry */ SymTabEntry entry = null; /** Field def */ Definition def = null; /** * Method addGenerator * * @param writer */ public void addGenerator(Class writer) { writers.add(writer); } // addWriter /** * Method addStuff * * @param baseWriter * @param entry * @param symbolTable */ public void addStuff(Generator baseWriter, SymTabEntry entry, SymbolTable symbolTable) { this.baseWriter = baseWriter; this.entry = entry; this.symbolTable = symbolTable; } // addStuff /** * Method addStuff * * @param baseWriter * @param def * @param symbolTable */ public void addStuff(Generator baseWriter, Definition def, SymbolTable symbolTable) { this.baseWriter = baseWriter; this.def = def; this.symbolTable = symbolTable; } // addStuff /** * Method generate * * @throws IOException */ public void generate() throws IOException { if (baseWriter != null) { baseWriter.generate(); } Class[] formalArgs; Object[] actualArgs; if (entry != null) { formalArgs = new Class[]{Emitter.class, entry.getClass(), SymbolTable.class}; actualArgs = new Object[]{emitter, entry, symbolTable}; } else { formalArgs = new Class[]{Emitter.class, Definition.class, SymbolTable.class}; actualArgs = new Object[]{emitter, def, symbolTable}; } for (int i = 0; i < writers.size(); ++i) { Class wClass = (Class) writers.get(i); Generator gen; try { Constructor ctor = wClass.getConstructor(formalArgs); gen = (Generator) ctor.newInstance(actualArgs); } catch (Throwable t) { throw new IOException(Messages.getMessage("exception01", t.getMessage())); } gen.generate(); } } // generate public String toString() { return "Writers[baseWriter=" + baseWriter + ",writers=" + writers + ",entry.name=" + (entry == null ? "N/A" : entry.getName()) + "]"; } } // class Writers /** * Method addGenerator * * @param wsdlClass * @param generator */ public void addGenerator(Class wsdlClass, Class generator) { if (log.isDebugEnabled()) { log.debug("Adding generator for " + wsdlClass.getName() + ": " + generator.getName()); } // This is just a hack right now... it just works with Service if (Message.class.isAssignableFrom(wsdlClass)) { messageWriters.addGenerator(generator); } else if (PortType.class.isAssignableFrom(wsdlClass)) { portTypeWriters.addGenerator(generator); } else if (Binding.class.isAssignableFrom(wsdlClass)) { bindingWriters.addGenerator(generator); } else if (Service.class.isAssignableFrom(wsdlClass)) { serviceWriters.addGenerator(generator); } else if (TypeEntry.class.isAssignableFrom(wsdlClass)) { typeWriters.addGenerator(generator); } else if (Definition.class.isAssignableFrom(wsdlClass)) { defWriters.addGenerator(generator); } } // addGenerator /** * Fill in the names of each SymTabEntry with the javaified name. * Note: This method also ensures that anonymous types are * given unique java type names. * * @param symbolTable */ protected void javifyNames(SymbolTable symbolTable) { int uniqueNum = 0; HashMap anonQNames = new HashMap(); Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (entry.getName() != null) { continue; } // Use the type or the referenced type's QName to generate the java name. if (entry instanceof TypeEntry) { uniqueNum = javifyTypeEntryName(symbolTable, (TypeEntry) entry, anonQNames, uniqueNum); } // If it is not a type, then use this entry's QName to // generate its name. else { entry.setName(emitter.getJavaName(entry.getQName())); } } } } // javifyNames /** Refactored to call recursively for JAX-RPC 1.1 spec 4.2.5. */ protected int javifyTypeEntryName(SymbolTable symbolTable, TypeEntry entry, HashMap anonQNames, int uniqueNum) { TypeEntry tEntry = entry; String dims = tEntry.getDimensions(); TypeEntry refType = tEntry.getRefType(); while (refType != null) { tEntry = refType; dims += tEntry.getDimensions(); refType = tEntry.getRefType(); } TypeEntry te = tEntry; while (te != null) { TypeEntry base = SchemaUtils.getBaseType(te, symbolTable); if (base == null) break; uniqueNum = javifyTypeEntryName(symbolTable, base, anonQNames, uniqueNum); if (Utils.getEnumerationBaseAndValues(te.getNode(), symbolTable) == null &&SchemaUtils.getComplexElementExtensionBase(te.getNode(), symbolTable) == null && te.getContainedAttributes() == null) { if(!SchemaUtils.isSimpleTypeWithUnion(te.getNode())) { if (base.isSimpleType()) { // Case 1: // <simpleType name="mySimpleStringType"> // <restriction base="xs:string"> // </restriction> // </simpleType> te.setSimpleType(true); te.setName(base.getName()); te.setRefType(base); } if (base.isBaseType()) { // Case 2: // <simpleType name="FooString"> // <restriction base="foo:mySimpleStringType"> // </restriction> // </simpleType> te.setBaseType(true); te.setName(base.getName()); te.setRefType(base); } } } if (!te.isSimpleType()) break; te = base; } // Need to javify the ref'd TypeEntry if it was not // already processed if (tEntry.getName() == null) { boolean processed = false; // true if the java name is already determined // Get the QName of the ref'd TypeEntry, which // is will be used to javify the name QName typeQName = tEntry.getQName(); // In case of <xsd:list itemType="...">, // set typeQName to the value of the itemType attribute. QName itemType = SchemaUtils.getListItemType(tEntry.getNode()); if (itemType != null) { // Get the typeEntry so we know the absolute base type TypeEntry itemEntry = symbolTable.getTypeEntry(itemType, false); // TODO - If the itemEntry is not found, we need to throw // an exception. "Item is referenced, but not defined" javifyTypeEntryName(symbolTable, itemEntry, anonQNames, uniqueNum); // Grab the referenced type, If it's there. TypeEntry refedEntry = itemEntry.getRefType(); QName baseName = refedEntry == null ? itemEntry.getQName() : refedEntry.getQName(); typeQName = new QName(baseName.getNamespaceURI(), baseName.getLocalPart() + "[]"); } if (emitter.isDeploy()) { Class class1 = (Class) emitter.getQName2ClassMap().get(typeQName); if (class1 != null && !class1.isArray()) { tEntry.setName(getJavaClassName(class1)); processed = true; } } if (!processed) { if ((typeQName.getLocalPart(). indexOf(SymbolTable.ANON_TOKEN) < 0)) { // Normal Case: The ref'd type is not anonymous // Simply construct the java name from // the qName tEntry.setName(emitter.getJavaName(typeQName)); } else { // This is an anonymous type name. // Axis uses '>' as a nesting token to generate // unique qnames for anonymous types. // Only consider the localName after the last '>' // when generating the java name // String localName = typeQName.getLocalPart(); // localName = // localName.substring( // localName.lastIndexOf( // SymbolTable.ANON_TOKEN)+1); // typeQName = new QName(typeQName.getNamespaceURI(), // localName); String localName = typeQName.getLocalPart(); // Check to see if this is an anonymous type, // if it is, replace Axis' ANON_TOKEN with // an underscore to make sure we don't run // into name collisions with similarly named // non-anonymous types StringBuffer sb = new StringBuffer(localName); int aidx; while ((aidx = sb.toString().indexOf(SymbolTable.ANON_TOKEN)) > -1) { sb.replace(aidx, aidx + SymbolTable.ANON_TOKEN.length(), ""); char c = sb.charAt(aidx); if (Character.isLetter(c) && Character.isLowerCase(c)) { sb.setCharAt(aidx, Character.toUpperCase(c)); } } localName = sb.toString(); typeQName = new QName(typeQName.getNamespaceURI(), localName); if (emitter.isTypeCollisionProtection() && !emitter.getNamespaceExcludes().contains(new NamespaceSelector(typeQName.getNamespaceURI()))) { // If there is already an existing type, // there will be a collision. // If there is an existing anon type, // there will be a collision. // In both cases, mangle the name. if (symbolTable.getType(typeQName) != null || anonQNames.get(typeQName) != null) { localName += "Type" + uniqueNum++; typeQName = new QName(typeQName.getNamespaceURI(), localName); } anonQNames.put(typeQName, typeQName); } // Now set the name with the constructed qname tEntry.setName(emitter.getJavaName(typeQName)); } } // if (!processed) Vector elements = tEntry.getContainedElements(); if (elements != null) { for (int i = 0; i < elements.size(); i++) { ElementDecl elem = (ElementDecl) elements.get(i); String varName = emitter.getJavaVariableName(typeQName, elem.getQName(), true); elem.setName(varName); } } Vector attributes = tEntry.getContainedAttributes(); if (attributes != null) { for (int i = 0; i < attributes.size(); i++) { ContainedAttribute attr = (ContainedAttribute) attributes.get(i); String varName = emitter.getJavaVariableName(typeQName, attr.getQName(), false); attr.setName(varName); } } } // Set the entry with the same name as the ref'd entry // but add the appropriate amount of dimensions entry.setName(tEntry.getName() + dims); return uniqueNum; } /** * Gets class name from Java class. * If the class is an array, get its component type's name * @param clazz a java class * @return the class name in string */ private static String getJavaClassName(Class clazz) { Class class1 = clazz; while (class1.isArray()) { class1 = class1.getComponentType(); } String name = class1.getName(); name.replace('$', '.'); return name; } /** * setFaultContext: * Processes the symbol table and sets the COMPLEX_TYPE_FAULT * on each TypeEntry that is a complexType and is referenced in * a fault message. TypeEntries that are the base or derived * from such a TypeEntry are also marked with COMPLEX_TYPE_FAULT. * The containing MessageEntry is marked with cOMPLEX_TYPE_FAULT, and * all MessageEntries for faults are tagged with the * EXCEPTION_CLASS_NAME variable, which indicates the java exception * class name. * * @param symbolTable SymbolTable */ private void setFaultContext(SymbolTable symbolTable) { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); // Inspect each BindingEntry in the Symbol Table if (entry instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) entry; HashMap allOpFaults = bEntry.getFaults(); Iterator ops = allOpFaults.values().iterator(); // set the context for all faults for this binding. while (ops.hasNext()) { ArrayList faults = (ArrayList) ops.next(); for (int j = 0; j < faults.size(); ++j) { FaultInfo info = (FaultInfo) faults.get(j); setFaultContext(info, symbolTable); } } } } } } // setFaultContext /** * setFaultContext: * Helper routine for the setFaultContext method above. * Examines the indicated fault and sets COMPLEX_TYPE_FAULT * EXCEPTION_DATA_TYPE and EXCEPTION_CLASS_NAME as appropriate. * * @param fault FaultInfo to analyze * @param symbolTable SymbolTable */ private void setFaultContext(FaultInfo fault, SymbolTable symbolTable) { QName faultXmlType = null; Vector parts = new Vector(); // Get the parts of the fault's message. // An IOException is thrown if the parts cannot be // processed. Skip such parts for this analysis try { symbolTable.getParametersFromParts( parts, fault.getMessage().getOrderedParts(null), false, fault.getName(), null); } catch (IOException e) { } // Inspect each TypeEntry referenced in a Fault Message Part String exceptionClassName = null; for (int j = 0; j < parts.size(); j++) { TypeEntry te = ((Parameter) (parts.elementAt(j))).getType(); // If the TypeEntry is an element, advance to the type. // This occurs if the message part uses the element= attribute TypeEntry elementTE = null; if (te instanceof Element) { elementTE = te; te = te.getRefType(); } // remember the QName of the type. faultXmlType = te.getQName(); // Determine if the te should be processed using the // simple type mapping or the complex type mapping // NOTE: treat array types as simple types if ((te.getBaseType() != null) || te.isSimpleType() || ((te.getDimensions().length() > 0) && (te.getRefType().getBaseType() != null))) { // Simple Type Exception } else { // Complex Type Exception if (!Utils.isFaultComplex(te)) { // Mark the type as a complex type fault te.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE); if (elementTE != null) { te.setDynamicVar( JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE); } // Mark all derived types as Complex Faults HashSet derivedSet = org.apache.axis.wsdl.symbolTable.Utils.getDerivedTypes( te, symbolTable); Iterator derivedI = derivedSet.iterator(); while (derivedI.hasNext()) { TypeEntry derivedTE = (TypeEntry) derivedI.next(); derivedTE.setDynamicVar( JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE); } // Mark all base types as Complex Faults TypeEntry base = SchemaUtils.getComplexElementExtensionBase(te.getNode(), symbolTable); while (base != null) { base.setDynamicVar( JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE); base = SchemaUtils.getComplexElementExtensionBase( base.getNode(), symbolTable); } } // The exception class name is the name of the type exceptionClassName = te.getName(); } } String excName = getExceptionJavaNameHook(fault.getMessage().getQName()); // for derived class if (excName != null) { exceptionClassName = excName; } // Set the name of the exception and // whether the exception is a complex type MessageEntry me = symbolTable.getMessageEntry(fault.getMessage().getQName()); if (me != null) { me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_DATA_TYPE, faultXmlType); if (exceptionClassName != null) { me.setDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT, Boolean.TRUE); me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_CLASS_NAME, exceptionClassName); } else { me.setDynamicVar(JavaGeneratorFactory.EXCEPTION_CLASS_NAME, emitter.getJavaName(me.getQName())); } } } protected String getExceptionJavaNameHook(QName qname) { return null; } /** * Method determineInterfaceNames * * @param symbolTable */ protected void determineInterfaceNames(SymbolTable symbolTable) { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (entry instanceof BindingEntry) { // The SEI (Service Endpoint Interface) name // is always the portType name. BindingEntry bEntry = (BindingEntry) entry; PortTypeEntry ptEntry = symbolTable.getPortTypeEntry( bEntry.getBinding().getPortType().getQName()); String seiName = getServiceEndpointInterfaceJavaNameHook(ptEntry, bEntry); if (seiName == null) { seiName = ptEntry.getName(); } bEntry.setDynamicVar(JavaBindingWriter.INTERFACE_NAME, seiName); } else if (entry instanceof ServiceEntry) { ServiceEntry sEntry = (ServiceEntry) entry; String siName = getServiceInterfaceJavaNameHook(sEntry); // for derived class if (siName != null) { sEntry.setName(siName); } Service service = sEntry.getService(); Map portMap = service.getPorts(); Iterator portIterator = portMap.values().iterator(); while (portIterator.hasNext()) { Port p = (Port) portIterator.next(); Binding binding = p.getBinding(); BindingEntry bEntry = symbolTable.getBindingEntry(binding.getQName()); // If this isn't a SOAP binding, skip it if (bEntry.getBindingType() != BindingEntry.TYPE_SOAP) { continue; } String portName = getPortJavaNameHook(p.getName()); // for derived class if (portName != null) { bEntry.setDynamicVar(JavaServiceWriter.PORT_NAME + ":" + p.getName(), portName); } } } } } } // determineInterfaceNames protected String getServiceEndpointInterfaceJavaNameHook(PortTypeEntry ptEntry, BindingEntry bEntry) { return null; } protected String getServiceInterfaceJavaNameHook(ServiceEntry sEntry) { return null; } protected String getPortJavaNameHook(String portName) { return null; } /** * Messages, PortTypes, Bindings, and Services can share the same name. If they do in this * Definition, force their names to be suffixed with _PortType and _Service, respectively. * * @param symbolTable */ protected void resolveNameClashes(SymbolTable symbolTable) { // Keep a list of anonymous types so we don't try to resolve them twice. HashSet anonTypes = new HashSet(); List collisionCandidates = new ArrayList(); // List of vector of SymbolTable entry List localParts = new ArrayList(); // all localparts in all symboltable entries for (Iterator i = symbolTable.getHashMap().keySet().iterator(); i.hasNext(); ) { QName qName = (QName)i.next(); String localPart = qName.getLocalPart(); if (!localParts.contains(localPart)) localParts.add(localPart); } Map pkg2NamespacesMap = emitter.getNamespaces().getPkg2NamespacesMap(); for (Iterator i = pkg2NamespacesMap.values().iterator(); i.hasNext(); ) { Vector namespaces = (Vector)i.next(); // namepaces mapped to same package // Combine entry vectors, which have the same entry name, into a new entry vector. for (int j = 0; j < localParts.size(); j++) { Vector v = new Vector(); for (int k = 0; k < namespaces.size(); k++) { QName qName = new QName((String)namespaces.get(k), (String)localParts.get(j)); if (symbolTable.getHashMap().get(qName) != null) { v.addAll((Vector)symbolTable.getHashMap().get(qName)); } } if(v.size()>0) { collisionCandidates.add(v); } } } Iterator it = collisionCandidates.iterator(); while (it.hasNext()) { Vector v = new Vector( (Vector) it.next()); // New vector we can temporarily add to it // Remove MessageEntries since they are not mapped int index = 0; while (index < v.size()) { if (v.elementAt(index) instanceof MessageEntry) { // Need to resolve a Exception message. MessageEntry msgEntry = (MessageEntry) v.elementAt(index); // AXIS-2900: Only simple type faults generate additional classes; message entries for // complex type faults don't cause any collisions. if (Utils.isFaultComplex(msgEntry) || msgEntry.getDynamicVar(EXCEPTION_CLASS_NAME) == null) { v.removeElementAt(index); } else { index++; } } else { index++; } } if (v.size() > 1) { boolean resolve = true; // Common Special Case: // If a Type and Element have the same QName, and the Element // references the Type, then they are the same class so // don't bother mangling. if (v.size() == 2 && ((v.elementAt(0) instanceof Element && v.elementAt(1) instanceof Type) || (v.elementAt(1) instanceof Element && v.elementAt(0) instanceof Type))) { Element e; Type t; if (v.elementAt(0) instanceof Element) { e = (Element) v.elementAt(0); t = (Type) v.elementAt(1); } else { e = (Element) v.elementAt(1); t = (Type) v.elementAt(0); } BooleanHolder forElement = new BooleanHolder(); QName eType = Utils.getTypeQName(e.getNode(), forElement, false); if ((eType != null) && !forElement.value && eType.equals(t.getQName())) { resolve = false; } } // Other Special Case: // If the names are already different, no mangling is needed. if (resolve) { resolve = false; // Assume false String name = null; for (int i = 0; (i < v.size()) && !resolve; ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if ((entry instanceof MessageEntry) || (entry instanceof BindingEntry)) { // Need to resolve a exception class name String exceptionClassName = (String) entry.getDynamicVar(EXCEPTION_CLASS_NAME); if (exceptionClassName != null) { if (name == null) { name = exceptionClassName; } else if (name.equals(exceptionClassName)) { resolve = true; } } } else if (name == null) { name = entry.getName(); } else if (name.equals(entry.getName())) { resolve = true; // Need to do resolution } } } // Full Mangle if resolution is necessary. if (resolve) { boolean firstType = true; for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (entry instanceof Element) { mangleName(entry, ELEMENT_SUFFIX); // If this global element was defined using // an anonymous type, then need to change the // java name of the anonymous type to match. QName anonQName = new QName(entry.getQName().getNamespaceURI(), SymbolTable.ANON_TOKEN + entry.getQName().getLocalPart()); TypeEntry anonType = symbolTable.getType(anonQName); if (anonType != null) { anonType.setName(entry.getName()); anonTypes.add(anonType); } } else if (entry instanceof TypeEntry) { // Search all other types for java names that match this one. // The sameJavaClass method returns true if the java names are // the same (ignores [] ). if (firstType) { firstType = false; Iterator types = symbolTable.getTypeIndex().values().iterator(); while (types.hasNext()) { TypeEntry type = (TypeEntry) types.next(); if ((type != entry) && (type.getBaseType() == null) && sameJavaClass(entry.getName(), type.getName())) { v.add(type); } } } // If this is an anonymous type, it's name was resolved in // the previous if block. Don't reresolve it. if (!anonTypes.contains(entry)) { // In case that other entry in name collision among // PortTypeEntry, ServiceEntry and BindingEntry boolean needResolve = false; // check collision of TypeEntry with PortTypeEntry, ServiceEtnry and/or BindingEntry for (int j = 0; j < v.size(); j++) { SymTabEntry e = (SymTabEntry) v.elementAt(j); if ((e instanceof PortTypeEntry || e instanceof ServiceEntry || e instanceof BindingEntry)) { needResolve = true; break; } } if (!needResolve) { continue; } // Appended Suffix for avoiding name collisions (JAX-RPC 1.1) boolean isComplexTypeFault = Utils.isFaultComplex(entry); mangleName(entry, isComplexTypeFault ? EXCEPTION_SUFFIX : TYPE_SUFFIX); // should update the class name of ElementEntry which references this type entry Map elementIndex = symbolTable.getElementIndex(); List elements = new ArrayList(elementIndex.values()); for (int j = 0; j < elementIndex.size(); j++) { TypeEntry te = (TypeEntry) elements.get(j); TypeEntry ref = te.getRefType(); if (ref != null && entry.getQName().equals(ref.getQName())) { te.setName(entry.getName()); } } // Need to resolve a complex-type exception message. if (isComplexTypeFault) { // SHOULD update the exception class name of a referencing message entry. List messageEntries = symbolTable.getMessageEntries(); for (int j = 0; j < messageEntries.size(); j++) { MessageEntry messageEntry = (MessageEntry)messageEntries.get(j); if (Utils.isFaultComplex(messageEntry)) { QName exceptionDataType = (QName)messageEntry.getDynamicVar(EXCEPTION_DATA_TYPE); if (((TypeEntry)entry).getQName().equals(exceptionDataType)) { String className = (String)messageEntry.getDynamicVar(EXCEPTION_CLASS_NAME); messageEntry.setDynamicVar(EXCEPTION_CLASS_NAME, className + EXCEPTION_SUFFIX); } } } } } } else if (entry instanceof PortTypeEntry) { mangleName(entry, PORT_TYPE_SUFFIX); // "_Port" --> "_PortType" for JAX-RPC 1.1 } else if (entry instanceof ServiceEntry) { mangleName(entry, SERVICE_SUFFIX); } else if (entry instanceof MessageEntry) { if (!Utils.isFaultComplex(entry)) { String exceptionClassName = (String) entry.getDynamicVar(EXCEPTION_CLASS_NAME); entry.setDynamicVar(EXCEPTION_CLASS_NAME, exceptionClassName + EXCEPTION_SUFFIX); } } // else if (entry instanceof MessageEntry) { // we don't care about messages // } else if (entry instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) entry; // If there is no literal use, then we never see a // class named directly from the binding name. They // all have suffixes: Stub, Skeleton, Impl. // If there IS literal use, then the SDI will be // named after the binding name, so there is the // possibility of a name clash. if (bEntry.hasLiteral()) { mangleName(entry, BINDING_SUFFIX); } } } } } } } // resolveNameClashes /** * Change the type name of the given symbol table entry into a mangled * form using the given suffix. * * @param entry * @param suffix */ private void mangleName(SymTabEntry entry, String suffix) { String name = entry.getName(); int index = name.indexOf("["); String newName; if (index >= 0) { String pre = name.substring(0, index); String post = name.substring(index); newName = pre + suffix + post; } else { newName = name + suffix; } entry.setName(newName); if (log.isDebugEnabled()) { log.debug("Symbol table of type " + entry.getClass().getName() + " mangled: " + name + " -> " + newName); } } /** * Returns true if same java class, ignore [] * * @param one * @param two * @return */ private boolean sameJavaClass(String one, String two) { int index1 = one.indexOf("["); int index2 = two.indexOf("["); if (index1 > 0) { one = one.substring(0, index1); } if (index2 > 0) { two = two.substring(0, index2); } return one.equals(two); } /** * The --all flag is set on the command line (or generateAll(true) is called * on WSDL2Java). Set all symbols as referenced (except nonSOAP bindings * which we don't know how to deal with). */ protected void setAllReferencesToTrue() { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if ((entry instanceof BindingEntry) && ((BindingEntry) entry).getBindingType() != BindingEntry.TYPE_SOAP) { entry.setIsReferenced(false); } else { entry.setIsReferenced(true); } } } } // setAllReferencesToTrue /** * If a binding's type is not TYPE_SOAP, then we don't use that binding * or that binding's portType. * * @param symbolTable */ protected void ignoreNonSOAPBindings(SymbolTable symbolTable) { // Look at all uses of the portTypes. If none of the portType's bindings are of type // TYPE_SOAP, then turn off that portType's isReferenced flag. Vector unusedPortTypes = new Vector(); Vector usedPortTypes = new Vector(); Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (entry instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) entry; Binding binding = bEntry.getBinding(); PortType portType = binding.getPortType(); PortTypeEntry ptEntry = symbolTable.getPortTypeEntry(portType.getQName()); if (bEntry.getBindingType() == BindingEntry.TYPE_SOAP) { // If a binding is of type TYPE_SOAP, then mark its portType used // (ie., add it to the usedPortTypes list. If the portType was // previously marked as unused, unmark it (in other words, remove it // from the unusedPortTypes list). usedPortTypes.add(ptEntry); if (unusedPortTypes.contains(ptEntry)) { unusedPortTypes.remove(ptEntry); } } else { bEntry.setIsReferenced(false); // If a binding is not of type TYPE_SOAP, then mark its portType as // unused ONLY if it hasn't already been marked as used. if (!usedPortTypes.contains(ptEntry)) { unusedPortTypes.add(ptEntry); } } } } } // Go through all the portTypes that are marked as unused and set their isReferenced flags // to false. for (int i = 0; i < unusedPortTypes.size(); ++i) { PortTypeEntry ptEntry = (PortTypeEntry) unusedPortTypes.get(i); ptEntry.setIsReferenced(false); } } // ignoreNonSOAPBindings /** * Method constructSignatures * * @param symbolTable */ protected void constructSignatures(SymbolTable symbolTable) { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); if (entry instanceof BindingEntry) { BindingEntry bEntry = (BindingEntry) entry; Binding binding = bEntry.getBinding(); PortType portType = binding.getPortType(); Iterator operations = portType.getOperations().iterator(); while (operations.hasNext()) { Operation operation = (Operation) operations.next(); String wsdlOpName = operation.getName(); OperationType type = operation.getStyle(); String javaOpName = getOperationJavaNameHook(bEntry, wsdlOpName); // for derived class if (javaOpName == null) { javaOpName = operation.getName(); } Parameters parameters = bEntry.getParameters(operation); if (OperationType.SOLICIT_RESPONSE.equals(type)) { parameters.signature = " // " + Messages.getMessage("invalidSolResp00", javaOpName); System.err.println( Messages.getMessage("invalidSolResp00", javaOpName)); } else if (OperationType.NOTIFICATION.equals(type)) { parameters.signature = " // " + Messages.getMessage("invalidNotif00", javaOpName); System.err.println( Messages.getMessage("invalidNotif00", javaOpName)); } else { // ONE_WAY or REQUEST_RESPONSE if (parameters != null) { String returnType = getReturnTypeJavaNameHook(bEntry, wsdlOpName); if (returnType != null) { if (parameters.returnParam != null) { // 'void' return type??? parameters.returnParam.getType().setName(returnType); } } for (int j = 0; j < parameters.list.size(); ++j) { Parameter p = (Parameter) parameters.list.get(j); String paramType = getParameterTypeJavaNameHook(bEntry, wsdlOpName, j); if (paramType != null) { p.getType().setName(paramType); } } parameters.signature = constructSignature(parameters, javaOpName); } } } } } } } // constructSignatures protected String getOperationJavaNameHook(BindingEntry bEntry, String wsdlOpName) { return null; } protected String getReturnTypeJavaNameHook(BindingEntry bEntry, String wsdlOpName) { return null; } protected String getParameterTypeJavaNameHook(BindingEntry bEntry, String wsdlOpName, int pos) { return null; } /** * Construct the signature, which is used by both the interface and the stub. * * @param parms * @param opName * @return */ private String constructSignature(Parameters parms, String opName) { String name = JavaUtils.xmlNameToJava(opName); String ret = "void"; if ((parms != null) && (parms.returnParam != null)) { ret = Utils.getParameterTypeName(parms.returnParam); } String signature = " public " + ret + " " + name + "("; boolean needComma = false; for (int i = 0; (parms != null) && (i < parms.list.size()); ++i) { Parameter p = (Parameter) parms.list.get(i); if (needComma) { signature = signature + ", "; } else { needComma = true; } String javifiedName = JavaUtils.xmlNameToJava(p.getName()); if (p.getMode() == Parameter.IN) { signature += Utils.getParameterTypeName(p) + " " + javifiedName; } else { signature += Utils.holder(p, emitter) + " " + javifiedName; } } signature = signature + ") throws java.rmi.RemoteException"; if ((parms != null) && (parms.faults != null)) { // Collect the list of faults into a single string, separated by commas. Iterator i = parms.faults.values().iterator(); while (i.hasNext()) { Fault fault = (Fault) i.next(); String exceptionName = Utils.getFullExceptionName(fault.getMessage(), symbolTable); if (exceptionName != null) { signature = signature + ", " + exceptionName; } } } return signature; } // constructSignature /** * Find all inout/out parameters and add a flag to the Type of that parameter saying a holder * is needed. * * @param symbolTable */ protected void determineIfHoldersNeeded(SymbolTable symbolTable) { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { if (v.get(i) instanceof BindingEntry) { // If entry is a BindingEntry, look at all the Parameters // in its portType BindingEntry bEntry = (BindingEntry) v.get(i); // PortTypeEntry ptEntry = // symbolTable.getPortTypeEntry(bEntry.getBinding().getPortType().getQName()); Iterator operations = bEntry.getParameters().values().iterator(); while (operations.hasNext()) { Parameters parms = (Parameters) operations.next(); for (int j = 0; j < parms.list.size(); ++j) { Parameter p = (Parameter) parms.list.get(j); // If the given parameter is an inout or out parameter, then // set a HOLDER_IS_NEEDED flag using the dynamicVar design. if (p.getMode() != Parameter.IN) { TypeEntry typeEntry = p.getType(); typeEntry.setDynamicVar( JavaTypeWriter.HOLDER_IS_NEEDED, Boolean.TRUE); // If this is a complex then set the HOLDER_IS_NEEDED // for the reftype too. if (!typeEntry.isSimpleType() && (typeEntry.getRefType() != null)) { typeEntry.getRefType().setDynamicVar( JavaTypeWriter.HOLDER_IS_NEEDED, Boolean.TRUE); } // If the type is a DefinedElement, need to // set HOLDER_IS_NEEDED on the anonymous type. QName anonQName = SchemaUtils.getElementAnonQName( p.getType().getNode()); if (anonQName != null) { TypeEntry anonType = symbolTable.getType(anonQName); if (anonType != null) { anonType.setDynamicVar( JavaTypeWriter.HOLDER_IS_NEEDED, Boolean.TRUE); } } } } } } } } } // determineIfHoldersNeeded /** * Get TypeMapping to use for translating * QNames to java base types */ BaseTypeMapping btm = null; /** * Method setBaseTypeMapping * * @param btm */ public void setBaseTypeMapping(BaseTypeMapping btm) { this.btm = btm; } /** * Method getBaseTypeMapping * * @return */ public BaseTypeMapping getBaseTypeMapping() { if (btm == null) { btm = new BaseTypeMapping() { public String getBaseName(QName qNameIn) { javax.xml.namespace.QName qName = new javax.xml.namespace.QName(qNameIn.getNamespaceURI(), qNameIn.getLocalPart()); Class cls = emitter.getDefaultTypeMapping().getClassForQName(qName); if (cls == null) { return null; } else { return JavaUtils.getTextClassName(cls.getName()); } } }; } return btm; } /** * Determines whether the QName supplied should be generated by comparing * the namespace for the QName against the included and excluded names. * <ul> * <li>if both the includes and excludes are both empty, * the element is generated</li> * <li>if the namespace is in the includes, * the element is generated</li> * <li>if the namespace is not in the excludes and the includes are empty, * the element will be generated. * <li>if the namespace is only in the excludes, * the element is not generated</li> * <li>if the namespace is not in the includes and the includes are not * empty, the element is not generated</li> * </ul> * @param qName * @return */ protected boolean include(QName qName) { String namespace = (qName != null && qName.getNamespaceURI() != null) ? qName.getNamespaceURI() : ""; boolean doInclude = false; NamespaceSelector selector = new NamespaceSelector(namespace); if (qName == null || emitter == null || emitter.getNamespaceIncludes().contains(selector) || (emitter.getNamespaceIncludes().size() == 0 && !emitter.getNamespaceExcludes().contains(selector))) { doInclude = true; } else { log.info( "excluding code generation for non-included QName:" + qName); } return doInclude; } } // class JavaGeneratorFactory
6,890
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaStubWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.utils.Messages; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.StringUtils; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.CollectionType; import org.apache.axis.wsdl.symbolTable.DefinedType; import org.apache.axis.wsdl.symbolTable.FaultInfo; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.apache.axis.wsdl.symbolTable.DefinedElement; import org.apache.commons.logging.Log; import javax.wsdl.Binding; import javax.wsdl.BindingOperation; import javax.wsdl.Fault; import javax.wsdl.Message; import javax.wsdl.Operation; import javax.wsdl.OperationType; import javax.wsdl.Part; import javax.wsdl.PortType; import javax.wsdl.extensions.soap.SOAPBinding; import javax.wsdl.extensions.soap.SOAPOperation; import javax.wsdl.extensions.soap12.SOAP12Binding; import javax.wsdl.extensions.soap12.SOAP12Operation; import javax.xml.namespace.QName; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.Arrays; import java.util.Comparator; import java.util.Collections; /** * This is Wsdl2java's stub writer. It writes the &lt;BindingName&gt;Stub.java * file which contains the &lt;bindingName&gt;Stub class. */ public class JavaStubWriter extends JavaClassWriter { /** Field log */ protected static Log log = LogFactory.getLog(JavaStubWriter.class.getName()); /** Field bEntry */ private BindingEntry bEntry; /** Field binding */ private Binding binding; /** Field symbolTable */ private SymbolTable symbolTable; // the maximum number of java type <-> qname binding instructions we'll // emit in a single method. This is important for stubs that handle // a large number of schema types, as the generated source can exceed // the size in a single method by the VM. /** Field MAXIMUM_BINDINGS_PER_METHOD */ private static final int MAXIMUM_BINDINGS_PER_METHOD = 100; /** Field modeStrings */ static String[] modeStrings = new String[]{"", "org.apache.axis.description.ParameterDesc.IN", "org.apache.axis.description.ParameterDesc.OUT", "org.apache.axis.description.ParameterDesc.INOUT"}; /** Field styles */ static Map styles = new HashMap(); /** Field uses */ static Map uses = new HashMap(); static { styles.put(Style.DOCUMENT, "org.apache.axis.constants.Style.DOCUMENT"); styles.put(Style.RPC, "org.apache.axis.constants.Style.RPC"); styles.put(Style.MESSAGE, "org.apache.axis.constants.Style.MESSAGE"); styles.put(Style.WRAPPED, "org.apache.axis.constants.Style.WRAPPED"); uses.put(Use.ENCODED, "org.apache.axis.constants.Use.ENCODED"); uses.put(Use.LITERAL, "org.apache.axis.constants.Use.LITERAL"); } /** Field OPERDESC_PER_BLOCK */ static int OPERDESC_PER_BLOCK = 10; /** * Constructor. * * @param emitter * @param bEntry * @param symbolTable */ public JavaStubWriter(Emitter emitter, BindingEntry bEntry, SymbolTable symbolTable) { super(emitter, bEntry.getName() + "Stub", "stub"); this.bEntry = bEntry; this.binding = bEntry.getBinding(); this.symbolTable = symbolTable; } // ctor /** * Returns "extends org.apache.axis.client.Stub ". * * @return */ protected String getExtendsText() { return "extends org.apache.axis.client.Stub "; } // getExtendsText /** * Returns "implements &lt;SEI&gt; ". * * @return */ protected String getImplementsText() { return "implements " + bEntry.getDynamicVar(JavaBindingWriter.INTERFACE_NAME) + " "; } // getImplementsText /** * Write the body of the binding's stub file. * * @param pw * @throws IOException */ protected void writeFileBody(PrintWriter pw) throws IOException { PortType portType = binding.getPortType(); HashSet types = getTypesInPortType(portType); boolean hasMIME = Utils.hasMIME(bEntry); if ((types.size() > 0) || hasMIME) { pw.println( " private java.util.Vector cachedSerClasses = new java.util.Vector();"); pw.println( " private java.util.Vector cachedSerQNames = new java.util.Vector();"); pw.println( " private java.util.Vector cachedSerFactories = new java.util.Vector();"); pw.println( " private java.util.Vector cachedDeserFactories = new java.util.Vector();"); } pw.println(); pw.println( " static org.apache.axis.description.OperationDesc [] _operations;"); pw.println(); writeOperationMap(pw); pw.println(); pw.println(" public " + className + "() throws org.apache.axis.AxisFault {"); pw.println(" this(null);"); pw.println(" }"); pw.println(); pw.println( " public " + className + "(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {"); pw.println(" this(service);"); pw.println(" super.cachedEndpoint = endpointURL;"); pw.println(" }"); pw.println(); pw.println( " public " + className + "(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {"); pw.println(" if (service == null) {"); pw.println( " super.service = new org.apache.axis.client.Service();"); pw.println(" } else {"); pw.println(" super.service = service;"); pw.println(" }"); pw.println(" ((org.apache.axis.client.Service)super.service).setTypeMappingVersion(\"" + emitter.getTypeMappingVersion() + "\");"); List deferredBindings = new ArrayList(); // keep track of how many type mappings we write out int typeMappingCount = 0; if (types.size() > 0) { Iterator it = types.iterator(); while (it.hasNext()) { TypeEntry type = (TypeEntry) it.next(); if (!Utils.shouldEmit(type)) { continue; } // Write out serializer declarations if (typeMappingCount == 0) { writeSerializationDecls( pw, hasMIME, binding.getQName().getNamespaceURI()); } // write the type mapping for this type // writeSerializationInit(pw, type); deferredBindings.add(type); // increase the number of type mappings count typeMappingCount++; } } // Sort the TypeEntry's by their qname. Collections.sort(deferredBindings, new Comparator() { public int compare(Object a, Object b) { TypeEntry type1 = (TypeEntry)a; TypeEntry type2 = (TypeEntry)b; return type1.getQName().toString().compareToIgnoreCase(type2.getQName().toString()); } }); // We need to write out the MIME mapping, even if we don't have // any type mappings if ((typeMappingCount == 0) && hasMIME) { writeSerializationDecls(pw, hasMIME, binding.getQName().getNamespaceURI()); typeMappingCount++; } // track whether the number of bindings exceeds the threshold // that we allow per method. boolean needsMultipleBindingMethods = false; if (deferredBindings.size() < MAXIMUM_BINDINGS_PER_METHOD) { // small number of bindings, just inline them: for (Iterator it = deferredBindings.iterator(); it.hasNext();) { writeSerializationInit(pw, (TypeEntry) it.next()); } } else { needsMultipleBindingMethods = true; int methodCount = calculateBindingMethodCount(deferredBindings); // invoke each of the soon-to-be generated addBindings methods // from the constructor. for (int i = 0; i < methodCount; i++) { pw.println(" addBindings" + i + "();"); } } pw.println(" }"); pw.println(); // emit any necessary methods for assembling binding metadata. if (needsMultipleBindingMethods) { writeBindingMethods(pw, deferredBindings); pw.println(); } pw.println( " protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {"); pw.println(" try {"); pw.println(" org.apache.axis.client.Call _call = super._createCall();"); pw.println(" if (super.maintainSessionSet) {"); pw.println( " _call.setMaintainSession(super.maintainSession);"); pw.println(" }"); pw.println(" if (super.cachedUsername != null) {"); pw.println(" _call.setUsername(super.cachedUsername);"); pw.println(" }"); pw.println(" if (super.cachedPassword != null) {"); pw.println(" _call.setPassword(super.cachedPassword);"); pw.println(" }"); pw.println(" if (super.cachedEndpoint != null) {"); pw.println( " _call.setTargetEndpointAddress(super.cachedEndpoint);"); pw.println(" }"); pw.println(" if (super.cachedTimeout != null) {"); pw.println(" _call.setTimeout(super.cachedTimeout);"); pw.println(" }"); pw.println(" if (super.cachedPortName != null) {"); pw.println(" _call.setPortName(super.cachedPortName);"); pw.println(" }"); pw.println( " java.util.Enumeration keys = super.cachedProperties.keys();"); pw.println(" while (keys.hasMoreElements()) {"); pw.println( " java.lang.String key = (java.lang.String) keys.nextElement();"); pw.println( " _call.setProperty(key, super.cachedProperties.get(key));"); pw.println(" }"); if (typeMappingCount > 0) { pw.println(" // " + Messages.getMessage("typeMap00")); pw.println(" // " + Messages.getMessage("typeMap01")); pw.println(" // " + Messages.getMessage("typeMap02")); pw.println(" // " + Messages.getMessage("typeMap03")); pw.println(" // " + Messages.getMessage("typeMap04")); pw.println(" synchronized (this) {"); pw.println(" if (firstCall()) {"); // Hack alert - we need to establish the encoding style before we register type mappings due // to the fact that TypeMappings key off of encoding style pw.println(" // " + Messages.getMessage("mustSetStyle")); if (bEntry.hasLiteral()) { pw.println(" _call.setEncodingStyle(null);"); } else { Iterator iterator = bEntry.getBinding().getExtensibilityElements().iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj instanceof SOAPBinding) { pw.println( " _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);"); pw.println( " _call.setEncodingStyle(org.apache.axis.Constants.URI_SOAP11_ENC);"); } else if (obj instanceof SOAP12Binding) { pw.println( " _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP12_CONSTANTS);"); pw.println( " _call.setEncodingStyle(org.apache.axis.Constants.URI_SOAP12_ENC);"); } } } pw.println( " for (int i = 0; i < cachedSerFactories.size(); ++i) {"); pw.println( " java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);"); pw.println( " javax.xml.namespace.QName qName ="); pw.println( " (javax.xml.namespace.QName) cachedSerQNames.get(i);"); pw.println( " java.lang.Object x = cachedSerFactories.get(i);"); pw.println( " if (x instanceof Class) {"); pw.println( " java.lang.Class sf = (java.lang.Class)"); pw.println( " cachedSerFactories.get(i);"); pw.println( " java.lang.Class df = (java.lang.Class)"); pw.println( " cachedDeserFactories.get(i);"); pw.println( " _call.registerTypeMapping(cls, qName, sf, df, false);"); pw.println(" }"); pw.println( " else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {"); pw.println( " org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)"); pw.println( " cachedSerFactories.get(i);"); pw.println( " org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)"); pw.println( " cachedDeserFactories.get(i);"); pw.println( " _call.registerTypeMapping(cls, qName, sf, df, false);"); pw.println(" }"); pw.println(" }"); pw.println(" }"); pw.println(" }"); } pw.println(" return _call;"); pw.println(" }"); pw.println(" catch (java.lang.Throwable _t) {"); pw.println(" throw new org.apache.axis.AxisFault(\"" + Messages.getMessage("badCall01") + "\", _t);"); pw.println(" }"); pw.println(" }"); pw.println(); List operations = binding.getBindingOperations(); for (int i = 0; i < operations.size(); ++i) { BindingOperation operation = (BindingOperation) operations.get(i); Parameters parameters = bEntry.getParameters(operation.getOperation()); // Get the soapAction from the <soap:operation> String soapAction = ""; String opStyle = null; Iterator operationExtensibilityIterator = operation.getExtensibilityElements().iterator(); for (; operationExtensibilityIterator.hasNext();) { Object obj = operationExtensibilityIterator.next(); if (obj instanceof SOAPOperation) { soapAction = ((SOAPOperation) obj).getSoapActionURI(); opStyle = ((SOAPOperation) obj).getStyle(); break; } else if (obj instanceof SOAP12Operation) { soapAction = ((SOAP12Operation) obj).getSoapActionURI(); opStyle = ((SOAP12Operation) obj).getStyle(); break; } } Operation ptOperation = operation.getOperation(); OperationType type = ptOperation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { pw.println(parameters.signature); pw.println(); } else { writeOperation(pw, operation, parameters, soapAction, opStyle, type == OperationType.ONE_WAY, i); } } } // writeFileBody /** * Compute the number of addBindings methods we need to generate for the * set of TypeEntries used by the generated stub. * * @param deferredBindings a <code>List</code> value * @return an <code>int</code> value */ private int calculateBindingMethodCount(List deferredBindings) { int methodCount = deferredBindings.size() / MAXIMUM_BINDINGS_PER_METHOD; if ((deferredBindings.size() % MAXIMUM_BINDINGS_PER_METHOD) != 0) { methodCount++; } return methodCount; } /** * for each of the TypeEntry objects in the deferredBindings list, we need * to write code that will associate a class with a schema namespace/name. * This method writes a number of private methods out that do this in * batches of size MAXIMUM_BINDINGS_PER_METHOD so that generated classes * do not end up with a single method that exceeds the 64K limit that the * VM imposes on all methods. * * @param pw a <code>PrintWriter</code> value * @param deferredBindings a <code>List</code> of TypeEntry objects */ protected void writeBindingMethods(PrintWriter pw, List deferredBindings) { int methodCount = calculateBindingMethodCount(deferredBindings); for (int i = 0; i < methodCount; i++) { pw.println(" private void addBindings" + i + "() {"); // each method gets its own local variables for use in generating // the binding code writeSerializationDecls(pw, false, null); for (int j = 0; j < MAXIMUM_BINDINGS_PER_METHOD; j++) { int absolute = i * MAXIMUM_BINDINGS_PER_METHOD + j; if (absolute == deferredBindings.size()) { break; // last one } writeSerializationInit( pw, (TypeEntry) deferredBindings.get(absolute)); } pw.println(" }"); } } /** * Method writeOperationMap * * @param pw */ protected void writeOperationMap(PrintWriter pw) { List operations = binding.getBindingOperations(); pw.println(" static {"); pw.println( " _operations = new org.apache.axis.description.OperationDesc[" + operations.size() + "];"); for (int j = 0, k = 0; j < operations.size(); ++j) { if ((j % OPERDESC_PER_BLOCK) == 0) { k++; pw.println(" _initOperationDesc" + k + "();"); } } for (int i = 0, k = 0; i < operations.size(); ++i) { if ((i % OPERDESC_PER_BLOCK) == 0) { k++; pw.println(" }\n"); pw.println(" private static void _initOperationDesc" + k + "(){"); pw.println( " org.apache.axis.description.OperationDesc oper;"); pw.println( " org.apache.axis.description.ParameterDesc param;"); } BindingOperation operation = (BindingOperation) operations.get(i); Parameters parameters = bEntry.getParameters(operation.getOperation()); // Get the soapAction from the <soap:operation> String opStyle = null; Iterator operationExtensibilityIterator = operation.getExtensibilityElements().iterator(); for (; operationExtensibilityIterator.hasNext();) { Object obj = operationExtensibilityIterator.next(); if (obj instanceof SOAPOperation) { opStyle = ((SOAPOperation) obj).getStyle(); break; } else if (obj instanceof SOAP12Operation) { opStyle = ((SOAP12Operation) obj).getStyle(); break; } } Operation ptOperation = operation.getOperation(); OperationType type = ptOperation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { pw.println(parameters.signature); pw.println(); } String operName = operation.getName(); String indent = " "; pw.println( indent + "oper = new org.apache.axis.description.OperationDesc();"); pw.println(indent + "oper.setName(\"" + operName + "\");"); // loop over paramters and set up in/out params for (int j = 0; j < parameters.list.size(); ++j) { Parameter p = (Parameter) parameters.list.get(j); // Get the QName representing the parameter type QName paramType = Utils.getXSIType(p); // Set the javaType to the name of the type String javaType = Utils.getParameterTypeName(p); if (javaType != null) { javaType += ".class, "; } else { javaType = "null, "; } // Get the text representing newing a QName for the name and type String paramNameText = Utils.getNewQNameWithLastLocalPart(p.getQName()); String paramTypeText = Utils.getNewQName(paramType); // Generate the addParameter call with the // name qname, typeQName, optional javaType, and mode boolean isInHeader = p.isInHeader(); boolean isOutHeader = p.isOutHeader(); pw.println(" param = new org.apache.axis.description.ParameterDesc(" + paramNameText + ", " + modeStrings[p.getMode()] + ", " + paramTypeText + ", " + javaType + isInHeader + ", " + isOutHeader + ");"); QName itemQName = Utils.getItemQName(p.getType()); if (itemQName != null) { pw.println(" param.setItemQName(" + Utils.getNewQName(itemQName) + ");"); } if (p.isOmittable()) pw.println(" param.setOmittable(true);"); if (p.isNillable()) pw.println(" param.setNillable(true);"); pw.println(" oper.addParameter(param);"); } // set output type Parameter returnParam = parameters.returnParam; if (returnParam != null) { // Get the QName for the return Type QName returnType = Utils.getXSIType(returnParam); // Get the javaType String javaType = Utils.getParameterTypeName(returnParam); if (javaType == null) { javaType = ""; } else { javaType += ".class"; } pw.println(" oper.setReturnType(" + Utils.getNewQName(returnType) + ");"); pw.println(" oper.setReturnClass(" + javaType + ");"); QName returnQName = returnParam.getQName(); if (returnQName != null) { pw.println(" oper.setReturnQName(" + Utils.getNewQNameWithLastLocalPart(returnQName) + ");"); } if (returnParam.isOutHeader()) { pw.println(" oper.setReturnHeader(true);"); } QName itemQName = Utils.getItemQName(returnParam.getType()); if (itemQName != null) { pw.println(" param = oper.getReturnParamDesc();"); pw.println(" param.setItemQName(" + Utils.getNewQName(itemQName) + ");"); } } else { pw.println( " oper.setReturnType(org.apache.axis.encoding.XMLType.AXIS_VOID);"); } boolean hasMIME = Utils.hasMIME(bEntry, operation); Style style = Style.getStyle(opStyle, bEntry.getBindingStyle()); Use use = bEntry.getInputBodyType(operation.getOperation()); if ((style == Style.DOCUMENT) && symbolTable.isWrapped()) { style = Style.WRAPPED; } if (!hasMIME) { pw.println(" oper.setStyle(" + styles.get(style) + ");"); pw.println(" oper.setUse(" + uses.get(use) + ");"); } // Register fault/exception information for this operation writeFaultInfo(pw, operation); pw.println(indent + "_operations[" + i + "] = oper;"); pw.println(""); } pw.println(" }"); } /** * This method returns a set of all the TypeEntry in a given PortType. * The elements of the returned HashSet are Types. * * @param portType * @return */ private HashSet getTypesInPortType(PortType portType) { HashSet types = new HashSet(); HashSet firstPassTypes = new HashSet(); // Get all the types from all the operations List operations = portType.getOperations(); for (int i = 0; i < operations.size(); ++i) { Operation op = (Operation) operations.get(i); firstPassTypes.addAll(getTypesInOperation(op)); } // Add all the types nested and derived from the types // in the first pass. Iterator i = firstPassTypes.iterator(); while (i.hasNext()) { TypeEntry type = (TypeEntry) i.next(); if (!types.contains(type)) { types.add(type); types.addAll(type.getNestedTypes(symbolTable, true)); } } if(emitter.isAllWanted()) { HashMap rawSymbolTable = symbolTable.getHashMap(); for(Iterator j = rawSymbolTable.values().iterator(); j.hasNext(); ) { Vector typeVector = (Vector)j.next(); for(Iterator k = typeVector.iterator(); k.hasNext(); ) { Object symbol = k.next(); if(symbol instanceof DefinedType) { TypeEntry type = (TypeEntry)symbol; if(!types.contains(type)) { types.add(type); } } } } } return types; } // getTypesInPortType /** * This method returns a set of all the TypeEntry in a given Operation. * The elements of the returned HashSet are TypeEntry. * * @param operation * @return */ private HashSet getTypesInOperation(Operation operation) { HashSet types = new HashSet(); Vector v = new Vector(); Parameters params = bEntry.getParameters(operation); // Loop over parameter types for this operation for (int i = 0; i < params.list.size(); i++) { Parameter p = (Parameter) params.list.get(i); v.add(p.getType()); } // Add the return type if (params.returnParam != null) { v.add(params.returnParam.getType()); } // Collect all the types in faults Map faults = operation.getFaults(); if (faults != null) { Iterator i = faults.values().iterator(); while (i.hasNext()) { Fault f = (Fault) i.next(); partTypes(v, f.getMessage().getOrderedParts(null)); } } // Put all these types into a set. This operation eliminates all duplicates. for (int i = 0; i < v.size(); i++) { types.add(v.get(i)); } return types; } // getTypesInOperation /** * This method returns a vector of TypeEntry for the parts. * * @param v * @param parts */ private void partTypes(Vector v, Collection parts) { Iterator i = parts.iterator(); while (i.hasNext()) { Part part = (Part) i.next(); QName qType = part.getTypeName(); if (qType != null) { v.add(symbolTable.getType(qType)); } else { qType = part.getElementName(); if (qType != null) { v.add(symbolTable.getElement(qType)); } } } // while } // partTypes /** * This function writes the regsiterFaultInfo API calls * * @param pw * @param bindOp */ protected void writeFaultInfo(PrintWriter pw, BindingOperation bindOp) { Map faultMap = bEntry.getFaults(); // Get the list of faults for this operation ArrayList faults = (ArrayList) faultMap.get(bindOp); // check for no faults if (faults == null) { return; } // For each fault, register its information for (Iterator faultIt = faults.iterator(); faultIt.hasNext();) { FaultInfo info = (FaultInfo) faultIt.next(); QName qname = info.getQName(); Message message = info.getMessage(); // if no parts in fault, skip it! if (qname == null) { continue; } // Get the Exception class name String className = Utils.getFullExceptionName(message, symbolTable); // output the registration API call pw.println( " oper.addFault(new org.apache.axis.description.FaultDesc("); pw.println(" " + Utils.getNewQName(qname) + ","); pw.println(" \"" + className + "\","); pw.println(" " + Utils.getNewQName(info.getXMLType()) + ", "); pw.println(" " + Utils.isFaultComplex(message, symbolTable)); pw.println(" ));"); } } /** * In the stub constructor, write the serializer code for the complex types. * * @param pw * @param hasMIME * @param namespace */ protected void writeSerializationDecls(PrintWriter pw, boolean hasMIME, String namespace) { pw.println(" java.lang.Class cls;"); pw.println(" javax.xml.namespace.QName qName;"); pw.println(" javax.xml.namespace.QName qName2;"); pw.println( " java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;"); pw.println( " java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;"); pw.println( " java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;"); pw.println( " java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;"); pw.println( " java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;"); pw.println( " java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;"); pw.println( " java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;"); pw.println( " java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;"); pw.println( " java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;"); pw.println( " java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;"); if (hasMIME) { pw.println( " java.lang.Class mimesf = org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory.class;"); pw.println( " java.lang.Class mimedf = org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory.class;"); pw.println(); QName qname = new QName(namespace, "DataHandler"); pw.println(" qName = new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() + "\", \"" + qname.getLocalPart() + "\");"); pw.println(" cachedSerQNames.add(qName);"); pw.println(" cls = javax.activation.DataHandler.class;"); pw.println(" cachedSerClasses.add(cls);"); pw.println(" cachedSerFactories.add(mimesf);"); pw.println(" cachedDeserFactories.add(mimedf);"); pw.println(); } } // writeSerializationDecls /** * Method writeSerializationInit * * @param pw * @param type */ protected void writeSerializationInit(PrintWriter pw, TypeEntry type) { QName qname = type.getQName(); pw.println(" qName = new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() + "\", \"" + qname.getLocalPart() + "\");"); pw.println(" cachedSerQNames.add(qName);"); pw.println(" cls = " + type.getName() + ".class;"); pw.println(" cachedSerClasses.add(cls);"); if (type.getName().endsWith("[]")) { if (SchemaUtils.isListWithItemType(type.getNode())) { pw.println(" cachedSerFactories.add(simplelistsf);"); pw.println(" cachedDeserFactories.add(simplelistdf);"); } else { // We use a custom serializer if WSDL told us the component type of the array. // Both factories must be an instance, so we create a ArrayDeserializerFactory if (type.getComponentType() != null) { QName ct = type.getComponentType(); QName name = type.getItemQName(); pw.println(" qName = new javax.xml.namespace.QName(\"" + ct.getNamespaceURI() + "\", \"" + ct.getLocalPart() + "\");"); if(name != null) { pw.println(" qName2 = new javax.xml.namespace.QName(\"" + name.getNamespaceURI() + "\", \"" + name.getLocalPart() + "\");"); } else { pw.println(" qName2 = null;"); } pw.println(" cachedSerFactories.add(new org.apache.axis.encoding.ser.ArraySerializerFactory(qName, qName2));"); pw.println(" cachedDeserFactories.add(new org.apache.axis.encoding.ser.ArrayDeserializerFactory());"); } else { pw.println(" cachedSerFactories.add(arraysf);"); pw.println(" cachedDeserFactories.add(arraydf);"); } } } else if ((type.getNode() != null) && (Utils.getEnumerationBaseAndValues( type.getNode(), symbolTable) != null)) { pw.println(" cachedSerFactories.add(enumsf);"); pw.println(" cachedDeserFactories.add(enumdf);"); } else if (type.isSimpleType()) { pw.println(" cachedSerFactories.add(org.apache.axis.encoding.ser.BaseSerializerFactory.createFactory(" + "org.apache.axis.encoding.ser.SimpleSerializerFactory.class, cls, qName));"); pw.println(" cachedDeserFactories.add(org.apache.axis.encoding.ser.BaseDeserializerFactory.createFactory(" + "org.apache.axis.encoding.ser.SimpleDeserializerFactory.class, cls, qName));"); } else if (type.getBaseType() != null) { // serializers are not required for types derived from base types // java type to qname mapping is anyway established by default // note that we have to add null to the serfactories vector to // keep the order of other entries, this is not going to screw // up because if type mapping returns null for a serialization // factory, it is assumed to be not-defined and the delegate // will be checked, the end delegate is DefaultTypeMappingImpl // that'll get it right with the base type name pw.println(" cachedSerFactories.add(null);"); pw.println(" cachedDeserFactories.add(simpledf);"); } else { pw.println(" cachedSerFactories.add(beansf);"); pw.println(" cachedDeserFactories.add(beandf);"); } pw.println(); } // writeSerializationInit /** * Write the stub code for the given operation. * * @param pw * @param operation * @param parms * @param soapAction * @param opStyle * @param oneway * @param opIndex */ protected void writeOperation(PrintWriter pw, BindingOperation operation, Parameters parms, String soapAction, String opStyle, boolean oneway, int opIndex) { writeComment(pw, operation.getDocumentationElement(), true); if (parms.signature == null) { return; } pw.println(parms.signature + " {"); pw.println(" if (super.cachedEndpoint == null) {"); pw.println( " throw new org.apache.axis.NoEndPointException();"); pw.println(" }"); pw.println(" org.apache.axis.client.Call _call = createCall();"); pw.println(" _call.setOperation(_operations[" + opIndex + "]);"); // SoapAction if (soapAction != null) { pw.println(" _call.setUseSOAPAction(true);"); pw.println(" _call.setSOAPActionURI(\"" + soapAction + "\");"); } boolean hasMIME = Utils.hasMIME(bEntry, operation); // Encoding: literal or encoded use. Use use = bEntry.getInputBodyType(operation.getOperation()); if (use == Use.LITERAL) { // Turn off encoding pw.println(" _call.setEncodingStyle(null);"); // turn off XSI types pw.println( " _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);"); } if (hasMIME || (use == Use.LITERAL)) { // If it is literal, turn off multirefs. // // If there are any MIME types, turn off multirefs. // I don't know enough about the guts to know why // attachments don't work with multirefs, but they don't. pw.println( " _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);"); } Style style = Style.getStyle(opStyle, bEntry.getBindingStyle()); if ((style == Style.DOCUMENT) && symbolTable.isWrapped()) { style = Style.WRAPPED; } Iterator iterator = bEntry.getBinding().getExtensibilityElements().iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj instanceof SOAPBinding) { pw.println( " _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);"); } else if (obj instanceof SOAP12Binding) { pw.println( " _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP12_CONSTANTS);"); } } // Operation name if (style == Style.WRAPPED) { // We need to make sure the operation name, which is what we // wrap the elements in, matches the Qname of the parameter // element. Map partsMap = operation.getOperation().getInput().getMessage().getParts(); Iterator i = partsMap.values().iterator(); QName q = null; while (q == null && i.hasNext()) { Part p = (Part) i.next(); q = p.getElementName(); } if(q != null) { pw.println(" _call.setOperationName(" + Utils.getNewQName(q) + ");"); } else { log.warn(Messages.getMessage("missingPartsForMessage00",operation.getOperation().getInput().getMessage().getQName().toString())); } } else { QName elementQName = Utils.getOperationQName(operation, bEntry, symbolTable); if (elementQName != null) { pw.println(" _call.setOperationName(" + Utils.getNewQName(elementQName) + ");"); } } pw.println(); // Set the headers pw.println(" setRequestHeaders(_call);"); // Set the attachments pw.println(" setAttachments(_call);"); // Set DIME flag if needed if (bEntry.isOperationDIME(operation.getOperation().getName())) { pw.println( " _call.setProperty(_call.ATTACHMENT_ENCAPSULATION_FORMAT, _call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME);"); } // Invoke the operation if (oneway) { pw.print(" _call.invokeOneWay("); } else { pw.print(" try {"); pw.print(" java.lang.Object _resp = _call.invoke("); } pw.print("new java.lang.Object[] {"); writeParameters(pw, parms); pw.println("});"); pw.println(); if (!oneway) { writeResponseHandling(pw, parms); } pw.println(" }"); pw.println(); } // writeOperation /** * Method writeParameters * * @param pw * @param parms */ protected void writeParameters(PrintWriter pw, Parameters parms) { // Write the input and inout parameter list boolean needComma = false; for (int i = 0; i < parms.list.size(); ++i) { Parameter p = (Parameter) parms.list.get(i); if (p.getMode() != Parameter.OUT) { if (needComma) { pw.print(", "); } else { needComma = true; } String javifiedName = JavaUtils.xmlNameToJava(p.getName()); if (p.getMode() != Parameter.IN) { javifiedName += ".value"; } if (p.getMIMEInfo() == null && !p.isOmittable()) { javifiedName = Utils.wrapPrimitiveType(p.getType(), javifiedName); } pw.print(javifiedName); } } } // writeParamters /** * Method writeResponseHandling * * @param pw * @param parms */ protected void writeResponseHandling(PrintWriter pw, Parameters parms) { pw.println(" if (_resp instanceof java.rmi.RemoteException) {"); pw.println(" throw (java.rmi.RemoteException)_resp;"); pw.println(" }"); int allOuts = parms.outputs + parms.inouts; if (allOuts > 0) { pw.println(" else {"); pw.println(" extractAttachments(_call);"); if (allOuts == 1) { if (parms.returnParam != null) { writeOutputAssign(pw, "return ", parms.returnParam, "_resp"); } else { // The resp object must go into a holder int i = 0; Parameter p = (Parameter) parms.list.get(i); while (p.getMode() == Parameter.IN) { p = (Parameter) parms.list.get(++i); } String javifiedName = JavaUtils.xmlNameToJava(p.getName()); String qnameName = Utils.getNewQNameWithLastLocalPart(p.getQName()); pw.println(" java.util.Map _output;"); pw.println( " _output = _call.getOutputParams();"); writeOutputAssign(pw, javifiedName + ".value = ", p, "_output.get(" + qnameName + ")"); } } else { // There is more than 1 output. Get the outputs from getOutputParams. pw.println(" java.util.Map _output;"); pw.println(" _output = _call.getOutputParams();"); for (int i = 0; i < parms.list.size(); ++i) { Parameter p = (Parameter) parms.list.get(i); String javifiedName = JavaUtils.xmlNameToJava(p.getName()); String qnameName = Utils.getNewQNameWithLastLocalPart(p.getQName()); if (p.getMode() != Parameter.IN) { writeOutputAssign(pw, javifiedName + ".value = ", p, "_output.get(" + qnameName + ")"); } } if (parms.returnParam != null) { writeOutputAssign(pw, "return ", parms.returnParam, "_resp"); } } pw.println(" }"); } else { pw.println(" extractAttachments(_call);"); } // End catch // Get faults Map faults = parms.faults; // Get faults of signature List exceptionsThrowsList = new ArrayList(); int index = parms.signature.indexOf("throws"); if (index != -1) { String[] thrExcep = StringUtils.split(parms.signature.substring(index+6),','); for (int i = 0; i < thrExcep.length; i++) { exceptionsThrowsList.add(thrExcep[i].trim()); } } pw.println(" } catch (org.apache.axis.AxisFault axisFaultException) {"); if (faults != null && faults.size() > 0) { pw.println(" if (axisFaultException.detail != null) {"); for (Iterator faultIt = exceptionsThrowsList.iterator(); faultIt .hasNext();) { String exceptionFullName = (String) faultIt.next(); pw.println(" if (axisFaultException.detail instanceof " + exceptionFullName + ") {"); pw.println(" throw (" + exceptionFullName + ") axisFaultException.detail;"); pw.println(" }"); } pw.println(" }"); } pw.println(" throw axisFaultException;"); pw.println("}"); } // writeResponseHandling /** * writeOutputAssign * * @param pw * @param target (either "return" or "something =" * @param source (source String) */ protected void writeOutputAssign(PrintWriter pw, String target, Parameter param, String source) { TypeEntry type = param.getType(); if ((type != null) && (type.getName() != null)) { String typeName = type.getName(); // If minOccurs="0" and singular or array with nillable underlying // type get the corresponding wrapper type. if ((param.isOmittable() && param.getType().getDimensions().equals("")) || (param.getType() instanceof CollectionType && ((CollectionType) param.getType()).isWrapped()) || param.getType().getUnderlTypeNillable()) { typeName = Utils.getWrapperType(type); } // Try casting the output to the expected output. // If that fails, use JavaUtils.convert() pw.println(" try {"); pw.println(" " + target + Utils.getResponseString(param, source)); pw.println( " } catch (java.lang.Exception _exception) {"); pw.println( " " + target + Utils.getResponseString(param, "org.apache.axis.utils.JavaUtils.convert(" + source + ", " + typeName + ".class)")); pw.println(" }"); } else { pw.println(" " + target + Utils.getResponseString(param, source)); } } } // class JavaStubWriter
6,891
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/GeneratedFileInfo.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * File info available after emit to describe what * exactly was created by the Emitter. * * @author Tom Jordahl (tomj@macromedia.com) */ public class GeneratedFileInfo { /** Field list */ protected ArrayList list = new ArrayList(); /** * Structure to hold entries. * There are three public data members: * <ul> * <li><code>fileName</code> - A relative path of the generated file.</li> * <li><code>className</code> - The name of the class in the file.</li> * <li><code>type</code> - The type of the file.<br> * Valid types are:<br> * <code> * stub, interface, complexType, enumType, fault, holder, skeleton, * skeletonImpl, service, deploy, undeploy, testCase * </code></li> * </ul> */ public class Entry { // relative path of the emitted file /** Field fileName */ public String fileName; // name of emitted class /** Field className */ public String className; // function of the emitted class /** Field type */ public String type; /** * Constructor Entry * * @param name * @param className * @param type */ public Entry(String name, String className, String type) { this.fileName = name; this.className = className; this.type = type; } /** * Method toString * * @return */ public String toString() { return "Name: " + fileName + " Class: " + className + " Type: " + type; } } // Entry /** * Construct an empty file info list. */ public GeneratedFileInfo() { } /** * Return the entire list of generated files * * @return */ public List getList() { return list; } /** * Add an entry * * @param name * @param className * @param type */ public void add(String name, String className, String type) { list.add(new Entry(name, className, type)); } /** * Lookup an entry by type. * <br> * Valid type values are: * stub, interface, complexType, enumType, fault, holder, skeleton, * skeletonImpl, service, deploy, undeploy, testCase * * @param type of objects you want info about * @return A list of <code>org.apache.axis.wsdl.toJava.GeneratedFileInfo.Entry</code> objects. Null if no objects found. */ public List findType(String type) { // look at each entry for the type we want ArrayList ret = null; for (Iterator i = list.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (e.type.equals(type)) { if (ret == null) { ret = new ArrayList(); } ret.add(e); } } return ret; } /** * Lookup an entry by file name * * @param fileName name you want info about * @return The entry for the file name specified. Null if not found */ public Entry findName(String fileName) { // look at each entry for the type we want for (Iterator i = list.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (e.fileName.equals(fileName)) { return e; } } return null; } /** * Lookup an entry by class name * * @param className name you want info about * @return The entry for the class specified. Null if not found */ public Entry findClass(String className) { // look at each entry for the type we want for (Iterator i = list.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); if (e.className.equals(className)) { return e; } } return null; } /** * Get the list of generated classes * * @return */ public List getClassNames() { // is there a better way to do this? ArrayList ret = new ArrayList(list.size()); for (Iterator i = list.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); ret.add(e.className); } return ret; } /** * Get the list of generated filenames * * @return */ public List getFileNames() { // is there a better way to do this? ArrayList ret = new ArrayList(list.size()); for (Iterator i = list.iterator(); i.hasNext();) { Entry e = (Entry) i.next(); ret.add(e.fileName); } return ret; } /** * Convert all entries in the list to a string * * @return */ public String toString() { String s = ""; for (Iterator i = list.iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); s += entry.toString() + "\n"; } return s; } }
6,892
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaBeanFaultWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.symbolTable.TypeEntry; import java.io.IOException; import java.io.PrintWriter; import java.util.Vector; import java.util.Set; import java.util.Collections; import java.util.HashSet; /** * This is Wsdl2java's Complex Fault Writer. * It generates bean-like class for complexTypes used * in an operation fault message. */ public class JavaBeanFaultWriter extends JavaBeanWriter { /** * All server specific exception classes have {@link Throwable} as an * indirect superclass. <code>Throwable</code> defines a set of properties * that may potentially conflict with those that would be generated by * this class for an XSD complex type used as a fault. The following * immutable object contains all property names that must be excluded * when generating a service specific exception. <i>Note:</i> * {@link org.apache.axis.encoding.ser.BeanSerializer} always excludes * <code>Throwable</code>'s and <code>AxisFault</code>'s properties * when marshalling a service Java exception. */ public static final Set RESERVED_PROPERTY_NAMES; static { Set temp = new HashSet(); // Throwable's properties. temp.add("cause"); temp.add("message"); temp.add("localizedMessage"); temp.add("stackTrace"); // AxisFault's properties. temp.add("faultActor"); temp.add("faultCode"); temp.add("faultDetails"); temp.add("faultNode"); temp.add("faultReason"); temp.add("faultRole"); temp.add("faultString"); temp.add("faultSubCodes"); temp.add("headers"); RESERVED_PROPERTY_NAMES = Collections.unmodifiableSet(temp); } /** * Constructor. * * @param emitter * @param type The type representing this class * @param elements Vector containing the Type and name of each property * @param extendType The type representing the extended class (or null) * @param attributes Vector containing the attribute types and names * @param helper Helper class writer */ protected JavaBeanFaultWriter(Emitter emitter, TypeEntry type, Vector elements, TypeEntry extendType, Vector attributes, JavaWriter helper) { super(emitter, type, elements, extendType, attributes, helper); // The Default Constructor is not JSR 101 v1.0 compliant, but // is the only way that Axis can get something back over the wire. // This will need to be changed when fault contents are supported // over the wire. enableDefaultConstructor = true; // JSR 101 v1.0 requires a full constructor enableFullConstructor = true; // JSR 101 v1.0 does not support write access methods enableSetters = true; } // ctor /** * Returns the appropriate extends text * * @return "" or " extends &lt;class&gt; " */ protected String getExtendsText() { // See if this class extends another class String extendsText = super.getExtendsText(); if (extendsText.equals("")) { // JSR 101 compliant code should extend java.lang.Exception! // extendsText = " extends java.lang.Exception "; extendsText = " extends org.apache.axis.AxisFault "; } return extendsText; } /** * Write the Exception serialization code * <p> * NOTE: This function is written in JavaFaultWriter.java also. * * @param pw * @throws IOException */ protected void writeFileFooter(PrintWriter pw) throws IOException { // We need to have the Exception class serialize itself // with the correct namespace, which can change depending on which // operation the exception is thrown from. We therefore have the // framework call this generated routine with the correct QName, // and allow it to serialize itself. // method that serializes this exception (writeDetail) pw.println(); pw.println(" /**"); pw.println(" * Writes the exception data to the faultDetails"); pw.println(" */"); pw.println( " public void writeDetails(javax.xml.namespace.QName qname, org.apache.axis.encoding.SerializationContext context) throws java.io.IOException {"); pw.println(" context.serialize(qname, null, this);"); pw.println(" }"); super.writeFileFooter(pw); } // writeFileFooter } // class JavaBeanFaultWriter
6,893
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/JavaServiceWriter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.wsdl.gen.Generator; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import javax.wsdl.Service; import java.io.IOException; /** * This is Wsdl2java's Service Writer. It writes the following files, as appropriate: * &lt;serviceName&gt;.java, &lt;serviceName&gt;TestCase.java. */ public class JavaServiceWriter implements Generator { /** Field serviceIfaceWriter */ protected Generator serviceIfaceWriter = null; /** Field serviceImplWriter */ protected Generator serviceImplWriter = null; /** Field testCaseWriter */ protected Generator testCaseWriter = null; /** Field PORT_NAME */ public static final String PORT_NAME = "port name"; /** Field emitter */ protected Emitter emitter; /** Field WSDL service */ protected Service service; /** Field symbolTable */ protected SymbolTable symbolTable; /** * Constructor. * * @param emitter * @param service * @param symbolTable */ public JavaServiceWriter(Emitter emitter, Service service, SymbolTable symbolTable) { this.emitter = emitter; this.service = service; this.symbolTable = symbolTable; } // ctor /** * setGenerators * Logic to set the generators that are based on the Service. * This logic was moved from the constructor so extended interfaces * can more effectively use the hooks. */ protected void setGenerators() { ServiceEntry sEntry = symbolTable.getServiceEntry(service.getQName()); if (sEntry.isReferenced()) { serviceIfaceWriter = new JavaServiceIfaceWriter(emitter, sEntry, symbolTable); serviceImplWriter = new JavaServiceImplWriter(emitter, sEntry, symbolTable); if (emitter.isTestCaseWanted()) { testCaseWriter = new JavaTestCaseWriter(emitter, sEntry, symbolTable); } } } /** * Set the writer based on the other condition after generate() is called. */ protected void postSetGenerators() { if (emitter.isDeploy()) { serviceIfaceWriter = null; serviceImplWriter = null; } } /** * Write all the service bindnigs: service and testcase. * * @throws IOException */ public void generate() throws IOException { setGenerators(); postSetGenerators(); if (serviceIfaceWriter != null) { serviceIfaceWriter.generate(); } if (serviceImplWriter != null) { serviceImplWriter.generate(); } if (testCaseWriter != null) { testCaseWriter.generate(); } } // generate } // class JavaServiceWriter
6,894
0
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl
Create_ds/axis-axis1-java/axis-codegen/src/main/java/org/apache/axis/wsdl/toJava/Emitter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.wsdl.toJava; import org.apache.axis.Constants; import org.apache.axis.constants.Scope; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.i18n.Messages; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.gen.GeneratorFactory; import org.apache.axis.wsdl.gen.Parser; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.wsdl.WSDLException; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Vector; /** * This class produces java files for stubs, skeletons, and types from a * WSDL document. * * @author Russell Butek (butek@us.ibm.com) * @author Tom Jordahl (tjordahl@macromedia.com) * @author Rich Scheuerle (scheu@us.ibm.com) * @author Steve Graham (sggraham@us.ibm.com) */ public class Emitter extends Parser { /** Field DEFAULT_NSTOPKG_FILE */ public static final String DEFAULT_NSTOPKG_FILE = "NStoPkg.properties"; /** Field namespaceMap */ protected HashMap namespaceMap = new HashMap(); /** Field typeMappingVersion */ protected String typeMappingVersion = "1.2"; /** Field namespaces */ protected Namespaces namespaces = null; /** Field NStoPkgFilename */ protected String NStoPkgFilename = null; /** Field bEmitServer */ private boolean bEmitServer = false; /** Field bDeploySkeleton */ private boolean bDeploySkeleton = false; /** Field bEmitTestCase */ private boolean bEmitTestCase = false; /** Field bGenerateAll */ private boolean bGenerateAll = false; /** Field bHelperGeneration */ private boolean bHelperGeneration = false; private boolean bBuildFileGeneration = false; private boolean typeCollisionProtection = true; /** Check if URL endpoints are valid or not */ private boolean allowInvalidURL = false; /** Field packageName */ private String packageName = null; /** Field scope */ private Scope scope = null; /** Field fileInfo */ private GeneratedFileInfo fileInfo = new GeneratedFileInfo(); /** Field delayedNamespacesMap */ private HashMap delayedNamespacesMap = new HashMap(); /** Field outputDir */ private String outputDir = null; /** Field nsIncludes - defines a list of namespaces to specifically * include in the generated source code. If non-empty, anything * not in this list should be excluded. If empty, everything in this * and not specifically excluded should be generated. */ protected List nsIncludes = new ArrayList(); /** Field nsIncludes - defines a list of namespaces to specifically * exclude from generated source code. Any entry in this list that * is in conflict with the includes list should be ignored and * generated. */ protected List nsExcludes = new ArrayList(); /** Field properties - defines a set of general purpose properties * that can be used by custom JavaGeneratorFactories. */ protected List properties = new ArrayList(); /** * Field implementationClassName - defines a non default classname for the actual * implementation class. Particularly useful when exporting a webservice directly * from the java implementation. */ private String implementationClassName = null; /** Field defaultTM */ private TypeMapping defaultTM = null; // Default TM private TypeMappingRegistryImpl tmr = new TypeMappingRegistryImpl(); /** The mapping of qname to its corresponding java type generated by Java2Wsdl emitter. For deploy mode roundtripping use. */ private HashMap qName2ClassMap; /** The ServiceDesc. For deploy mode roundtripping use. */ private ServiceDesc serviceDesc; /** The deploy mode flag */ private boolean isDeploy; /** * Default constructor. */ public Emitter() { setFactory(new JavaGeneratorFactory(this)); } // ctor // ///////////////////////////////////////////////// // // Command line switches // /** * Turn on/off server skeleton creation * * @param value */ public void setServerSide(boolean value) { this.bEmitServer = value; } // setServerSide /** * Indicate if we should be emitting server side code and deploy/undeploy * * @return */ public boolean isServerSide() { return bEmitServer; } // isServerSide /** * Turn on/off server skeleton deploy * * @param value */ public void setSkeletonWanted(boolean value) { bDeploySkeleton = value; } // setSkeletonWanted /** * Indicate if we should be deploying skeleton or implementation * * @return */ public boolean isSkeletonWanted() { return bDeploySkeleton; } // isSkeletonWanted /** * Turn on/off Helper class generation * * @param value */ public void setHelperWanted(boolean value) { bHelperGeneration = value; } // setHelperWanted /** * Indicate if we should be generating Helper classes * * @return */ public boolean isHelperWanted() { return bHelperGeneration; } // isHelperWanted /** * Turn on/off test case creation * * @param value */ public void setTestCaseWanted(boolean value) { this.bEmitTestCase = value; } // setTestCaseWanted /** * Method isTestCaseWanted * * @return */ public boolean isTestCaseWanted() { return bEmitTestCase; } // isTestCaseWanted /** * get the build file genaeration state * @return */ public boolean isBuildFileWanted(){ return bBuildFileGeneration; } /** * turn the build file genaration ON * @param value */ public void setBuildFileWanted(boolean value){ bBuildFileGeneration = value; } /** * By default, code is generated only for referenced elements. * Call bGenerateAll(true) and WSDL2Java will generate code for all * elements in the scope regardless of whether they are * referenced. Scope means: by default, all WSDL files; if * generateImports(false), then only the immediate WSDL file. * * @param all */ public void setAllWanted(boolean all) { bGenerateAll = all; } // setAllWanted /** * Method isAllWanted * * @return */ public boolean isAllWanted() { return bGenerateAll; } // isAllWanted /** * Method getNamespaces * * @return */ public Namespaces getNamespaces() { return namespaces; } // getNamespaces /** * Set the output directory to use in emitted source files * * @param outputDir */ public void setOutputDir(String outputDir) { this.outputDir = outputDir; } /** * Get the output directory to use for emitted source files * * @return */ public String getOutputDir() { return outputDir; } /** * Get global package name to use instead of mapping namespaces * * @return */ public String getPackageName() { return packageName; } /** * Set a global package name to use instead of mapping namespaces * * @param packageName */ public void setPackageName(String packageName) { this.packageName = packageName; } /** * Set the scope for the deploy.xml file. * * @param scope One of 'null', * Scope.APPLICATION, Scope.REQUEST, Scope.SESSION. * Anything else is equivalent to 'null' null and no explicit * scope tag will appear in deploy.xml. */ public void setScope(Scope scope) { this.scope = scope; } // setScope /** * Get the scope for the deploy.xml file. * * @return */ public Scope getScope() { return scope; } // getScope /** * Set the NStoPkg mappings filename. * * @param NStoPkgFilename */ public void setNStoPkg(String NStoPkgFilename) { if (NStoPkgFilename != null) { this.NStoPkgFilename = NStoPkgFilename; } } // setNStoPkg /** * Set a map of namespace -&gt; Java package names * * @param map */ public void setNamespaceMap(HashMap map) { delayedNamespacesMap = map; } /** * Get the map of namespace -&gt; Java package names * * @return */ public HashMap getNamespaceMap() { return delayedNamespacesMap; } /** Sets the list of namespaces to specifically include * in the generated code. */ public void setNamespaceIncludes(List nsIncludes) { this.nsIncludes = nsIncludes; } /** Returns the list of namespaces specifically excluded * from the generated code. */ public List getNamespaceIncludes() { return this.nsIncludes; } /** Sets the list of namespaces to specifically exclude * from the generated source. */ public void setNamespaceExcludes(List nsExcludes) { this.nsExcludes = nsExcludes; } /** Returns the list of excludes to specifically exclude * from the generated source. */ public List getNamespaceExcludes() { return this.nsExcludes; } /** Sets the list of extension properties for custom * JavaGeneratorFactories. */ public void setProperties(List properties) { this.properties = properties; } /** Gets the list of extension properties for custom * JavaGeneratorFactories. */ public List getProperties() { return this.properties; } /** * Returns the default <code>TypeMapping</code> used by the service * * @return the default <code>TypeMapping</code> used by the service */ public TypeMapping getDefaultTypeMapping() { if (defaultTM == null) { defaultTM = (TypeMapping)tmr.getTypeMapping(Constants.URI_SOAP11_ENC); } return defaultTM; } /** * Sets the default <code>TypeMapping</code> used by the service * * @param defaultTM the default <code>TypeMapping</code> used by the service */ public void setDefaultTypeMapping(TypeMapping defaultTM) { this.defaultTM = defaultTM; } /** * Sets the <code>WriterFactory Class</code> to use * * @param factory the name of the factory <code>Class</code> */ public void setFactory(String factory) { try { Class clazz = ClassUtils.forName(factory); GeneratorFactory genFac; try { Constructor ctor = clazz.getConstructor(new Class[]{ getClass()}); genFac = (GeneratorFactory) ctor.newInstance(new Object[]{ this}); } catch (NoSuchMethodException ex) { genFac = (GeneratorFactory) clazz.newInstance(); } setFactory(genFac); } catch (Exception ex) { ex.printStackTrace(); } } // setFactory // // Command line switches // // ///////////////////////////////////////////////// /** * Returns an object which contains of information on all generated files * including the class name, filename and a type string. * * @return An org.apache.axis.wsdl.toJava.GeneratedFileInfo object * @see org.apache.axis.wsdl.toJava.GeneratedFileInfo */ public GeneratedFileInfo getGeneratedFileInfo() { return fileInfo; } /** * This method returns a list of all generated class names. * * @return */ public List getGeneratedClassNames() { return fileInfo.getClassNames(); } /** * This method returns a list of all generated file names. * * @return */ public List getGeneratedFileNames() { return fileInfo.getFileNames(); } /** * Get the Package name for the specified namespace * * @param namespace * @return */ public String getPackage(String namespace) { return namespaces.getCreate(namespace); } /** * Get the Package name for the specified QName * * @param qName * @return */ public String getPackage(QName qName) { return getPackage(qName.getNamespaceURI()); } /** * Convert the specified QName into a full Java Name. * * @param qName * @return */ public String getJavaName(QName qName) { // If this is one of our special 'collection' qnames. // get the element type and append [] if (qName.getLocalPart().indexOf("[") > 0) { String localPart = qName.getLocalPart().substring(0, qName.getLocalPart().indexOf("[")); QName eQName = new QName(qName.getNamespaceURI(), localPart); return getJavaName(eQName) + "[]"; } // Handle the special "java" namespace for types if (qName.getNamespaceURI().equalsIgnoreCase("java")) { return qName.getLocalPart(); } // The QName may represent a base java name, so check this first String fullJavaName = getFactory().getBaseTypeMapping().getBaseName(qName); if (fullJavaName != null) { return fullJavaName; } fullJavaName = getJavaNameHook(qName); if (fullJavaName != null) { return fullJavaName; } // Use the namespace uri to get the appropriate package String pkg = getPackage(qName.getNamespaceURI()); if (pkg != null && pkg.length() > 0) { fullJavaName = pkg + "." + Utils.xmlNameToJavaClass(qName.getLocalPart()); } else { fullJavaName = Utils.xmlNameToJavaClass(qName.getLocalPart()); } return fullJavaName; } // getJavaName protected String getJavaNameHook(QName qname) { return null; } /** * @param typeQName QName for containing xml type * @param xmlName QName for element * @return */ public String getJavaVariableName(QName typeQName, QName xmlName, boolean isElement) { String javaName = getJavaVariableNameHook(typeQName, xmlName, isElement); if (javaName == null) { String elemName = Utils.getLastLocalPart(xmlName.getLocalPart()); javaName = JavaUtils.xmlNameToJava(elemName); } return javaName; } protected String getJavaVariableNameHook(QName typeQName, QName xmlName, boolean isElement) { return null; } /** * Emit appropriate Java files for a WSDL at a given URL. * <p> * This method will time out after the number of milliseconds specified * by our timeoutms member. * * @param wsdlURL * @throws Exception */ public void run(String wsdlURL) throws Exception { setup(); super.run(wsdlURL); } // run /** * Call this method if your WSDL document has already been * parsed as an XML DOM document. * * @param context context This is directory context for the Document. * If the Document were from file "/x/y/z.wsdl" then the context * could be "/x/y" (even "/x/y/z.wsdl" would work). * If context is null, then the context becomes the current directory. * @param doc doc This is the XML Document containing the WSDL. * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException */ public void run(String context, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { setup(); super.run(context, doc); } // run /** * Method setup * * @throws IOException */ private void setup() throws IOException { tmr.doRegisterFromVersion(typeMappingVersion); namespaces = new Namespaces(outputDir); if (packageName != null) { namespaces.setDefaultPackage(packageName); } else { // First, read the namespace mapping file - configurable, by default // NStoPkg.properties - if it exists, and load the namespaceMap HashMap // with its data. getNStoPkgFromPropsFile(namespaces); if (delayedNamespacesMap != null) { namespaces.putAll(delayedNamespacesMap); } } } // setup /** * Method sanityCheck * * @param symbolTable */ protected void sanityCheck(SymbolTable symbolTable) { Iterator it = symbolTable.getHashMap().values().iterator(); while (it.hasNext()) { Vector v = (Vector) it.next(); for (int i = 0; i < v.size(); ++i) { SymTabEntry entry = (SymTabEntry) v.elementAt(i); String namespace = entry.getQName().getNamespaceURI(); String packageName = org.apache.axis.wsdl.toJava.Utils.makePackageName( namespace); String localName = entry.getQName().getLocalPart(); if (localName.equals(packageName) && packageName.equals( namespaces.getCreate(namespace))) { packageName += "_pkg"; namespaces.put(namespace, packageName); } } } } /** * Tries to load the namespace-to-package mapping file. * <ol> * <li>if a file name is explicitly set using <code>setNStoPkg()</code>, tries * to load the mapping from this file. If this fails, the built-in default * mapping is used. * <p/> * <li>if no file name is set, tries to load the file <code>DEFAULT_NSTOPKG_FILE</code> * as a java resource. If this fails, the built-in dfault mapping is used. * </ol> * * @param namespaces a hashmap which is filled with the namespace-to-package mapping * in this method * @throws IOException * @see #setNStoPkg(String) * @see #DEFAULT_NSTOPKG_FILE * @see org.apache.axis.utils.ClassUtils#getResourceAsStream(java.lang.Class,String) */ private void getNStoPkgFromPropsFile(HashMap namespaces) throws IOException { Properties mappings = new Properties(); if (NStoPkgFilename != null) { try { mappings.load(new FileInputStream(NStoPkgFilename)); if (verbose) { System.out.println( Messages.getMessage( "nsToPkgFileLoaded00", NStoPkgFilename)); } } catch (Throwable t) { // loading the custom mapping file failed. We do not try // to load the mapping from a default mapping file. throw new IOException( Messages.getMessage( "nsToPkgFileNotFound00", NStoPkgFilename)); } } else { try { mappings.load(new FileInputStream(DEFAULT_NSTOPKG_FILE)); if (verbose) { System.out.println( Messages.getMessage( "nsToPkgFileLoaded00", DEFAULT_NSTOPKG_FILE)); } } catch (Throwable t) { try { mappings.load(ClassUtils.getResourceAsStream(Emitter.class, DEFAULT_NSTOPKG_FILE)); if (verbose) { System.out.println( Messages.getMessage( "nsToPkgDefaultFileLoaded00", DEFAULT_NSTOPKG_FILE)); } } catch (Throwable t1) { // loading the default mapping file failed. // The built-in default mapping is used // No message is given, since this is generally what happens } } } Enumeration keys = mappings.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); namespaces.put(key, mappings.getProperty(key)); } } // getNStoPkgFromPropsFile /** * Get the typemapping version */ public String getTypeMappingVersion() { return typeMappingVersion; } /** * Method setTypeMappingVersion * * @param typeMappingVersion */ public void setTypeMappingVersion(String typeMappingVersion) { this.typeMappingVersion = typeMappingVersion; } // The remainder are deprecated methods. /** * Get the GeneratorFactory. * * @return * @deprecated Call getFactory instead. This doesn't return * a WriterFactory, it returns a GeneratorFactory. */ public GeneratorFactory getWriterFactory() { return getFactory(); } // getWriterFactory /** * Call this method if you have a uri for the WSDL document * * @param uri wsdlURI the location of the WSDL file. * @throws Exception * @deprecated Call run(uri) instead. */ public void emit(String uri) throws Exception { run(uri); } // emit /** * Call this method if your WSDL document has already been * parsed as an XML DOM document. * * @param context context This is directory context for the Document. * If the Document were from file "/x/y/z.wsdl" then the context could be "/x/y" * (even "/x/y/z.wsdl" would work). If context is null, then the context * becomes the current directory. * @param doc doc This is the XML Document containing the WSDL. * @throws IOException * @throws SAXException * @throws WSDLException * @throws ParserConfigurationException * @deprecated Call run(context, doc) instead. */ public void emit(String context, Document doc) throws IOException, SAXException, WSDLException, ParserConfigurationException { run(context, doc); } // emit /** * Turn on/off server-side binding generation * * @param value * @deprecated Use setServerSide(value) */ public void generateServerSide(boolean value) { setServerSide(value); } /** * Indicate if we should be emitting server side code and deploy/undeploy * * @return * @deprecated Use isServerSide() */ public boolean getGenerateServerSide() { return isServerSide(); } /** * Turn on/off server skeleton deploy * * @param value * @deprecated Use setSkeletonWanted(value) */ public void deploySkeleton(boolean value) { setSkeletonWanted(value); } /** * Indicate if we should be deploying skeleton or implementation * * @return * @deprecated Use isSkeletonWanted() */ public boolean getDeploySkeleton() { return isSkeletonWanted(); } /** * Turn on/off Helper class generation * * @param value * @deprecated Use setHelperWanted(value) */ public void setHelperGeneration(boolean value) { setHelperWanted(value); } /** * Indicate if we should be generating Helper classes * * @return * @deprecated Use isHelperWanted() */ public boolean getHelperGeneration() { return isHelperWanted(); } /** * Turn on/off generation of elements from imported files. * * @param generateImports * @deprecated Use setImports(generateImports) */ public void generateImports(boolean generateImports) { setImports(generateImports); } // generateImports /** * Turn on/off debug messages. * * @param value * @deprecated Use setDebug(value) */ public void debug(boolean value) { setDebug(value); } // debug /** * Return the status of the debug switch. * * @return * @deprecated Use isDebug() */ public boolean getDebug() { return isDebug(); } // getDebug /** * Turn on/off verbose messages * * @param value * @deprecated Use setVerbose(value) */ public void verbose(boolean value) { setVerbose(value); } /** * Return the status of the verbose switch * * @return * @deprecated Use isVerbose() */ public boolean getVerbose() { return isVerbose(); } /** * Turn on/off test case creation * * @param value * @deprecated Use setTestCaseWanted() */ public void generateTestCase(boolean value) { setTestCaseWanted(value); } /** * @param all * @deprecated Use setAllWanted(all) */ public void generateAll(boolean all) { setAllWanted(all); } // generateAll /** * Get the type collision protection setting * @return */ public boolean isTypeCollisionProtection(){ return this.typeCollisionProtection; } /** * Enable/disable type collision protection * @param value */ public void setTypeCollisionProtection(boolean value){ this.typeCollisionProtection = value; } /** * Get an implementation classname to use instead of the default. * @return */ public String getImplementationClassName() { return implementationClassName; } /** * Set an implementation classname to use instead of the default. * * @param implementationClassName */ public void setImplementationClassName(String implementationClassName) { this.implementationClassName = implementationClassName; } /** * @return Returns the allowInvalidURL. */ public boolean isAllowInvalidURL() { return allowInvalidURL; } /** * @param allowInvalidURL The allowInvalidURL to set. */ public void setAllowInvalidURL(boolean allowInvalidURL) { this.allowInvalidURL = allowInvalidURL; } /** * Set the type qname to java class map * @param map a type qname to javaclass map (from Java2Wsdl emitter) */ public void setQName2ClassMap(HashMap map) { qName2ClassMap = map; } /** * Get the type qname to java class map * @return the type qname to java class map */ public HashMap getQName2ClassMap() { return qName2ClassMap; } /** * Retruns the SericeDesc object * @return */ public ServiceDesc getServiceDesc() { return serviceDesc; } /** * Sets the ServicdDesc object * @param serviceDesc ServiceDesc to set */ public void setServiceDesc(ServiceDesc serviceDesc) { this.serviceDesc = serviceDesc; } /** * Returns the deploy mode flag * @return */ public boolean isDeploy() { return isDeploy; } /** * Sets the deploy mode flag * @param isDeploy deploy mode flag */ public void setDeploy(boolean isDeploy) { this.isDeploy = isDeploy; } /** * Check if the className exists. * * @param className className to check * @return true if exists, false if not */ protected boolean doesExist(String className) { try { ClassUtils.forName(className); } catch (ClassNotFoundException e) { return false; } return true; } public void setWrapArrays(boolean wrapArrays) { this.wrapArrays = wrapArrays; } }
6,895
0
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport/jms/JMSConstants.java
/* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.transport.jms; import javax.jms.DeliveryMode; import javax.jms.Message; import javax.jms.Session; /** * JMSConstants contains constants that apply to all JMS providers. * * <code>JMSConstants</code> contains the constant definitions for * interacting with the WSClient. The most important constants are the * <code>HashMap</code> keys for use in the arguments to the * <code>send, call, registerListener, unregisterListener</code> methods of * <code>JMSEndpoint</code> and the <code>createConnector</code> method of * <code>JMSConnectorFactory</code>. * * @author Jaime Meritt (jmeritt@sonicsoftware.com) * @author Richard Chung (rchung@sonicsoftware.com) * @author Dave Chappell (chappell@sonicsoftware.com) * @author Ray Chun (rchun@sonicsoftware.com) */ public interface JMSConstants { public final static String PROTOCOL = "jms"; // abbreviated version of all constants (see below for description of each constant) // the short name is used in the JMS URL. the full name is used in the Axis call. final static String _WAIT_FOR_RESPONSE = "waitForResponse"; final static String _CLIENT_ID = "clientID"; final static String _VENDOR = "vendor"; final static String _DOMAIN = "domain"; final static String _JMS_CORRELATION_ID = "jmsCorrelationID"; final static String _JMS_CORRELATION_ID_AS_BYTES = "jmsCorrelationIDAsBytes"; final static String _JMS_TYPE = "jmsType"; final static String _TIME_TO_LIVE = "ttl"; final static String _PRIORITY = "priority"; final static String _DELIVERY_MODE = "deliveryMode"; final static String _MESSAGE_SELECTOR = "messageSelector"; final static String _ACKNOWLEDGE_MODE = "acknowledgeMode"; final static String _SUBSCRIPTION_NAME = "subscriptionName"; final static String _UNSUBSCRIBE = "unsubscribe"; final static String _NO_LOCAL = "noLocal"; final static String _NUM_RETRIES = "numRetries"; final static String _NUM_SESSIONS = "numSessions"; final static String _CONNECT_RETRY_INTERVAL = "connectRetryInterval"; final static String _INTERACT_RETRY_INTERVAL = "interactRetryInterval"; final static String _TIMEOUT_TIME = "timeoutTime"; final static String _MIN_TIMEOUT_TIME = "minTimeoutTime"; /** Defines a prefix added to each application-specific property in the * JMS URL that should be added to the JMS Message when issued. */ final static String _MSG_PROP_PREFIX = "msgProp."; public static String JMS_PROPERTY_PREFIX = "transport.jms."; /** * This is used as a key in the Call properties telling the JMS transport * to wait for a response from the service. The default value is true. * If false is specified, the message will be delivered without specifying * a ReplyTo. The client will always return null from invoke unless * a client-side exception is thrown (similar to invokeOneWay in semantics) * The value must be a <code>java.lang.Boolean</code>. * See the javax.jms javadoc for information on this property. */ final static String WAIT_FOR_RESPONSE = JMS_PROPERTY_PREFIX + _WAIT_FOR_RESPONSE; /** * <code>JMSConnectorFactory</code> parameter valid for either domain. This should * be used as a key in the environment map passed into calls to * <code>createConnector</code> in <code>JMSConnectorFactory</code> * This is a required property for durable subscribers. * The value must be a <code>java.lang.String</code>. * See the javax.jms javadoc for information on this property. */ final static String CLIENT_ID = JMS_PROPERTY_PREFIX + _CLIENT_ID; // there is no short version final static String DESTINATION = JMS_PROPERTY_PREFIX + "Destination"; final static String VENDOR = JMS_PROPERTY_PREFIX + _VENDOR; public final static String JNDI_VENDOR_ID = "JNDI"; final static String DOMAIN = JMS_PROPERTY_PREFIX + _DOMAIN; final static String DOMAIN_QUEUE = "QUEUE"; final static String DOMAIN_TOPIC = "TOPIC"; final static String DOMAIN_DEFAULT = DOMAIN_QUEUE; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>java.lang.String</code>. * See the javax.jms javadoc for information on this property. */ final static String JMS_CORRELATION_ID = JMS_PROPERTY_PREFIX + _JMS_CORRELATION_ID; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>byte[]</code>. * See the javax.jms javadoc for information on this property. */ final static String JMS_CORRELATION_ID_AS_BYTES = JMS_PROPERTY_PREFIX + _JMS_CORRELATION_ID_AS_BYTES; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>java.lang.String</code>. * See the javax.jms javadoc for information on this property. */ final static String JMS_TYPE = JMS_PROPERTY_PREFIX + _JMS_TYPE; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>java.lang.Long</code>. * See the javax.jms javadoc for information on this property. */ final static String TIME_TO_LIVE = JMS_PROPERTY_PREFIX + _TIME_TO_LIVE; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>java.lang.Integer</code>. * See the javax.jms javadoc for information on this property. */ final static String PRIORITY = JMS_PROPERTY_PREFIX + _PRIORITY; /** * Key for properties used in the <code>send</code> and <code>call</code> * methods. It is valid for either domain. * The value must be a <code>java.lang.Integer</code> equal to * DeliveryMode.NON_PERSISTENT or DeliveryMode.PERSISTENT. * See the javax.jms javadoc for information on this property. */ final static String DELIVERY_MODE = JMS_PROPERTY_PREFIX + _DELIVERY_MODE; final static String DELIVERY_MODE_PERSISTENT = "Persistent"; final static String DELIVERY_MODE_NONPERSISTENT = "Nonpersistent"; final static String DELIVERY_MODE_DISCARDABLE = "Discardable"; final static int DEFAULT_DELIVERY_MODE = DeliveryMode.NON_PERSISTENT; final static int DEFAULT_PRIORITY = Message.DEFAULT_PRIORITY; final static long DEFAULT_TIME_TO_LIVE = Message.DEFAULT_TIME_TO_LIVE; /** * Key for properties used in the <code>registerListener</code> * method. It is valid for either domain. * The value must be a <code>java.lang.String</code>. * See the javax.jms javadoc for information on this property. */ final static String MESSAGE_SELECTOR = JMS_PROPERTY_PREFIX + _MESSAGE_SELECTOR; /** * Key for properties used in the <code>registerListener</code> * method. It is valid for either domain. * The value must be a <code>java.lang.Integer</code> that is one of * Session.AUTO_ACKNOWLEDGE, Session.DUPS_OK_ACKNOWLEDGE, * or Session.CLIENT_ACKNOWLEDGE. * See the javax.jms javadoc for information on this property. */ final static String ACKNOWLEDGE_MODE = JMS_PROPERTY_PREFIX + _ACKNOWLEDGE_MODE; /** * value for ACKNOWLEDGE_MODE if left unset. It is equal to * Session.DUPS_OK_ACKNOWLEDGE. */ final static int DEFAULT_ACKNOWLEDGE_MODE = Session.DUPS_OK_ACKNOWLEDGE; /** * Specifies the name of a durable subscription * Key for properties used in the <code>registerListener</code> * method. It is valid for the PubSub domain. * The value must be a <code>java.lang.String</code>. */ final static String SUBSCRIPTION_NAME = JMS_PROPERTY_PREFIX + _SUBSCRIPTION_NAME; /** * Key for properties used in the <code>registerListener</code> * method. It is valid for the PubSub domain. * Specifies that the durable subscription should be unsubscribed * (deleted from the broker) when unregistered. * The value must be a <code>java.lang.Boolean</code>. */ final static String UNSUBSCRIBE = JMS_PROPERTY_PREFIX + _UNSUBSCRIBE; /** * Key for properties used in the <code>registerListener</code> * method. It is valid for the PubSub domain. * The value must be a <code>java.lang.Boolean</code>. */ final static String NO_LOCAL = JMS_PROPERTY_PREFIX + _NO_LOCAL; final static boolean DEFAULT_NO_LOCAL = false; final static boolean DEFAULT_UNSUBSCRIBE = false; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Integer</code>. */ final static String NUM_RETRIES = JMS_PROPERTY_PREFIX + _NUM_RETRIES; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Integer</code>. */ final static String NUM_SESSIONS = JMS_PROPERTY_PREFIX + _NUM_SESSIONS; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Long</code>. */ final static String CONNECT_RETRY_INTERVAL = JMS_PROPERTY_PREFIX + _CONNECT_RETRY_INTERVAL; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Long</code>. */ final static String INTERACT_RETRY_INTERVAL = JMS_PROPERTY_PREFIX + _INTERACT_RETRY_INTERVAL; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Long</code>. */ final static String TIMEOUT_TIME = JMS_PROPERTY_PREFIX + _TIMEOUT_TIME; /** * Key for properties used in the <code>createConnector</code> * method. It changes the behavior of the wsclient. * The value must be a <code>java.lang.Long</code>. */ final static String MIN_TIMEOUT_TIME = JMS_PROPERTY_PREFIX + _MIN_TIMEOUT_TIME; final static int DEFAULT_NUM_RETRIES = 5; final static int DEFAULT_NUM_SESSIONS = 5; final static long DEFAULT_CONNECT_RETRY_INTERVAL = 2000; final static long DEFAULT_TIMEOUT_TIME = 5000; final static long DEFAULT_MIN_TIMEOUT_TIME = 1000; final static long DEFAULT_INTERACT_RETRY_INTERVAL = 250; // key used to store the JMS connector in the message context final static String CONNECTOR = JMS_PROPERTY_PREFIX + "Connector"; // key used to store the JMS vendor adapter in the message context final static String VENDOR_ADAPTER = JMS_PROPERTY_PREFIX + "VendorAdapter"; // key used to store the JMS URL string in the message context final static String JMS_URL = JMS_PROPERTY_PREFIX + "EndpointAddress"; /** A property that carries a Map of application-specific properties to be * added to the JMS messages when issued. */ final static String JMS_APPLICATION_MSG_PROPS = JMS_PROPERTY_PREFIX + "msgProps"; final static String ADAPTER_POSTFIX = "VendorAdapter"; }
6,896
0
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport/jms/InvokeTimeoutException.java
/* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.transport.jms; /** * The <code>InvokeTimeoutException</code> is thrown when a method cannot * complete processing within the time allotted. This occurs most often * when the broker has failed and the client is unable to reconnect. This * may be thrown from any method within the wsclient that interacts with the * broker. The timeout is defined within the environment parameter to * <code>createConnector</code> method in <code>JMSConnectorFactory</code> * The key in the table is <code>IJMSConstants.INTERACT_TIMEOUT_TIME</code> * * @author Jaime Meritt (jmeritt@sonicsoftware.com) * @author Richard Chung (rchung@sonicsoftware.com) * @author Dave Chappell (chappell@sonicsoftware.com) * */ public class InvokeTimeoutException extends InvokeException { public InvokeTimeoutException(String message) { super(message); } }
6,897
0
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport/jms/InvokeException.java
/* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.transport.jms; /** * The <code>InvokeException</code> is thrown when a method encounters a * general exception in the course of processing. * @author Jaime Meritt (jmeritt@sonicsoftware.com) * @author Richard Chung (rchung@sonicsoftware.com) * @author Dave Chappell (chappell@sonicsoftware.com) */ public class InvokeException extends RuntimeException { public InvokeException(String message) { super(message); } }
6,898
0
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport
Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/transport/jms/QueueConnector.java
/* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.transport.jms; import org.apache.axis.components.jms.JMSVendorAdapter; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueReceiver; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TemporaryQueue; /** * QueueConnector is a concrete JMSConnector subclass that specifically handles * connections to queues (ptp domain). * * @author Jaime Meritt (jmeritt@sonicsoftware.com) * @author Richard Chung (rchung@sonicsoftware.com) * @author Dave Chappell (chappell@sonicsoftware.com) */ public class QueueConnector extends JMSConnector { public QueueConnector(ConnectionFactory factory, int numRetries, int numSessions, long connectRetryInterval, long interactRetryInterval, long timeoutTime, boolean allowReceive, String clientID, String username, String password, JMSVendorAdapter adapter, JMSURLHelper jmsurl) throws JMSException { super(factory, numRetries, numSessions, connectRetryInterval, interactRetryInterval, timeoutTime, allowReceive, clientID, username, password, adapter, jmsurl); } public JMSEndpoint createEndpoint(String destination) { return new QueueEndpoint(destination); } /** * Create an endpoint for a queue destination. * * @param destination * @return * @throws JMSException */ public JMSEndpoint createEndpoint(Destination destination) throws JMSException { if(!(destination instanceof Queue)) throw new IllegalArgumentException("The input must be a queue for this connector"); return new QueueDestinationEndpoint((Queue)destination); } protected Connection internalConnect(ConnectionFactory connectionFactory, String username, String password) throws JMSException { QueueConnectionFactory qcf = (QueueConnectionFactory)connectionFactory; if(username == null) return qcf.createQueueConnection(); return qcf.createQueueConnection(username, password); } protected SyncConnection createSyncConnection(ConnectionFactory factory, Connection connection, int numSessions, String threadName, String clientID, String username, String password) throws JMSException { return new QueueSyncConnection((QueueConnectionFactory)factory, (QueueConnection)connection, numSessions, threadName, clientID, username, password); } private QueueSession createQueueSession(QueueConnection connection, int ackMode) throws JMSException { return connection.createQueueSession(false, ackMode); } private Queue createQueue(QueueSession session, String subject) throws Exception { return m_adapter.getQueue(session, subject); } private QueueReceiver createReceiver(QueueSession session, Queue queue, String messageSelector) throws JMSException { return session.createReceiver(queue, messageSelector); } private final class QueueSyncConnection extends SyncConnection { QueueSyncConnection(QueueConnectionFactory connectionFactory, QueueConnection connection, int numSessions, String threadName, String clientID, String username, String password) throws JMSException { super(connectionFactory, connection, numSessions, threadName, clientID, username, password); } protected SendSession createSendSession(javax.jms.Connection connection) throws JMSException { QueueSession session = createQueueSession((QueueConnection)connection, JMSConstants.DEFAULT_ACKNOWLEDGE_MODE); QueueSender sender = session.createSender(null); return new QueueSendSession(session, sender); } private final class QueueSendSession extends SendSession { QueueSendSession(QueueSession session, QueueSender sender) throws JMSException { super(session, sender); } protected MessageConsumer createConsumer(Destination destination) throws JMSException { return createReceiver((QueueSession)m_session, (Queue)destination, null); } protected Destination createTemporaryDestination() throws JMSException { return ((QueueSession)m_session).createTemporaryQueue(); } protected void deleteTemporaryDestination(Destination destination) throws JMSException { ((TemporaryQueue)destination).delete(); } protected void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException { ((QueueSender)m_producer).send((Queue)destination, message, deliveryMode, priority, timeToLive); } } } private class QueueEndpoint extends JMSEndpoint { String m_queueName; QueueEndpoint(String queueName) { super(QueueConnector.this); m_queueName = queueName; } Destination getDestination(Session session) throws Exception { return createQueue((QueueSession)session, m_queueName); } public String toString() { StringBuffer buffer = new StringBuffer("QueueEndpoint:"); buffer.append(m_queueName); return buffer.toString(); } public boolean equals(Object object) { if(!super.equals(object)) return false; if(!(object instanceof QueueEndpoint)) return false; return m_queueName.equals(((QueueEndpoint)object).m_queueName); } } private final class QueueDestinationEndpoint extends QueueEndpoint { Queue m_queue; QueueDestinationEndpoint(Queue queue) throws JMSException { super(queue.getQueueName()); m_queue = queue; } Destination getDestination(Session session) { return m_queue; } } protected AsyncConnection createAsyncConnection(ConnectionFactory factory, Connection connection, String threadName, String clientID, String username, String password) throws JMSException { return new QueueAsyncConnection((QueueConnectionFactory)factory, (QueueConnection)connection, threadName, clientID, username, password); } private final class QueueAsyncConnection extends AsyncConnection { QueueAsyncConnection(QueueConnectionFactory connectionFactory, QueueConnection connection, String threadName, String clientID, String username, String password) throws JMSException { super(connectionFactory, connection, threadName, clientID, username, password); } protected ListenerSession createListenerSession(javax.jms.Connection connection, Subscription subscription) throws Exception { QueueSession session = createQueueSession((QueueConnection)connection, subscription.m_ackMode); QueueReceiver receiver = createReceiver(session, (Queue)subscription.m_endpoint.getDestination(session), subscription.m_messageSelector); return new ListenerSession(session, receiver, subscription); } } }
6,899