index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/axis-axis1-java/axis-rt-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/JMSConnectorFactory.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 org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import java.util.HashMap;
/**
* JMSConnectorFactory is a factory class for creating JMSConnectors. It can
* create both client connectors and server connectors. A server connector
* is configured to allow asynchronous message receipt, while a client
* connector is not.
*
* JMSConnectorFactory can also be used to select an appropriately configured
* JMSConnector from an existing pool of connectors.
*
* @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 abstract class JMSConnectorFactory
{
protected static Log log =
LogFactory.getLog(JMSConnectorFactory.class.getName());
/**
* Performs an initial check on the connector properties, and then defers
* to the vendor adapter for matching on the vendor-specific connection factory.
*
* @param connectors the list of potential matches
* @param connectorProps the set of properties to be used for matching the connector
* @param cfProps the set of properties to be used for matching the connection factory
* @param username the user requesting the connector
* @param password the password associated with the requesting user
* @param adapter the vendor adapter specified in the JMS URL
* @return a JMSConnector that matches the specified properties
*/
public static JMSConnector matchConnector(java.util.Set connectors,
HashMap connectorProps,
HashMap cfProps,
String username,
String password,
JMSVendorAdapter adapter)
{
java.util.Iterator iter = connectors.iterator();
while (iter.hasNext())
{
JMSConnector conn = (JMSConnector) iter.next();
// username
String connectorUsername = conn.getUsername();
if (!( ((connectorUsername == null) && (username == null)) ||
((connectorUsername != null) && (username != null) && (connectorUsername.equals(username))) ))
continue;
// password
String connectorPassword = conn.getPassword();
if (!( ((connectorPassword == null) && (password == null)) ||
((connectorPassword != null) && (password != null) && (connectorPassword.equals(password))) ))
continue;
// num retries
int connectorNumRetries = conn.getNumRetries();
String propertyNumRetries = (String)connectorProps.get(JMSConstants.NUM_RETRIES);
int numRetries = JMSConstants.DEFAULT_NUM_RETRIES;
if (propertyNumRetries != null)
numRetries = Integer.parseInt(propertyNumRetries);
if (connectorNumRetries != numRetries)
continue;
// client id
String connectorClientID = conn.getClientID();
String clientID = (String)connectorProps.get(JMSConstants.CLIENT_ID);
if (!( ((connectorClientID == null) && (clientID == null))
||
((connectorClientID != null) && (clientID != null) && connectorClientID.equals(clientID)) ))
continue;
// domain
String connectorDomain = (conn instanceof QueueConnector) ? JMSConstants.DOMAIN_QUEUE : JMSConstants.DOMAIN_TOPIC;
String propertyDomain = (String)connectorProps.get(JMSConstants.DOMAIN);
String domain = JMSConstants.DOMAIN_DEFAULT;
if (propertyDomain != null)
domain = propertyDomain;
if (!( ((connectorDomain == null) && (domain == null))
||
((connectorDomain != null) && (domain != null) && connectorDomain.equalsIgnoreCase(domain)) ))
continue;
// the connection factory must also match for the connector to be reused
JMSURLHelper jmsurl = conn.getJMSURL();
if (adapter.isMatchingConnectionFactory(conn.getConnectionFactory(), jmsurl, cfProps))
{
// attempt to reserve the connector
try
{
JMSConnectorManager.getInstance().reserve(conn);
if (log.isDebugEnabled()) {
log.debug("JMSConnectorFactory: Found matching connector");
}
}
catch (Exception e)
{
// ignore. the connector may be in the process of shutting down, so try the next element
continue;
}
return conn;
}
}
if (log.isDebugEnabled()) {
log.debug("JMSConnectorFactory: No matching connectors found");
}
return null;
}
/**
* Static method to create a server connector. Server connectors can
* accept incoming requests.
*
* @param connectorConfig
* @param cfConfig
* @param username
* @param password
* @return
* @throws Exception
*/
public static JMSConnector createServerConnector(HashMap connectorConfig,
HashMap cfConfig,
String username,
String password,
JMSVendorAdapter adapter)
throws Exception
{
return createConnector(connectorConfig, cfConfig, true,
username, password, adapter);
}
/**
* Static method to create a client connector. Client connectors cannot
* accept incoming requests.
*
* @param connectorConfig
* @param cfConfig
* @param username
* @param password
* @return
* @throws Exception
*/
public static JMSConnector createClientConnector(HashMap connectorConfig,
HashMap cfConfig,
String username,
String password,
JMSVendorAdapter adapter)
throws Exception
{
return createConnector(connectorConfig, cfConfig, false,
username, password, adapter);
}
private static JMSConnector createConnector(HashMap connectorConfig,
HashMap cfConfig,
boolean allowReceive,
String username,
String password,
JMSVendorAdapter adapter)
throws Exception
{
if(connectorConfig != null)
connectorConfig = (HashMap)connectorConfig.clone();
int numRetries = MapUtils.removeIntProperty(connectorConfig,
JMSConstants.NUM_RETRIES,
JMSConstants.DEFAULT_NUM_RETRIES);
int numSessions = MapUtils.removeIntProperty(connectorConfig,
JMSConstants.NUM_SESSIONS,
JMSConstants.DEFAULT_NUM_SESSIONS);
long connectRetryInterval = MapUtils.removeLongProperty(connectorConfig,
JMSConstants.CONNECT_RETRY_INTERVAL,
JMSConstants.DEFAULT_CONNECT_RETRY_INTERVAL);
long interactRetryInterval = MapUtils.removeLongProperty(connectorConfig,
JMSConstants.INTERACT_RETRY_INTERVAL,
JMSConstants.DEFAULT_INTERACT_RETRY_INTERVAL);
long timeoutTime = MapUtils.removeLongProperty(connectorConfig,
JMSConstants.TIMEOUT_TIME,
JMSConstants.DEFAULT_TIMEOUT_TIME);
String clientID = MapUtils.removeStringProperty(connectorConfig,
JMSConstants.CLIENT_ID,
null);
String domain = MapUtils.removeStringProperty(connectorConfig,
JMSConstants.DOMAIN,
JMSConstants.DOMAIN_DEFAULT);
// this will be set if the target endpoint address was set on the Axis call
JMSURLHelper jmsurl = (JMSURLHelper)connectorConfig.get(JMSConstants.JMS_URL);
if(cfConfig == null)
throw new IllegalArgumentException("noCfConfig");
if(domain.equals(JMSConstants.DOMAIN_QUEUE))
{
return new QueueConnector(adapter.getQueueConnectionFactory(cfConfig),
numRetries, numSessions, connectRetryInterval,
interactRetryInterval, timeoutTime,
allowReceive, clientID, username, password,
adapter, jmsurl);
}
else // domain is Topic
{
return new TopicConnector(adapter.getTopicConnectionFactory(cfConfig),
numRetries, numSessions, connectRetryInterval,
interactRetryInterval, timeoutTime,
allowReceive, clientID, username, password,
adapter, jmsurl);
}
}
} | 6,900 |
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/SimpleJMSWorker.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.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* SimpleJMSWorker is a worker thread that processes messages that are
* received by SimpleJMSListener. It creates a new message context, invokes
* the server, and sends back response msg to the replyTo destination.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class SimpleJMSWorker implements Runnable
{
protected static Log log =
LogFactory.getLog(SimpleJMSWorker.class.getName());
SimpleJMSListener listener;
BytesMessage message;
public SimpleJMSWorker(SimpleJMSListener listener, BytesMessage message)
{
this.listener = listener;
this.message = message;
}
/**
* This is where the incoming message is processed.
*/
public void run()
{
InputStream in = null;
try
{
// get the incoming msg content into a byte array
byte[] buffer = new byte[8 * 1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
for(int bytesRead = message.readBytes(buffer);
bytesRead != -1; bytesRead = message.readBytes(buffer))
{
out.write(buffer, 0, bytesRead);
}
in = new ByteArrayInputStream(out.toByteArray());
}
catch(Exception e)
{
log.error(Messages.getMessage("exception00"), e);
e.printStackTrace();
return;
}
// create the msg and context and invoke the server
AxisServer server = SimpleJMSListener.getAxisServer();
// if the incoming message has a contentType set,
// pass it to my new Message
String contentType = null;
try
{
contentType = message.getStringProperty("contentType");
}
catch(Exception e)
{
e.printStackTrace();
}
Message msg = null;
if(contentType != null && !contentType.trim().equals(""))
{
msg = new Message(in, true, contentType, null);
}
else
{
msg = new Message(in);
}
MessageContext msgContext = new MessageContext(server);
msgContext.setRequestMessage( msg );
try
{
server.invoke( msgContext );
msg = msgContext.getResponseMessage();
}
catch (AxisFault af)
{
msg = new Message(af);
msg.setMessageContext(msgContext);
}
catch (Exception e)
{
msg = new Message(new AxisFault(e.toString()));
msg.setMessageContext(msgContext);
}
try
{
// now we need to send the response
Destination destination = message.getJMSReplyTo();
if(destination == null)
return;
JMSEndpoint replyTo = listener.getConnector().createEndpoint(destination);
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
replyTo.send(out.toByteArray());
}
catch(Exception e)
{
e.printStackTrace();
}
if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null)
// why then, quit!
try {listener.shutdown();} catch (Exception e) {}
}
}
| 6,901 |
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/Handler.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 java.net.URL;
import java.net.URLConnection;
/**
* URLStreamHandler for the "jms" protocol
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class Handler
extends java.net.URLStreamHandler
{
static {
// register the JMSTransport class
org.apache.axis.client.Call.setTransportForProtocol(JMSConstants.PROTOCOL, org.apache.axis.transport.jms.JMSTransport.class);
}
/**
* Reassembles the URL string, in the form "jms:/<dest>?prop1=value1&prop2=value2&..."
*/
protected String toExternalForm(URL url) {
String destination = url.getPath().substring(1);
String query = url.getQuery();
StringBuffer jmsurl = new StringBuffer(JMSConstants.PROTOCOL + ":/");
jmsurl.append(destination).append("?").append(query);
return jmsurl.toString();
}
protected URLConnection openConnection(URL url) {
return new JMSURLConnection(url);
}
} | 6,902 |
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/MapUtils.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 java.util.Map;
/**
* MapUtils provides convenience methods for accessing a java.util.Map
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class MapUtils
{
/**
* Returns an int property from a Map and removes it.
*
* @param properties
* @param key
* @param defaultValue
* @return
*/
public static int removeIntProperty(Map properties, String key, int defaultValue)
{
int value = defaultValue;
if(properties != null && properties.containsKey(key))
{
try{value = ((Integer)properties.remove(key)).intValue();}catch(Exception ignore){}
}
return value;
}
/**
* Returns a long property from a Map and removes it.
*
* @param properties
* @param key
* @param defaultValue
* @return
*/
public static long removeLongProperty(Map properties, String key, long defaultValue)
{
long value = defaultValue;
if(properties != null && properties.containsKey(key))
{
try{value = ((Long)properties.remove(key)).longValue();}catch(Exception ignore){}
}
return value;
}
/**
* Returns a String property from a Map and removes it.
*
* @param properties
* @param key
* @param defaultValue
* @return
*/
public static String removeStringProperty(Map properties, String key, String defaultValue)
{
String value = defaultValue;
if(properties != null && properties.containsKey(key))
{
try{value = (String)properties.remove(key);}catch(Exception ignore){}
}
return value;
}
/**
* Returns a boolean property from a Map and removes it.
*
* @param properties
* @param key
* @param defaultValue
* @return
*/
public static boolean removeBooleanProperty(Map properties, String key, boolean defaultValue)
{
boolean value = defaultValue;
if(properties != null && properties.containsKey(key))
{
try{value = ((Boolean)properties.remove(key)).booleanValue();}catch(Exception ignore){}
}
return value;
}
/**
* Returns an Object property from a Map and removes it.
*
* @param properties
* @param key
* @param defaultValue
* @return
*/
public static Object removeObjectProperty(Map properties, String key, Object defaultValue)
{
Object value = defaultValue;
if(properties != null && properties.containsKey(key))
{
value = properties.remove(key);
}
return value;
}
}
| 6,903 |
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/TopicConnector.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.MessageListener;
import javax.jms.Session;
import javax.jms.TemporaryTopic;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import java.util.HashMap;
/**
* TopicConnector is a concrete JMSConnector subclass that specifically handles
* connections to topics (pub-sub domain).
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class TopicConnector extends JMSConnector
{
public TopicConnector(TopicConnectionFactory 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);
}
protected Connection internalConnect(ConnectionFactory connectionFactory,
String username, String password)
throws JMSException
{
TopicConnectionFactory tcf = (TopicConnectionFactory)connectionFactory;
if(username == null)
return tcf.createTopicConnection();
return tcf.createTopicConnection(username, password);
}
protected SyncConnection createSyncConnection(ConnectionFactory factory,
Connection connection,
int numSessions,
String threadName,
String clientID,
String username,
String password)
throws JMSException
{
return new TopicSyncConnection((TopicConnectionFactory)factory,
(TopicConnection)connection, numSessions,
threadName, clientID, username, password);
}
protected AsyncConnection createAsyncConnection(ConnectionFactory factory,
Connection connection,
String threadName,
String clientID,
String username,
String password)
throws JMSException
{
return new TopicAsyncConnection((TopicConnectionFactory)factory,
(TopicConnection)connection, threadName,
clientID, username, password);
}
public JMSEndpoint createEndpoint(String destination)
{
return new TopicEndpoint(destination);
}
/**
* Create an endpoint for a queue destination.
*
* @param destination
* @return
* @throws JMSException
*/
public JMSEndpoint createEndpoint(Destination destination)
throws JMSException
{
if(!(destination instanceof Topic))
throw new IllegalArgumentException("The input be a topic for this connector");
return new TopicDestinationEndpoint((Topic)destination);
}
private TopicSession createTopicSession(TopicConnection connection, int ackMode)
throws JMSException
{
return connection.createTopicSession(false,
ackMode);
}
private Topic createTopic(TopicSession session, String subject)
throws Exception
{
return m_adapter.getTopic(session, subject);
}
private TopicSubscriber createSubscriber(TopicSession session,
TopicSubscription subscription)
throws Exception
{
if(subscription.isDurable())
return createDurableSubscriber(session,
(Topic)subscription.m_endpoint.getDestination(session),
subscription.m_subscriptionName,
subscription.m_messageSelector,
subscription.m_noLocal);
else
return createSubscriber(session,
(Topic)subscription.m_endpoint.getDestination(session),
subscription.m_messageSelector,
subscription.m_noLocal);
}
private TopicSubscriber createDurableSubscriber(TopicSession session,
Topic topic,
String subscriptionName,
String messageSelector,
boolean noLocal)
throws JMSException
{
return session.createDurableSubscriber(topic, subscriptionName,
messageSelector, noLocal);
}
private TopicSubscriber createSubscriber(TopicSession session,
Topic topic,
String messageSelector,
boolean noLocal)
throws JMSException
{
return session.createSubscriber(topic, messageSelector, noLocal);
}
private final class TopicAsyncConnection extends AsyncConnection
{
TopicAsyncConnection(TopicConnectionFactory connectionFactory,
TopicConnection 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
{
TopicSession session = createTopicSession((TopicConnection)connection,
subscription.m_ackMode);
TopicSubscriber subscriber = createSubscriber(session,
(TopicSubscription)subscription);
return new TopicListenerSession(session, subscriber,
(TopicSubscription)subscription);
}
private final class TopicListenerSession extends ListenerSession
{
TopicListenerSession(TopicSession session,
TopicSubscriber subscriber,
TopicSubscription subscription)
throws Exception
{
super(session, subscriber, subscription);
}
void cleanup()
{
try{m_consumer.close();}catch(Exception ignore){}
try
{
TopicSubscription sub = (TopicSubscription)m_subscription;
if(sub.isDurable() && sub.m_unsubscribe)
{
((TopicSession)m_session).unsubscribe(sub.m_subscriptionName);
}
}
catch(Exception ignore){}
try{m_session.close();}catch(Exception ignore){}
}
}
}
private final class TopicSyncConnection extends SyncConnection
{
TopicSyncConnection(TopicConnectionFactory connectionFactory,
TopicConnection 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
{
TopicSession session = createTopicSession((TopicConnection)connection,
JMSConstants.DEFAULT_ACKNOWLEDGE_MODE);
TopicPublisher publisher = session.createPublisher(null);
return new TopicSendSession(session, publisher);
}
private final class TopicSendSession extends SendSession
{
TopicSendSession(TopicSession session,
TopicPublisher publisher)
throws JMSException
{
super(session, publisher);
}
protected MessageConsumer createConsumer(Destination destination)
throws JMSException
{
return createSubscriber((TopicSession)m_session, (Topic)destination,
null, JMSConstants.DEFAULT_NO_LOCAL);
}
protected void deleteTemporaryDestination(Destination destination)
throws JMSException
{
((TemporaryTopic)destination).delete();
}
protected Destination createTemporaryDestination()
throws JMSException
{
return ((TopicSession)m_session).createTemporaryTopic();
}
protected void send(Destination destination, Message message,
int deliveryMode, int priority, long timeToLive)
throws JMSException
{
((TopicPublisher)m_producer).publish((Topic)destination, message,
deliveryMode, priority, timeToLive);
}
}
}
private class TopicEndpoint
extends JMSEndpoint
{
String m_topicName;
TopicEndpoint(String topicName)
{
super(TopicConnector.this);
m_topicName = topicName;
}
Destination getDestination(Session session)
throws Exception
{
return createTopic((TopicSession)session, m_topicName);
}
protected Subscription createSubscription(MessageListener listener,
HashMap properties)
{
return new TopicSubscription(listener, this, properties);
}
public String toString()
{
StringBuffer buffer = new StringBuffer("TopicEndpoint:");
buffer.append(m_topicName);
return buffer.toString();
}
public boolean equals(Object object)
{
if(!super.equals(object))
return false;
if(!(object instanceof TopicEndpoint))
return false;
return m_topicName.equals(((TopicEndpoint)object).m_topicName);
}
}
private final class TopicSubscription extends Subscription
{
String m_subscriptionName;
boolean m_unsubscribe;
boolean m_noLocal;
TopicSubscription(MessageListener listener,
JMSEndpoint endpoint,
HashMap properties)
{
super(listener, endpoint, properties);
m_subscriptionName = MapUtils.removeStringProperty(properties,
JMSConstants.SUBSCRIPTION_NAME,
null);
m_unsubscribe = MapUtils.removeBooleanProperty(properties,
JMSConstants.UNSUBSCRIBE,
JMSConstants.DEFAULT_UNSUBSCRIBE);
m_noLocal = MapUtils.removeBooleanProperty(properties,
JMSConstants.NO_LOCAL,
JMSConstants.DEFAULT_NO_LOCAL);
}
boolean isDurable()
{
return m_subscriptionName != null;
}
public boolean equals(Object obj)
{
if(!super.equals(obj))
return false;
if(!(obj instanceof TopicSubscription))
return false;
TopicSubscription other = (TopicSubscription)obj;
if(other.m_unsubscribe != m_unsubscribe || other.m_noLocal != m_noLocal)
return false;
if(isDurable())
{
return other.isDurable() && other.m_subscriptionName.equals(m_subscriptionName);
}
else if(other.isDurable())
return false;
else
return true;
}
public String toString()
{
StringBuffer buffer = new StringBuffer(super.toString());
buffer.append(":").append(m_noLocal).append(":").append(m_unsubscribe);
if(isDurable())
{
buffer.append(":");
buffer.append(m_subscriptionName);
}
return buffer.toString();
}
}
private final class TopicDestinationEndpoint
extends TopicEndpoint
{
Topic m_topic;
TopicDestinationEndpoint(Topic topic)
throws JMSException
{
super(topic.getTopicName());
m_topic = topic;
}
Destination getDestination(Session session)
{
return m_topic;
}
}
} | 6,904 |
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/JMSConnectorManager.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.AxisFault;
import org.apache.axis.components.jms.JMSVendorAdapter;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import java.util.HashMap;
import java.util.Iterator;
/**
* JMSConnectorManager manages a pool of connectors and works with the
* vendor adapters to support the reuse of JMS connections.
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSConnectorManager
{
protected static Log log =
LogFactory.getLog(JMSConnectorManager.class.getName());
private static JMSConnectorManager s_instance = new JMSConnectorManager();
private static HashMap vendorConnectorPools = new HashMap();
private int DEFAULT_WAIT_FOR_SHUTDOWN = 90000; // 1.5 minutes
private JMSConnectorManager()
{
}
public static JMSConnectorManager getInstance()
{
return s_instance;
}
/**
* Returns the pool of JMSConnectors for a particular vendor
*/
public ShareableObjectPool getVendorPool(String vendorId)
{
return (ShareableObjectPool)vendorConnectorPools.get(vendorId);
}
/**
* Retrieves a JMSConnector that satisfies the provided connector criteria
*/
public JMSConnector getConnector(HashMap connectorProperties,
HashMap connectionFactoryProperties,
String username,
String password,
JMSVendorAdapter vendorAdapter)
throws AxisFault
{
JMSConnector connector = null;
try
{
// check for a vendor-specific pool, and create if necessary
ShareableObjectPool vendorConnectors = getVendorPool(vendorAdapter.getVendorId());
if (vendorConnectors == null)
{
synchronized (vendorConnectorPools)
{
vendorConnectors = getVendorPool(vendorAdapter.getVendorId());
if (vendorConnectors == null)
{
vendorConnectors = new ShareableObjectPool();
vendorConnectorPools.put(vendorAdapter.getVendorId(), vendorConnectors);
}
}
}
// look for a matching JMSConnector among existing connectors
synchronized (vendorConnectors)
{
try
{
connector = JMSConnectorFactory.matchConnector(vendorConnectors.getElements(),
connectorProperties,
connectionFactoryProperties,
username,
password,
vendorAdapter);
}
catch (Exception e) {} // ignore. a new connector will be created if no match is found
if (connector == null)
{
connector = JMSConnectorFactory.createClientConnector(connectorProperties,
connectionFactoryProperties,
username,
password,
vendorAdapter);
connector.start();
}
}
}
catch (Exception e)
{
log.error(Messages.getMessage("cannotConnectError"), e);
if(e instanceof AxisFault)
throw (AxisFault)e;
throw new AxisFault("cannotConnect", e);
}
return connector;
}
/**
* Closes JMSConnectors in all pools
*/
void closeAllConnectors()
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSConnectorManager::closeAllConnectors");
}
synchronized (vendorConnectorPools)
{
Iterator iter = vendorConnectorPools.values().iterator();
while (iter.hasNext())
{
// close all connectors in the vendor pool
ShareableObjectPool pool = (ShareableObjectPool)iter.next();
synchronized (pool)
{
java.util.Iterator connectors = pool.getElements().iterator();
while (connectors.hasNext())
{
JMSConnector conn = (JMSConnector)connectors.next();
try
{
// shutdown automatically decrements the ref count of a connector before closing it
// call reserve() to simulate the checkout
reserve(conn);
closeConnector(conn);
}
catch (Exception e) {} // ignore. the connector is already being deactivated
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("Exit: JMSConnectorManager::closeAllConnectors");
}
}
/**
* Closes JMS connectors that match the specified endpoint address
*/
void closeMatchingJMSConnectors(HashMap connectorProps, HashMap cfProps,
String username, String password,
JMSVendorAdapter vendorAdapter)
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSConnectorManager::closeMatchingJMSConnectors");
}
try
{
String vendorId = vendorAdapter.getVendorId();
// get the vendor-specific pool of connectors
ShareableObjectPool vendorConnectors = null;
synchronized (vendorConnectorPools)
{
vendorConnectors = getVendorPool(vendorId);
}
// it's possible that there is no pool for that vendor
if (vendorConnectors == null)
return;
synchronized (vendorConnectors)
{
// close any matched connectors
JMSConnector connector = null;
while ((vendorConnectors.size() > 0) &&
(connector = JMSConnectorFactory.matchConnector(vendorConnectors.getElements(),
connectorProps,
cfProps,
username,
password,
vendorAdapter)) != null)
{
closeConnector(connector);
}
}
}
catch (Exception e)
{
log.warn(Messages.getMessage("failedJMSConnectorShutdown"), e);
}
if (log.isDebugEnabled()) {
log.debug("Exit: JMSConnectorManager::closeMatchingJMSConnectors");
}
}
private void closeConnector(JMSConnector conn)
{
conn.stop();
conn.shutdown();
}
/**
* Adds a JMSConnector to the appropriate vendor pool
*/
public void addConnectorToPool(JMSConnector conn)
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSConnectorManager::addConnectorToPool");
}
ShareableObjectPool vendorConnectors = null;
synchronized (vendorConnectorPools)
{
String vendorId = conn.getVendorAdapter().getVendorId();
vendorConnectors = getVendorPool(vendorId);
// it's possible the pool does not yet exist (if, for example, the connector
// is created before invoking the call/JMSTransport, as is the case with
// SimpleJMSListener)
if (vendorConnectors == null)
{
vendorConnectors = new ShareableObjectPool();
vendorConnectorPools.put(vendorId, vendorConnectors);
}
}
synchronized (vendorConnectors)
{
vendorConnectors.addObject(conn);
}
if (log.isDebugEnabled()) {
log.debug("Exit: JMSConnectorManager::addConnectorToPool");
}
}
/**
* Removes a JMSConnector from the appropriate vendor pool
*/
public void removeConnectorFromPool(JMSConnector conn)
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSConnectorManager::removeConnectorFromPool");
}
ShareableObjectPool vendorConnectors = null;
synchronized (vendorConnectorPools)
{
vendorConnectors = getVendorPool(conn.getVendorAdapter().getVendorId());
}
if (vendorConnectors == null)
return;
synchronized (vendorConnectors)
{
// first release, to decrement the ref count (it is automatically incremented when
// the connector is matched)
vendorConnectors.release(conn);
vendorConnectors.removeObject(conn);
}
if (log.isDebugEnabled()) {
log.debug("Exit: JMSConnectorManager::removeConnectorFromPool");
}
}
/**
* Performs a non-exclusive checkout of the JMSConnector
*/
public void reserve(JMSConnector connector) throws Exception
{
ShareableObjectPool pool = null;
synchronized (vendorConnectorPools)
{
pool = getVendorPool(connector.getVendorAdapter().getVendorId());
}
if (pool != null)
pool.reserve(connector);
}
/**
* Performs a non-exclusive checkin of the JMSConnector
*/
public void release(JMSConnector connector)
{
ShareableObjectPool pool = null;
synchronized (vendorConnectorPools)
{
pool = getVendorPool(connector.getVendorAdapter().getVendorId());
}
if (pool != null)
pool.release(connector);
}
/**
* A simple non-blocking pool impl for objects that can be shared.
* Only a ref count is necessary to prevent collisions at shutdown.
* Todo: max size, cleanup stale connections
*/
public class ShareableObjectPool
{
// maps object to ref count wrapper
private java.util.HashMap m_elements;
// holds objects which should no longer be leased (pending removal)
private java.util.HashMap m_expiring;
private int m_numElements = 0;
public ShareableObjectPool()
{
m_elements = new java.util.HashMap();
m_expiring = new java.util.HashMap();
}
/**
* Adds the object to the pool, if not already added
*/
public void addObject(Object obj)
{
ReferenceCountedObject ref = new ReferenceCountedObject(obj);
synchronized (m_elements)
{
if (!m_elements.containsKey(obj) && !m_expiring.containsKey(obj))
m_elements.put(obj, ref);
}
}
/**
* Removes the object from the pool. If the object is reserved,
* waits the specified time before forcibly removing
* Todo: check expirations with the next request instead of holding up the current request
*/
public void removeObject(Object obj, long waitTime)
{
ReferenceCountedObject ref = null;
synchronized (m_elements)
{
ref = (ReferenceCountedObject)m_elements.get(obj);
if (ref == null)
return;
m_elements.remove(obj);
if (ref.count() == 0)
return;
else
// mark the object for expiration
m_expiring.put(obj, ref);
}
// connector is now marked for expiration. wait for the ref count to drop to zero
long expiration = System.currentTimeMillis() + waitTime;
while (ref.count() > 0)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e) {} // ignore
if (System.currentTimeMillis() > expiration)
break;
}
// also clear from the expiring list
m_expiring.remove(obj);
}
public void removeObject(Object obj)
{
removeObject(obj, DEFAULT_WAIT_FOR_SHUTDOWN);
}
/**
* Marks the connector as in use by incrementing the connector's reference count
*/
public void reserve(Object obj) throws Exception
{
synchronized (m_elements)
{
if (m_expiring.containsKey(obj))
throw new Exception("resourceUnavailable");
ReferenceCountedObject ref = (ReferenceCountedObject)m_elements.get(obj);
ref.increment();
}
}
/**
* Decrements the connector's reference count
*/
public void release(Object obj)
{
synchronized (m_elements)
{
ReferenceCountedObject ref = (ReferenceCountedObject)m_elements.get(obj);
ref.decrement();
}
}
public synchronized java.util.Set getElements()
{
return m_elements.keySet();
}
public synchronized int size()
{
return m_elements.size();
}
/**
* Wrapper to track the use count of an object
*/
public class ReferenceCountedObject
{
private Object m_object;
private int m_refCount;
public ReferenceCountedObject(Object obj)
{
m_object = obj;
m_refCount = 0;
}
public synchronized void increment()
{
m_refCount++;
}
public synchronized void decrement()
{
if (m_refCount > 0)
m_refCount--;
}
public synchronized int count()
{
return m_refCount;
}
}
}
} | 6,905 |
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/JMSURLHelper.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 java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* JMSURLHelper provides access to properties in the URL.
* The URL must be of the form: "jms:/<destination>?[<property>=<key>&]*"
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSURLHelper
{
private URL url;
// the only property not in the query string
private String destination;
// vendor-specific properties
private HashMap properties;
// required properties
private Vector requiredProperties;
//application-specific JMS message properties
private Vector appProperties;
public JMSURLHelper(java.net.URL url) throws java.net.MalformedURLException {
this(url, null);
}
public JMSURLHelper(java.net.URL url, String[] requiredProperties) throws java.net.MalformedURLException {
this.url = url;
properties = new HashMap();
appProperties = new Vector();
// the path should be something like '/SampleQ1'
// clip the leading '/' if there is one
destination = url.getPath();
if (destination.startsWith("/"))
destination = destination.substring(1);
if ((destination == null) || (destination.trim().length() < 1))
throw new java.net.MalformedURLException("Missing destination in URL");
// parse the query string and populate the properties table
String query = url.getQuery();
StringTokenizer st = new StringTokenizer(query, "&;");
while (st.hasMoreTokens()) {
String keyValue = st.nextToken();
int eqIndex = keyValue.indexOf("=");
if (eqIndex > 0)
{
String key = keyValue.substring(0, eqIndex);
String value = keyValue.substring(eqIndex+1);
if (key.startsWith(JMSConstants._MSG_PROP_PREFIX)) {
key = key.substring(
JMSConstants._MSG_PROP_PREFIX.length());
addApplicationProperty(key);
}
properties.put(key, value);
}
}
// set required properties
addRequiredProperties(requiredProperties);
validateURL();
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getVendor() {
return getPropertyValue(JMSConstants._VENDOR);
}
public String getDomain() {
return getPropertyValue(JMSConstants._DOMAIN);
}
public HashMap getProperties() {
return properties;
}
public String getPropertyValue(String property) {
return (String)properties.get(property);
}
public void addRequiredProperties(String[] properties)
{
if (properties == null)
return;
for (int i = 0; i < properties.length; i++)
{
addRequiredProperty(properties[i]);
}
}
public void addRequiredProperty(String property) {
if (property == null)
return;
if (requiredProperties == null)
requiredProperties = new Vector();
requiredProperties.addElement(property);
}
public Vector getRequiredProperties() {
return requiredProperties;
}
/** Adds the name of a property from the url properties that should
* be added to the JMS message.
*/
public void addApplicationProperty(String property) {
if (property == null)
return;
if (appProperties == null)
appProperties = new Vector();
appProperties.addElement(property);
}
/** Adds the name and value od the application property to the
* JMS URL.
*/
public void addApplicationProperty(String property, String value) {
if (property == null)
return;
if (appProperties == null)
appProperties = new Vector();
properties.put(property, value);
appProperties.addElement(property);
}
/** Returns a collection of properties that are defined within the
* JMS URL to be added directly to the JMS messages.
@return collection or null depending on presence of elements
*/
public Vector getApplicationProperties() {
return appProperties;
}
/**
Returns a URL formatted String. The properties of the URL may not
end up in the same order as the JMS URL that was originally used to
create this object.
*/
public String getURLString() {
StringBuffer text = new StringBuffer("jms:/");
text.append(getDestination());
text.append("?");
Map props = (Map)properties.clone();
boolean firstEntry = true;
for(Iterator itr=properties.keySet().iterator(); itr.hasNext();) {
String key = (String)itr.next();
if (!firstEntry) {
text.append("&");
}
if (appProperties.contains(key)) {
text.append(JMSConstants._MSG_PROP_PREFIX);
}
text.append(key);
text.append("=");
text.append(props.get(key));
firstEntry = false;
}
return text.toString();
}
/** Returns a formatted URL String with the assigned properties */
public String toString() {
return getURLString();
}
private void validateURL()
throws java.net.MalformedURLException {
Vector required = getRequiredProperties();
if (required == null)
return;
for (int i = 0; i < required.size(); i++)
{
String key = (String)required.elementAt(i);
if (properties.get(key) == null)
throw new java.net.MalformedURLException();
}
}
} | 6,906 |
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/JMSConnector.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.BytesMessage;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
// No vendor dependent exception classes
//import progress.message.client.EUserAlreadyConnected;
//import progress.message.jclient.ErrorCodes;
/**
* JMSConnector is an abstract class that encapsulates the work of connecting
* to JMS destinations. Its subclasses are TopicConnector and QueueConnector
* which further specialize connections to the pub-sub and the ptp domains.
* It also implements the capability to retry connections in the event of
* failures.
*
* @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 abstract class JMSConnector
{
protected int m_numRetries;
protected long m_connectRetryInterval;
protected long m_interactRetryInterval;
protected long m_timeoutTime;
protected long m_poolTimeout;
protected AsyncConnection m_receiveConnection;
protected SyncConnection m_sendConnection;
protected int m_numSessions;
protected boolean m_allowReceive;
protected JMSVendorAdapter m_adapter;
protected JMSURLHelper m_jmsurl;
public JMSConnector(ConnectionFactory connectionFactory,
int numRetries,
int numSessions,
long connectRetryInterval,
long interactRetryInterval,
long timeoutTime,
boolean allowReceive,
String clientID,
String username,
String password,
JMSVendorAdapter adapter,
JMSURLHelper jmsurl)
throws JMSException
{
m_numRetries = numRetries;
m_connectRetryInterval = connectRetryInterval;
m_interactRetryInterval = interactRetryInterval;
m_timeoutTime = timeoutTime;
m_poolTimeout = timeoutTime/(long)numRetries;
m_numSessions = numSessions;
m_allowReceive = allowReceive;
m_adapter = adapter;
m_jmsurl = jmsurl;
// try to connect initially so we can fail fast
// in the case of irrecoverable errors.
// If we fail in a recoverable fashion we will retry
javax.jms.Connection sendConnection = createConnectionWithRetry(
connectionFactory,
username,
password);
m_sendConnection = createSyncConnection(connectionFactory, sendConnection,
m_numSessions, "SendThread",
clientID,
username,
password);
m_sendConnection.start();
if(m_allowReceive)
{
javax.jms.Connection receiveConnection = createConnectionWithRetry(
connectionFactory,
username,
password);
m_receiveConnection = createAsyncConnection(connectionFactory,
receiveConnection,
"ReceiveThread",
clientID,
username,
password);
m_receiveConnection.start();
}
}
public int getNumRetries()
{
return m_numRetries;
}
public int numSessions()
{
return m_numSessions;
}
public ConnectionFactory getConnectionFactory()
{
// there is always a send connection
return getSendConnection().getConnectionFactory();
}
public String getClientID()
{
return getSendConnection().getClientID();
}
public String getUsername()
{
return getSendConnection().getUsername();
}
public String getPassword()
{
return getSendConnection().getPassword();
}
public JMSVendorAdapter getVendorAdapter()
{
return m_adapter;
}
public JMSURLHelper getJMSURL()
{
return m_jmsurl;
}
protected javax.jms.Connection createConnectionWithRetry(
ConnectionFactory connectionFactory,
String username,
String password)
throws JMSException
{
javax.jms.Connection connection = null;
for(int numTries = 1; connection == null; numTries++)
{
try
{
connection = internalConnect(connectionFactory, username, password);
}
catch(JMSException jmse)
{
if(!m_adapter.isRecoverable(jmse, JMSVendorAdapter.CONNECT_ACTION) || numTries == m_numRetries)
throw jmse;
else
try{Thread.sleep(m_connectRetryInterval);}catch(InterruptedException ie){};
}
}
return connection;
}
public void stop()
{
JMSConnectorManager.getInstance().removeConnectorFromPool(this);
m_sendConnection.stopConnection();
if(m_allowReceive)
m_receiveConnection.stopConnection();
}
public void start()
{
m_sendConnection.startConnection();
if(m_allowReceive)
m_receiveConnection.startConnection();
JMSConnectorManager.getInstance().addConnectorToPool(this);
}
public void shutdown()
{
m_sendConnection.shutdown();
if(m_allowReceive)
m_receiveConnection.shutdown();
}
public abstract JMSEndpoint createEndpoint(String destinationName)
throws JMSException;
public abstract JMSEndpoint createEndpoint(Destination destination)
throws JMSException;
protected abstract javax.jms.Connection internalConnect(
ConnectionFactory connectionFactory,
String username,
String password)
throws JMSException;
private abstract class Connection extends Thread implements ExceptionListener
{
private ConnectionFactory m_connectionFactory;
protected javax.jms.Connection m_connection;
protected boolean m_isActive;
private boolean m_needsToConnect;
private boolean m_startConnection;
private String m_clientID;
private String m_username;
private String m_password;
private Object m_jmsLock;
private Object m_lifecycleLock;
protected Connection(ConnectionFactory connectionFactory,
javax.jms.Connection connection,
String threadName,
String clientID,
String username,
String password)
throws JMSException
{
super(threadName);
m_connectionFactory = connectionFactory;
m_clientID = clientID;
m_username = username;
m_password = password;
m_jmsLock = new Object();
m_lifecycleLock = new Object();
if (connection != null)
{
m_needsToConnect = false;
m_connection = connection;
m_connection.setExceptionListener(this);
if(m_clientID != null)
m_connection.setClientID(m_clientID);
}
else
{
m_needsToConnect = true;
}
m_isActive = true;
}
public ConnectionFactory getConnectionFactory()
{
return m_connectionFactory;
}
public String getClientID()
{
return m_clientID;
}
public String getUsername()
{
return m_username;
}
public String getPassword()
{
return m_password;
}
/**
* @todo handle non-recoverable errors
*/
public void run()
{
// loop until a connection is made and when a connection is made (re)establish
// any subscriptions
while (m_isActive)
{
if (m_needsToConnect)
{
m_connection = null;
try
{
m_connection = internalConnect(m_connectionFactory,
m_username, m_password);
m_connection.setExceptionListener(this);
if(m_clientID != null)
m_connection.setClientID(m_clientID);
}
catch(JMSException e)
{
// simply backoff for a while and then retry
try { Thread.sleep(m_connectRetryInterval); } catch(InterruptedException ie) { }
continue;
}
}
else
m_needsToConnect = true; // When we'll get to the "if (needsToConnect)" statement the next time it will be because
// we lost the connection
// we now have a valid connection so establish some context
try
{
internalOnConnect();
}
catch(Exception e)
{
// insert code to handle non recoverable errors
// simply retry
continue;
}
synchronized(m_jmsLock)
{
try { m_jmsLock.wait(); } catch(InterruptedException ie) { } // until notified due to some change in status
}
}
// no longer staying connected, so see what we can cleanup
internalOnShutdown();
}
void startConnection()
{
synchronized(m_lifecycleLock)
{
if(m_startConnection)
return;
m_startConnection = true;
try {m_connection.start();}catch(Throwable e) { } // ignore
}
}
void stopConnection()
{
synchronized(m_lifecycleLock)
{
if(!m_startConnection)
return;
m_startConnection = false;
try {m_connection.stop();}catch(Throwable e) { } // ignore
}
}
void shutdown()
{
m_isActive = false;
synchronized(m_jmsLock)
{
m_jmsLock.notifyAll();
}
}
public void onException(JMSException exception)
{
if(m_adapter.isRecoverable(exception,
JMSVendorAdapter.ON_EXCEPTION_ACTION))
return;
onException();
synchronized(m_jmsLock)
{
m_jmsLock.notifyAll();
}
}
private final void internalOnConnect()
throws Exception
{
onConnect();
synchronized(m_lifecycleLock)
{
if(m_startConnection)
{
try {m_connection.start();}catch(Throwable e) { } // ignore
}
}
}
private final void internalOnShutdown()
{
stopConnection();
onShutdown();
try { m_connection.close(); } catch(Throwable e) { } // ignore
}
protected abstract void onConnect()throws Exception;
protected abstract void onShutdown();
protected abstract void onException();
}
protected abstract SyncConnection createSyncConnection(ConnectionFactory factory,
javax.jms.Connection connection,
int numSessions,
String threadName,
String clientID,
String username,
String password)
throws JMSException;
SyncConnection getSendConnection()
{
return m_sendConnection;
}
protected abstract class SyncConnection extends Connection
{
LinkedList m_senders;
int m_numSessions;
Object m_senderLock;
SyncConnection(ConnectionFactory connectionFactory,
javax.jms.Connection connection,
int numSessions,
String threadName,
String clientID,
String username,
String password)
throws JMSException
{
super(connectionFactory, connection, threadName,
clientID, username, password);
m_senders = new LinkedList();
m_numSessions = numSessions;
m_senderLock = new Object();
}
protected abstract SendSession createSendSession(javax.jms.Connection connection)
throws JMSException;
protected void onConnect()
throws JMSException
{
synchronized(m_senderLock)
{
for(int i = 0; i < m_numSessions; i++)
{
m_senders.add(createSendSession(m_connection));
}
m_senderLock.notifyAll();
}
}
byte[] call(JMSEndpoint endpoint, byte[] message, long timeout, HashMap properties)
throws Exception
{
long timeoutTime = System.currentTimeMillis() + timeout;
while(true)
{
if(System.currentTimeMillis() > timeoutTime)
{
throw new InvokeTimeoutException("Unable to complete call in time allotted");
}
SendSession sendSession = null;
try
{
sendSession = getSessionFromPool(m_poolTimeout);
byte[] response = sendSession.call(endpoint,
message,
timeoutTime - System.currentTimeMillis(),
properties);
returnSessionToPool(sendSession);
if(response == null)
{
throw new InvokeTimeoutException("Unable to complete call in time allotted");
}
return response;
}
catch(JMSException jmse)
{
if(!m_adapter.isRecoverable(jmse, JMSVendorAdapter.SEND_ACTION))
{
//this we cannot recover from
//but it does not invalidate the session
returnSessionToPool(sendSession);
throw jmse;
}
//for now we will assume this is a reconnect related issue
//and let the sender be collected
//give the reconnect thread a chance to fill the pool
Thread.yield();
continue;
}
catch(NullPointerException npe)
{
Thread.yield();
continue;
}
}
}
/** @todo add in handling for security exceptions
* @todo add support for timeouts */
void send(JMSEndpoint endpoint, byte[] message, HashMap properties)
throws Exception
{
long timeoutTime = System.currentTimeMillis() + m_timeoutTime;
while(true)
{
if(System.currentTimeMillis() > timeoutTime)
{
throw new InvokeTimeoutException("Cannot complete send in time allotted");
}
SendSession sendSession = null;
try
{
sendSession = getSessionFromPool(m_poolTimeout);
sendSession.send(endpoint, message, properties);
returnSessionToPool(sendSession);
}
catch(JMSException jmse)
{
if(!m_adapter.isRecoverable(jmse, JMSVendorAdapter.SEND_ACTION))
{
//this we cannot recover from
//but it does not invalidate the session
returnSessionToPool(sendSession);
throw jmse;
}
//for now we will assume this is a reconnect related issue
//and let the sender be collected
//give the reconnect thread a chance to fill the pool
Thread.yield();
continue;
}
catch(NullPointerException npe)
{
//give the reconnect thread a chance to fill the pool
Thread.yield();
continue;
}
break;
}
}
protected void onException()
{
synchronized(m_senderLock)
{
m_senders.clear();
}
}
protected void onShutdown()
{
synchronized(m_senderLock)
{
Iterator senders = m_senders.iterator();
while(senders.hasNext())
{
SendSession session = (SendSession)senders.next();
session.cleanup();
}
m_senders.clear();
}
}
private SendSession getSessionFromPool(long timeout)
{
synchronized(m_senderLock)
{
while(m_senders.size() == 0)
{
try
{
m_senderLock.wait(timeout);
if(m_senders.size() == 0)
{
return null;
}
}
catch(InterruptedException ignore)
{
return null;
}
}
return (SendSession)m_senders.removeFirst();
}
}
private void returnSessionToPool(SendSession sendSession)
{
synchronized(m_senderLock)
{
m_senders.addLast(sendSession);
m_senderLock.notifyAll();
}
}
protected abstract class SendSession extends ConnectorSession
{
MessageProducer m_producer;
SendSession(Session session,
MessageProducer producer)
throws JMSException
{
super(session);
m_producer = producer;
}
protected abstract Destination createTemporaryDestination()
throws JMSException;
protected abstract void deleteTemporaryDestination(Destination destination)
throws JMSException;
protected abstract MessageConsumer createConsumer(Destination destination)
throws JMSException;
protected abstract void send(Destination destination,
Message message,
int deliveryMode,
int priority,
long timeToLive)
throws JMSException;
void send(JMSEndpoint endpoint, byte[] message, HashMap properties)
throws Exception
{
BytesMessage jmsMessage = m_session.createBytesMessage();
jmsMessage.writeBytes(message);
int deliveryMode = extractDeliveryMode(properties);
int priority = extractPriority(properties);
long timeToLive = extractTimeToLive(properties);
if(properties != null && !properties.isEmpty())
setProperties(properties, jmsMessage);
send(endpoint.getDestination(m_session), jmsMessage, deliveryMode,
priority, timeToLive);
}
void cleanup()
{
try{m_producer.close();}catch(Throwable t){}
try{m_session.close();}catch(Throwable t){}
}
byte[] call(JMSEndpoint endpoint, byte[] message, long timeout,
HashMap properties)
throws Exception
{
Destination reply = createTemporaryDestination();
MessageConsumer subscriber = createConsumer(reply);
BytesMessage jmsMessage = m_session.createBytesMessage();
jmsMessage.writeBytes(message);
jmsMessage.setJMSReplyTo(reply);
int deliveryMode = extractDeliveryMode(properties);
int priority = extractPriority(properties);
long timeToLive = extractTimeToLive(properties);
if(properties != null && !properties.isEmpty())
setProperties(properties, jmsMessage);
send(endpoint.getDestination(m_session), jmsMessage, deliveryMode,
priority, timeToLive);
BytesMessage response = null;
try {
response = (BytesMessage)subscriber.receive(timeout);
} catch (ClassCastException cce) {
throw new InvokeException
("Error: unexpected message type received - expected BytesMessage");
}
byte[] respBytes = null;
if(response != null)
{
byte[] buffer = new byte[8 * 1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
for(int bytesRead = response.readBytes(buffer);
bytesRead != -1; bytesRead = response.readBytes(buffer))
{
out.write(buffer, 0, bytesRead);
}
respBytes = out.toByteArray();
}
subscriber.close();
deleteTemporaryDestination(reply);
return respBytes;
}
private int extractPriority(HashMap properties)
{
return MapUtils.removeIntProperty(properties, JMSConstants.PRIORITY,
JMSConstants.DEFAULT_PRIORITY);
}
private int extractDeliveryMode(HashMap properties)
{
return MapUtils.removeIntProperty(properties, JMSConstants.DELIVERY_MODE,
JMSConstants.DEFAULT_DELIVERY_MODE);
}
private long extractTimeToLive(HashMap properties)
{
return MapUtils.removeLongProperty(properties, JMSConstants.TIME_TO_LIVE,
JMSConstants.DEFAULT_TIME_TO_LIVE);
}
private void setProperties(HashMap properties, Message message)
throws JMSException
{
Iterator propertyIter = properties.entrySet().iterator();
while(propertyIter.hasNext())
{
Map.Entry property = (Map.Entry)propertyIter.next();
setProperty((String)property.getKey(), property.getValue(),
message);
}
}
private void setProperty(String property, Object value, Message message)
throws JMSException
{
if(property == null)
return;
if(property.equals(JMSConstants.JMS_CORRELATION_ID))
message.setJMSCorrelationID((String)value);
else if(property.equals(JMSConstants.JMS_CORRELATION_ID_AS_BYTES))
message.setJMSCorrelationIDAsBytes((byte[])value);
else if(property.equals(JMSConstants.JMS_TYPE))
message.setJMSType((String)value);
else
message.setObjectProperty(property, value);
}
}
}
AsyncConnection getReceiveConnection()
{
return m_receiveConnection;
}
protected abstract AsyncConnection createAsyncConnection(ConnectionFactory factory,
javax.jms.Connection connection,
String threadName,
String clientID,
String username,
String password)
throws JMSException;
protected abstract class AsyncConnection extends Connection
{
HashMap m_subscriptions;
Object m_subscriptionLock;
protected AsyncConnection(ConnectionFactory connectionFactory,
javax.jms.Connection connection,
String threadName,
String clientID,
String username,
String password)
throws JMSException
{
super(connectionFactory, connection, threadName,
clientID, username, password);
m_subscriptions = new HashMap();
m_subscriptionLock = new Object();
}
protected abstract ListenerSession createListenerSession(
javax.jms.Connection connection,
Subscription subscription)
throws Exception;
protected void onShutdown()
{
synchronized(m_subscriptionLock)
{
Iterator subscriptions = m_subscriptions.keySet().iterator();
while(subscriptions.hasNext())
{
Subscription subscription = (Subscription)subscriptions.next();
ListenerSession session = (ListenerSession)
m_subscriptions.get(subscription);
if(session != null)
{
session.cleanup();
}
}
m_subscriptions.clear();
}
}
/**
* @todo add in security exception propagation
* @param subscription
*/
void subscribe(Subscription subscription)
throws Exception
{
long timeoutTime = System.currentTimeMillis() + m_timeoutTime;
synchronized(m_subscriptionLock)
{
if(m_subscriptions.containsKey(subscription))
return;
while(true)
{
if(System.currentTimeMillis() > timeoutTime)
{
throw new InvokeTimeoutException("Cannot subscribe listener");
}
try
{
ListenerSession session = createListenerSession(m_connection,
subscription);
m_subscriptions.put(subscription, session);
break;
}
catch(JMSException jmse)
{
if(!m_adapter.isRecoverable(jmse, JMSVendorAdapter.SUBSCRIBE_ACTION))
{
throw jmse;
}
try{m_subscriptionLock.wait(m_interactRetryInterval);}
catch(InterruptedException ignore){}
//give reconnect a chance
Thread.yield();
continue;
}
catch(NullPointerException jmse)
{
//we ARE reconnecting
try{m_subscriptionLock.wait(m_interactRetryInterval);}
catch(InterruptedException ignore){}
//give reconnect a chance
Thread.yield();
continue;
}
}
}
}
void unsubscribe(Subscription subscription)
{
long timeoutTime = System.currentTimeMillis() + m_timeoutTime;
synchronized(m_subscriptionLock)
{
if(!m_subscriptions.containsKey(subscription))
return;
while(true)
{
if(System.currentTimeMillis() > timeoutTime)
{
throw new InvokeTimeoutException("Cannot unsubscribe listener");
}
//give reconnect a chance
Thread.yield();
try
{
ListenerSession session = (ListenerSession)
m_subscriptions.get(subscription);
session.cleanup();
m_subscriptions.remove(subscription);
break;
}
catch(NullPointerException jmse)
{
//we are reconnecting
try{m_subscriptionLock.wait(m_interactRetryInterval);}
catch(InterruptedException ignore){}
continue;
}
}
}
}
protected void onConnect()
throws Exception
{
synchronized(m_subscriptionLock)
{
Iterator subscriptions = m_subscriptions.keySet().iterator();
while(subscriptions.hasNext())
{
Subscription subscription = (Subscription)subscriptions.next();
if(m_subscriptions.get(subscription) == null)
{
m_subscriptions.put(subscription,
createListenerSession(m_connection, subscription));
}
}
m_subscriptionLock.notifyAll();
}
}
protected void onException()
{
synchronized(m_subscriptionLock)
{
Iterator subscriptions = m_subscriptions.keySet().iterator();
while(subscriptions.hasNext())
{
Subscription subscription = (Subscription)subscriptions.next();
m_subscriptions.put(subscription, null);
}
}
}
protected class ListenerSession extends ConnectorSession
{
protected MessageConsumer m_consumer;
protected Subscription m_subscription;
ListenerSession(Session session,
MessageConsumer consumer,
Subscription subscription)
throws Exception
{
super(session);
m_subscription = subscription;
m_consumer = consumer;
Destination destination = subscription.m_endpoint.getDestination(m_session);
m_consumer.setMessageListener(subscription.m_listener);
}
void cleanup()
{
try{m_consumer.close();}catch(Exception ignore){}
try{m_session.close();}catch(Exception ignore){}
}
}
}
private abstract class ConnectorSession
{
Session m_session;
ConnectorSession(Session session)
throws JMSException
{
m_session = session;
}
}
} | 6,907 |
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/JMSURLConnection.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 java.net.URL;
/**
* URLConnection for the "jms" protocol
*
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSURLConnection extends java.net.URLConnection
{
public JMSURLConnection(URL url)
{
super(url);
}
public void connect()
{
}
} | 6,908 |
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/SimpleJMSListener.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 org.apache.axis.components.jms.JMSVendorAdapterFactory;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.Options;
import org.apache.commons.logging.Log;
import javax.jms.BytesMessage;
import javax.jms.MessageListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
/**
* SimpleJMSListener implements the javax.jms.MessageListener interface. Its
* basic purpose is listen asynchronously for messages and to pass them off
* to SimpleJMSWorker for processing.
*
* Note: This is a simple JMS listener that does not pool worker threads and
* is not otherwise tuned for performance. As such, its intended use is not
* for production code, but for demos, debugging, and performance profiling.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class SimpleJMSListener implements MessageListener
{
protected static Log log =
LogFactory.getLog(SimpleJMSListener.class.getName());
// Do we use (multiple) threads to process incoming messages?
private static boolean doThreads;
private JMSConnector connector;
private JMSEndpoint endpoint;
private AxisServer server;
private HashMap connectorProps;
public SimpleJMSListener(HashMap connectorMap, HashMap cfMap,
String destination, String username,
String password, boolean doThreads)
throws Exception
{
SimpleJMSListener.doThreads = doThreads;
try {
// create a JMS connector using the default vendor adapter
JMSVendorAdapter adapter = JMSVendorAdapterFactory.getJMSVendorAdapter();
connector = JMSConnectorFactory.createServerConnector(connectorMap,
cfMap,
username,
password,
adapter);
connectorProps = connectorMap;
} catch (Exception e) {
log.error(Messages.getMessage("exception00"), e);
throw e;
}
// create the appropriate endpoint for the indicated destination
endpoint = connector.createEndpoint(destination);
}
// Axis server (shared between instances)
private static AxisServer myAxisServer = new AxisServer();
protected static AxisServer getAxisServer()
{
return myAxisServer;
}
protected JMSConnector getConnector()
{
return connector;
}
/**
* This method is called asynchronously whenever a message arrives.
* @param message
*/
public void onMessage(javax.jms.Message message)
{
try
{
// pass off the message to a worker as a BytesMessage
SimpleJMSWorker worker = new SimpleJMSWorker(this, (BytesMessage)message);
// do we allow multi-threaded workers?
if (doThreads) {
Thread t = new Thread(worker);
t.start();
} else {
worker.run();
}
}
catch(ClassCastException cce)
{
log.error(Messages.getMessage("exception00"), cce);
cce.printStackTrace();
return;
}
}
public void start()
throws Exception
{
endpoint.registerListener(this, connectorProps);
connector.start();
}
public void shutdown()
throws Exception
{
endpoint.unregisterListener(this);
connector.stop();
connector.shutdown();
}
public static final HashMap createConnectorMap(Options options)
{
HashMap connectorMap = new HashMap();
if (options.isFlagSet('t') > 0)
{
//queue is default so only setup map if topic domain is required
connectorMap.put(JMSConstants.DOMAIN, JMSConstants.DOMAIN_TOPIC);
}
return connectorMap;
}
public static final HashMap createCFMap(Options options)
throws IOException
{
String cfFile = options.isValueSet('c');
if(cfFile == null)
return null;
Properties cfProps = new Properties();
cfProps.load(new BufferedInputStream(new FileInputStream(cfFile)));
HashMap cfMap = new HashMap(cfProps);
return cfMap;
}
public static void main(String[] args) throws Exception
{
Options options = new Options(args);
// first check if we should print usage
if ((options.isFlagSet('?') > 0) || (options.isFlagSet('h') > 0))
printUsage();
SimpleJMSListener listener = new SimpleJMSListener(createConnectorMap(options),
createCFMap(options),
options.isValueSet('d'),
options.getUser(),
options.getPassword(),
options.isFlagSet('s') > 0);
listener.start();
}
public static void printUsage()
{
System.out.println("Usage: SimpleJMSListener [options]");
System.out.println(" Opts: -? this message");
System.out.println();
System.out.println(" -c connection factory properties filename");
System.out.println(" -d destination");
System.out.println(" -t topic [absence of -t indicates queue]");
System.out.println();
System.out.println(" -u username");
System.out.println(" -w password");
System.out.println();
System.out.println(" -s single-threaded listener");
System.out.println(" [absence of option => multithreaded]");
System.exit(1);
}
}
| 6,909 |
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/JMSSender.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.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.attachments.Attachments;
import javax.jms.Destination;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* This is meant to be used on a SOAP Client to call a SOAP server.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class JMSSender extends BasicHandler
{
public JMSSender()
{
}
/**
* invoke() creates an endpoint, sends the request SOAP message, and then
* either reads the response SOAP message or simply returns.
*
* TODO: hash on something much better than the connection factory
* something like domain:url:username:password would be adequate
* @param msgContext
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault
{
JMSConnector connector = null;
try
{
Object destination = msgContext.getProperty(JMSConstants.DESTINATION);
if(destination == null)
throw new AxisFault("noDestination");
connector = (JMSConnector)msgContext.getProperty(JMSConstants.CONNECTOR);
JMSEndpoint endpoint = null;
if(destination instanceof String)
endpoint = connector.createEndpoint((String)destination);
else
endpoint = connector.createEndpoint((Destination)destination);
ByteArrayOutputStream out = new ByteArrayOutputStream();
msgContext.getRequestMessage().writeTo(out);
HashMap props = createSendProperties(msgContext);
// If the request message contains attachments, set
// a contentType property to go in the outgoing message header
String ret = null;
Message message = msgContext.getRequestMessage();
Attachments mAttachments = message.getAttachmentsImpl();
if (mAttachments != null && 0 != mAttachments.getAttachmentCount())
{
String contentType = mAttachments.getContentType();
if(contentType != null && !contentType.trim().equals(""))
{
props.put("contentType", contentType);
}
}
boolean waitForResponse = true;
if(msgContext.containsProperty(JMSConstants.WAIT_FOR_RESPONSE))
waitForResponse =
((Boolean)msgContext.getProperty(
JMSConstants.WAIT_FOR_RESPONSE)).booleanValue();
if(waitForResponse)
{
long timeout = (long) msgContext.getTimeout();
byte[] response = endpoint.call(out.toByteArray(), timeout, props);
Message msg = new Message(response);
msgContext.setResponseMessage(msg);
}
else
{
endpoint.send(out.toByteArray(), props);
}
}
catch(Exception e)
{
throw new AxisFault("failedSend", e);
}
finally
{
if (connector != null)
JMSConnectorManager.getInstance().release(connector);
}
}
private HashMap createSendProperties(MessageContext context)
{
//I'm not sure why this helper method is private, but
//we need to delegate to factory method that can build the
//application-specific map of properties so make a change to
//delegate here.
HashMap props = createApplicationProperties(context);
if(context.containsProperty(JMSConstants.PRIORITY))
props.put(JMSConstants.PRIORITY,
context.getProperty(JMSConstants.PRIORITY));
if(context.containsProperty(JMSConstants.DELIVERY_MODE))
props.put(JMSConstants.DELIVERY_MODE,
context.getProperty(JMSConstants.DELIVERY_MODE));
if(context.containsProperty(JMSConstants.TIME_TO_LIVE))
props.put(JMSConstants.TIME_TO_LIVE,
context.getProperty(JMSConstants.TIME_TO_LIVE));
if(context.containsProperty(JMSConstants.JMS_CORRELATION_ID))
props.put(JMSConstants.JMS_CORRELATION_ID,
context.getProperty(JMSConstants.JMS_CORRELATION_ID));
return props;
}
/** Return a map of properties that makeup the application-specific
for the JMS Messages.
*/
protected HashMap createApplicationProperties(MessageContext context) {
HashMap props = null;
if (context.containsProperty(
JMSConstants.JMS_APPLICATION_MSG_PROPS)) {
props = new HashMap();
props.putAll((Map)context.getProperty(
JMSConstants.JMS_APPLICATION_MSG_PROPS));
}
return props;
}
} | 6,910 |
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/JMSTransport.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.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Transport;
import org.apache.axis.components.jms.JMSVendorAdapter;
import org.apache.axis.components.jms.JMSVendorAdapterFactory;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import java.util.HashMap;
/**
* JMSTransport is the JMS-specific implemenation of org.apache.axis.client.Transport.
* It implements the setupMessageContextImpl() function to set JMS-specific message
* context fields and transport chains.
*
* There are two
* Connector and connection factory
* properties are passed in during instantiation and are in turn passed through
* when creating a connector.
*
* @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 class JMSTransport extends Transport
{
protected static Log log =
LogFactory.getLog(JMSTransport.class.getName());
private static HashMap vendorConnectorPools = new HashMap();
private HashMap defaultConnectorProps;
private HashMap defaultConnectionFactoryProps;
static
{
// add a shutdown hook to close JMS connections
Runtime.getRuntime().addShutdownHook(
new Thread()
{
public void run()
{
JMSTransport.closeAllConnectors();
}
}
);
}
public JMSTransport()
{
transportName = "JMSTransport";
}
// this cons is provided for clients that instantiate the JMSTransport directly
public JMSTransport(HashMap connectorProps,
HashMap connectionFactoryProps)
{
this();
defaultConnectorProps = connectorProps;
defaultConnectionFactoryProps = connectionFactoryProps;
}
/**
* Set up any transport-specific derived properties in the message context.
* @param context the context to set up
* @param message the client service instance
* @param engine the engine containing the registries
* @throws AxisFault if service cannot be found
*/
public void setupMessageContextImpl(MessageContext context,
Call message,
AxisEngine engine)
throws AxisFault
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSTransport::setupMessageContextImpl");
}
JMSConnector connector = null;
HashMap connectorProperties = null;
HashMap connectionFactoryProperties = null;
JMSVendorAdapter vendorAdapter = null;
JMSURLHelper jmsurl = null;
// a security context is required to create/use JMSConnectors
String username = message.getUsername();
String password = message.getPassword();
// the presence of an endpoint address indicates whether the client application
// is instantiating the JMSTransport directly (deprecated) or indirectly via JMS URL
String endpointAddr = message.getTargetEndpointAddress();
if (endpointAddr != null)
{
try
{
// performs minimal validation ('jms:/destination?...')
jmsurl = new JMSURLHelper(new java.net.URL(endpointAddr));
// lookup the appropriate vendor adapter
String vendorId = jmsurl.getVendor();
if (vendorId == null)
vendorId = JMSConstants.JNDI_VENDOR_ID;
if (log.isDebugEnabled())
log.debug("JMSTransport.setupMessageContextImpl(): endpt=" + endpointAddr +
", vendor=" + vendorId);
vendorAdapter = JMSVendorAdapterFactory.getJMSVendorAdapter(vendorId);
if (vendorAdapter == null)
{
throw new AxisFault("cannotLoadAdapterClass:" + vendorId);
}
// populate the connector and connection factory properties tables
connectorProperties = vendorAdapter.getJMSConnectorProperties(jmsurl);
connectionFactoryProperties = vendorAdapter.getJMSConnectionFactoryProperties(jmsurl);
}
catch (java.net.MalformedURLException e)
{
log.error(Messages.getMessage("malformedURLException00"), e);
throw new AxisFault(Messages.getMessage("malformedURLException00"), e);
}
}
else
{
// the JMSTransport was instantiated directly, use the default adapter
vendorAdapter = JMSVendorAdapterFactory.getJMSVendorAdapter();
if (vendorAdapter == null)
{
throw new AxisFault("cannotLoadAdapterClass");
}
// use the properties passed in to the constructor
connectorProperties = defaultConnectorProps;
connectionFactoryProperties = defaultConnectionFactoryProps;
}
try
{
connector = JMSConnectorManager.getInstance().getConnector(connectorProperties, connectionFactoryProperties,
username, password, vendorAdapter);
}
catch (Exception e)
{
log.error(Messages.getMessage("cannotConnectError"), e);
if(e instanceof AxisFault)
throw (AxisFault)e;
throw new AxisFault("cannotConnect", e);
}
// store these in the context for later use
context.setProperty(JMSConstants.CONNECTOR, connector);
context.setProperty(JMSConstants.VENDOR_ADAPTER, vendorAdapter);
// vendors may populate the message context
vendorAdapter.setupMessageContext(context, message, jmsurl);
if (log.isDebugEnabled()) {
log.debug("Exit: JMSTransport::setupMessageContextImpl");
}
}
/**
* Shuts down the connectors managed by this JMSTransport.
*/
public void shutdown()
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSTransport::shutdown");
}
closeAllConnectors();
if (log.isDebugEnabled()) {
log.debug("Exit: JMSTransport::shutdown");
}
}
/**
* Closes all JMS connectors
*/
public static void closeAllConnectors()
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSTransport::closeAllConnectors");
}
JMSConnectorManager.getInstance().closeAllConnectors();
if (log.isDebugEnabled()) {
log.debug("Exit: JMSTransport::closeAllConnectors");
}
}
/**
* Closes JMS connectors that match the specified endpoint address
*
* @param endpointAddr the JMS endpoint address
* @param username
* @param password
*/
public static void closeMatchingJMSConnectors(String endpointAddr, String username, String password)
{
if (log.isDebugEnabled()) {
log.debug("Enter: JMSTransport::closeMatchingJMSConnectors");
}
try
{
JMSURLHelper jmsurl = new JMSURLHelper(new java.net.URL(endpointAddr));
String vendorId = jmsurl.getVendor();
JMSVendorAdapter vendorAdapter = null;
if (vendorId == null)
vendorId = JMSConstants.JNDI_VENDOR_ID;
vendorAdapter = JMSVendorAdapterFactory.getJMSVendorAdapter(vendorId);
// the vendor adapter may not exist
if (vendorAdapter == null)
return;
// determine the set of properties to be used for matching the connection
HashMap connectorProps = vendorAdapter.getJMSConnectorProperties(jmsurl);
HashMap cfProps = vendorAdapter.getJMSConnectionFactoryProperties(jmsurl);
JMSConnectorManager.getInstance().closeMatchingJMSConnectors(connectorProps, cfProps,
username, password,
vendorAdapter);
}
catch (java.net.MalformedURLException e)
{
log.warn(Messages.getMessage("malformedURLException00"), e);
}
if (log.isDebugEnabled()) {
log.debug("Exit: JMSTransport::closeMatchingJMSConnectors");
}
}
} | 6,911 |
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/JMSEndpoint.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 java.util.HashMap;
import javax.jms.Destination;
import javax.jms.MessageListener;
import javax.jms.Session;
/**
* JMSEndpoint encapsulates interactions w/ a JMS destination.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public abstract class JMSEndpoint
{
private JMSConnector m_connector;
protected JMSEndpoint(JMSConnector connector)
{
m_connector = connector;
}
abstract Destination getDestination(Session session)
throws Exception;
/**
* Send a message and wait for a response.
*
* @param message
* @param timeout
* @return
* @throws Exception
*/
public byte[] call(byte[] message, long timeout)throws Exception
{
return m_connector.getSendConnection().call(this, message, timeout, null);
}
/**
* Send a message and wait for a response.
*
* @param message
* @param timeout
* @param properties
* @return
* @throws Exception
*/
public byte[] call(byte[] message, long timeout, HashMap properties)
throws Exception
{
if(properties != null)
properties = (HashMap)properties.clone();
return m_connector.getSendConnection().call(this, message, timeout, properties);
}
/**
* Send a message w/o waiting for a response.
*
* @param message
* @throws Exception
*/
public void send(byte[] message)throws Exception
{
m_connector.getSendConnection().send(this, message, null);
}
/**
* Send a message w/o waiting for a response.
*
* @param message
* @param properties
* @throws Exception
*/
public void send(byte[] message, HashMap properties)
throws Exception
{
if(properties != null)
properties = (HashMap)properties.clone();
m_connector.getSendConnection().send(this, message, properties);
}
/**
* Register a MessageListener.
*
* @param listener
* @throws Exception
*/
public void registerListener(MessageListener listener)
throws Exception
{
m_connector.getReceiveConnection().subscribe(createSubscription(listener, null));
}
/**
* Register a MessageListener.
*
* @param listener
* @param properties
* @throws Exception
*/
public void registerListener(MessageListener listener, HashMap properties)
throws Exception
{
if(properties != null)
properties = (HashMap)properties.clone();
m_connector.getReceiveConnection().subscribe(createSubscription(listener, properties));
}
/**
* Unregister a message listener.
*
* @param listener
*/
public void unregisterListener(MessageListener listener)
{
m_connector.getReceiveConnection().unsubscribe(createSubscription(listener, null));
}
/**
* Unregister a message listener.
*
* @param listener
* @param properties
*/
public void unregisterListener(MessageListener listener, HashMap properties)
{
if(properties != null)
properties = (HashMap)properties.clone();
m_connector.getReceiveConnection().unsubscribe(createSubscription(listener, properties));
}
protected Subscription createSubscription(MessageListener listener,
HashMap properties)
{
return new Subscription(listener, this, properties);
}
public int hashCode()
{
return toString().hashCode();
}
public boolean equals(Object object)
{
if(object == null || !(object instanceof JMSEndpoint))
return false;
return true;
}
}
| 6,912 |
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/Subscription.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.MessageListener;
import java.util.HashMap;
/*
* Subscription class holds information about a subscription
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Richard Chung (rchung@sonicsoftware.com)
* @author Dave Chappell (chappell@sonicsoftware.com)
*/
public class Subscription
{
MessageListener m_listener;
JMSEndpoint m_endpoint;
String m_messageSelector;
int m_ackMode;
Subscription(MessageListener listener,
JMSEndpoint endpoint,
HashMap properties)
{
m_listener = listener;
m_endpoint = endpoint;
m_messageSelector = MapUtils.removeStringProperty(
properties,
JMSConstants.MESSAGE_SELECTOR,
null);
m_ackMode = MapUtils.removeIntProperty(properties,
JMSConstants.ACKNOWLEDGE_MODE,
JMSConstants.DEFAULT_ACKNOWLEDGE_MODE);
}
public int hashCode()
{
return toString().hashCode();
}
public boolean equals(Object obj)
{
if(obj == null || !(obj instanceof Subscription))
return false;
Subscription other = (Subscription)obj;
if(m_messageSelector == null)
{
if(other.m_messageSelector != null)
return false;
}
else
{
if(other.m_messageSelector == null ||
!other.m_messageSelector.equals(m_messageSelector))
return false;
}
return m_ackMode == other.m_ackMode &&
m_endpoint.equals(other.m_endpoint) &&
other.m_listener.equals(m_listener);
}
public String toString()
{
return m_listener.toString();
}
} | 6,913 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components/jms/JNDIVendorAdapter.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.components.jms;
import java.util.HashMap;
import java.util.Hashtable;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Topic;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.axis.transport.jms.JMSConstants;
import org.apache.axis.transport.jms.JMSURLHelper;
/**
* Uses JNDI to locate ConnectionFactory and Destinations
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JNDIVendorAdapter extends JMSVendorAdapter
{
public final static String CONTEXT_FACTORY = "java.naming.factory.initial";
public final static String PROVIDER_URL = "java.naming.provider.url";
public final static String _CONNECTION_FACTORY_JNDI_NAME = "ConnectionFactoryJNDIName";
public final static String CONNECTION_FACTORY_JNDI_NAME = JMSConstants.JMS_PROPERTY_PREFIX +
_CONNECTION_FACTORY_JNDI_NAME;
private Context context;
public QueueConnectionFactory getQueueConnectionFactory(HashMap cfConfig)
throws Exception
{
return (QueueConnectionFactory)getConnectionFactory(cfConfig);
}
public TopicConnectionFactory getTopicConnectionFactory(HashMap cfConfig)
throws Exception
{
return (TopicConnectionFactory)getConnectionFactory(cfConfig);
}
private ConnectionFactory getConnectionFactory(HashMap cfProps)
throws Exception
{
if(cfProps == null)
throw new IllegalArgumentException("noCFProps");
String jndiName = (String)cfProps.get(CONNECTION_FACTORY_JNDI_NAME);
if(jndiName == null || jndiName.trim().length() == 0)
throw new IllegalArgumentException("noCFName");
Hashtable environment = new Hashtable(cfProps);
// set the context factory if provided in the JMS URL
String ctxFactory = (String)cfProps.get(CONTEXT_FACTORY);
if (ctxFactory != null)
environment.put(CONTEXT_FACTORY, ctxFactory);
// set the provider url if provided in the JMS URL
String providerURL = (String)cfProps.get(PROVIDER_URL);
if (providerURL != null)
environment.put(PROVIDER_URL, providerURL);
context = new InitialContext(environment);
return (ConnectionFactory)context.lookup(jndiName);
}
/**
* Populates the connection factory config table with properties from
* the JMS URL query string
*
* @param jmsurl The target endpoint address of the Axis call
* @param cfConfig The set of properties necessary to create/configure the connection factory
*/
public void addVendorConnectionFactoryProperties(JMSURLHelper jmsurl,
HashMap cfConfig)
{
// add the connection factory jndi name
String cfJNDIName = jmsurl.getPropertyValue(_CONNECTION_FACTORY_JNDI_NAME);
if (cfJNDIName != null)
cfConfig.put(CONNECTION_FACTORY_JNDI_NAME, cfJNDIName);
// add the initial ctx factory
String ctxFactory = jmsurl.getPropertyValue(CONTEXT_FACTORY);
if (ctxFactory != null)
cfConfig.put(CONTEXT_FACTORY, ctxFactory);
// add the provider url
String providerURL = jmsurl.getPropertyValue(PROVIDER_URL);
if (providerURL != null)
cfConfig.put(PROVIDER_URL, providerURL);
}
/**
* Check that the attributes of the candidate connection factory match the
* requested connection factory properties.
*
* @param cf the candidate connection factory
* @param originalJMSURL the URL which was used to create the connection factory
* @param cfProps the set of properties that should be used to determine the match
* @return true or false to indicate whether a match has been found
*/
public boolean isMatchingConnectionFactory(ConnectionFactory cf,
JMSURLHelper originalJMSURL,
HashMap cfProps)
{
JMSURLHelper jmsurl = (JMSURLHelper)cfProps.get(JMSConstants.JMS_URL);
// just check the connection factory jndi name
String cfJndiName = jmsurl.getPropertyValue(_CONNECTION_FACTORY_JNDI_NAME);
String originalCfJndiName = originalJMSURL.getPropertyValue(_CONNECTION_FACTORY_JNDI_NAME);
if (cfJndiName.equalsIgnoreCase(originalCfJndiName))
return true;
return false;
}
public Queue getQueue(QueueSession session, String name)
throws Exception
{
return (Queue)context.lookup(name);
}
public Topic getTopic(TopicSession session, String name)
throws Exception
{
return (Topic)context.lookup(name);
}
} | 6,914 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components/jms/BeanVendorAdapter.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.components.jms;
import java.util.HashMap;
import javax.jms.ConnectionFactory;
import javax.jms.QueueConnectionFactory;
import javax.jms.TopicConnectionFactory;
import org.apache.axis.utils.BeanPropertyDescriptor;
import org.apache.axis.utils.BeanUtils;
import org.apache.axis.utils.ClassUtils;
/**
* Uses ClassUtils.forName and reflection to configure ConnectionFactory. Uses
* the input sessions to create destinations.
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
*/
public abstract class BeanVendorAdapter extends JMSVendorAdapter
{
protected final static String CONNECTION_FACTORY_CLASS =
"transport.jms.ConnectionFactoryClass";
public QueueConnectionFactory getQueueConnectionFactory(HashMap cfConfig)
throws Exception
{
return (QueueConnectionFactory)getConnectionFactory(cfConfig);
}
public TopicConnectionFactory getTopicConnectionFactory(HashMap cfConfig)
throws Exception
{
return (TopicConnectionFactory)getConnectionFactory(cfConfig);
}
private ConnectionFactory getConnectionFactory(HashMap cfConfig)
throws Exception
{
String classname = (String)cfConfig.get(CONNECTION_FACTORY_CLASS);
if(classname == null || classname.trim().length() == 0)
throw new IllegalArgumentException("noCFClass");
Class factoryClass = ClassUtils.forName(classname);
ConnectionFactory factory = (ConnectionFactory)factoryClass.newInstance();
callSetters(cfConfig, factoryClass, factory);
return factory;
}
private void callSetters(HashMap cfConfig,
Class factoryClass,
ConnectionFactory factory)
throws Exception
{
BeanPropertyDescriptor[] bpd = BeanUtils.getPd(factoryClass);
for(int i = 0; i < bpd.length; i++)
{
BeanPropertyDescriptor thisBPD = bpd[i];
String propName = thisBPD.getName();
if(cfConfig.containsKey(propName))
{
Object value = cfConfig.get(propName);
if(value == null)
continue;
String validType = thisBPD.getType().getName();
if(!value.getClass().getName().equals(validType))
throw new IllegalArgumentException("badType");
if(!thisBPD.isWriteable())
throw new IllegalArgumentException("notWriteable");
if(thisBPD.isIndexed())
throw new IllegalArgumentException("noIndexedSupport");
thisBPD.set(factory, value);
}
}
}
} | 6,915 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components/jms/JMSVendorAdapter.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.components.jms;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Topic;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.transport.jms.JMSConstants;
import org.apache.axis.transport.jms.JMSURLHelper;
/**
* SPI Interface that all JMSVendorAdaptors must implement. Allows for
* ConnectionFactory creation and Destination lookup
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public abstract class JMSVendorAdapter
{
public static final int SEND_ACTION = 0;
public static final int CONNECT_ACTION = 1;
public static final int SUBSCRIBE_ACTION = 2;
public static final int RECEIVE_ACTION = 3;
public static final int ON_EXCEPTION_ACTION = 4;
public abstract QueueConnectionFactory getQueueConnectionFactory(HashMap cfProps)
throws Exception;
public abstract TopicConnectionFactory getTopicConnectionFactory(HashMap cfProps)
throws Exception;
// let adapters add vendor-specific properties or override standard ones
public abstract void addVendorConnectionFactoryProperties(JMSURLHelper jmsurl, HashMap cfProps);
// let adapters match connectors using vendor-specific connection factory properties
public abstract boolean isMatchingConnectionFactory(javax.jms.ConnectionFactory cf, JMSURLHelper jmsurl, HashMap cfProps);
// returns <adapter> in 'org.apache.axis.components.jms.<adapter>VendorAdapter'
public String getVendorId()
{
String name = this.getClass().getName();
// cut off the trailing 'VendorAdapter'
if (name.endsWith(JMSConstants.ADAPTER_POSTFIX))
{
int index = name.lastIndexOf(JMSConstants.ADAPTER_POSTFIX);
name = name.substring(0,index);
}
// cut off the leading 'org.apache.axis.components.jms.'
int index = name.lastIndexOf(".");
if (index > 0)
name = name.substring(index+1);
return name;
}
/**
* Creates a JMS connector property table using values supplied in
* the endpoint address. Properties are translated from the short form
* in the endpoint address to the long form (prefixed by "transport.jms.")
*
* @param jmsurl the endpoint address
* @return the set of properties to be used for instantiating the JMS connector
*/
public HashMap getJMSConnectorProperties(JMSURLHelper jmsurl)
{
HashMap connectorProps = new HashMap();
// the JMS URL may be useful when matching connectors
connectorProps.put(JMSConstants.JMS_URL, jmsurl);
// JMSConstants.CLIENT_ID,
String clientID = jmsurl.getPropertyValue(JMSConstants._CLIENT_ID);
if (clientID != null)
connectorProps.put(JMSConstants.CLIENT_ID, clientID);
// JMSConstants.CONNECT_RETRY_INTERVAL,
String connectRetryInterval = jmsurl.getPropertyValue(JMSConstants._CONNECT_RETRY_INTERVAL);
if (connectRetryInterval != null)
connectorProps.put(JMSConstants.CONNECT_RETRY_INTERVAL, connectRetryInterval);
// JMSConstants.INTERACT_RETRY_INTERVAL,
String interactRetryInterval = jmsurl.getPropertyValue(JMSConstants._INTERACT_RETRY_INTERVAL);
if (interactRetryInterval != null)
connectorProps.put(JMSConstants.INTERACT_RETRY_INTERVAL, interactRetryInterval);
// JMSConstants.DOMAIN
String domain = jmsurl.getPropertyValue(JMSConstants._DOMAIN);
if (domain != null)
connectorProps.put(JMSConstants.DOMAIN, domain);
// JMSConstants.NUM_RETRIES
String numRetries = jmsurl.getPropertyValue(JMSConstants._NUM_RETRIES);
if (numRetries != null)
connectorProps.put(JMSConstants.NUM_RETRIES, numRetries);
// JMSConstants.NUM_SESSIONS
String numSessions = jmsurl.getPropertyValue(JMSConstants._NUM_SESSIONS);
if (numSessions != null)
connectorProps.put(JMSConstants.NUM_SESSIONS, numSessions);
// JMSConstants.TIMEOUT_TIME,
String timeoutTime = jmsurl.getPropertyValue(JMSConstants._TIMEOUT_TIME);
if (timeoutTime != null)
connectorProps.put(JMSConstants.TIMEOUT_TIME, timeoutTime);
return connectorProps;
}
/**
*
* Creates a connection factory property table using values supplied in
* the endpoint address
*
* @param jmsurl the endpoint address
* @return the set of properties to be used for instantiating the connection factory
*/
public HashMap getJMSConnectionFactoryProperties(JMSURLHelper jmsurl)
{
HashMap cfProps = new HashMap();
// hold on to the original address (this will be useful when the JNDI vendor adapter
// matches connectors)
cfProps.put(JMSConstants.JMS_URL, jmsurl);
// JMSConstants.DOMAIN
String domain = jmsurl.getPropertyValue(JMSConstants._DOMAIN);
if (domain != null)
cfProps.put(JMSConstants.DOMAIN, domain);
// allow vendors to customize the cf properties table
addVendorConnectionFactoryProperties(jmsurl, cfProps);
return cfProps;
}
public Queue getQueue(QueueSession session, String name)
throws Exception
{
return session.createQueue(name);
}
public Topic getTopic(TopicSession session, String name)
throws Exception
{
return session.createTopic(name);
}
public boolean isRecoverable(Throwable thrown, int action)
{
if(thrown instanceof RuntimeException ||
thrown instanceof Error ||
thrown instanceof JMSSecurityException ||
thrown instanceof InvalidDestinationException)
return false;
if(action == ON_EXCEPTION_ACTION)
return false;
return true;
}
public void setProperties(Message message, HashMap props)
throws JMSException
{
Iterator iter = props.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
String value = (String)props.get(key);
message.setStringProperty(key, value);
}
}
/**
* Set JMS properties in the message context.
*
* TODO: just copy all properties that are not used for the JMS connector
* or connection factory
*/
public void setupMessageContext(MessageContext context,
Call call,
JMSURLHelper jmsurl)
{
Object tmp = null;
String jmsurlDestination = null;
if (jmsurl != null)
jmsurlDestination = jmsurl.getDestination();
if (jmsurlDestination != null)
context.setProperty(JMSConstants.DESTINATION, jmsurlDestination);
else
{
tmp = call.getProperty(JMSConstants.DESTINATION);
if (tmp != null && tmp instanceof String)
context.setProperty(JMSConstants.DESTINATION, tmp);
else
context.removeProperty(JMSConstants.DESTINATION);
}
String delivMode = null;
if (jmsurl != null)
delivMode = jmsurl.getPropertyValue(JMSConstants._DELIVERY_MODE);
if (delivMode != null)
{
int mode = JMSConstants.DEFAULT_DELIVERY_MODE;
if (delivMode.equalsIgnoreCase(JMSConstants.DELIVERY_MODE_PERSISTENT))
mode = javax.jms.DeliveryMode.PERSISTENT;
else if (delivMode.equalsIgnoreCase(JMSConstants.DELIVERY_MODE_NONPERSISTENT))
mode = javax.jms.DeliveryMode.NON_PERSISTENT;
context.setProperty(JMSConstants.DELIVERY_MODE, new Integer(mode));
}
else
{
tmp = call.getProperty(JMSConstants.DELIVERY_MODE);
if(tmp != null && tmp instanceof Integer)
context.setProperty(JMSConstants.DELIVERY_MODE, tmp);
else
context.removeProperty(JMSConstants.DELIVERY_MODE);
}
String prio = null;
if (jmsurl != null)
prio = jmsurl.getPropertyValue(JMSConstants._PRIORITY);
if (prio != null)
context.setProperty(JMSConstants.PRIORITY, Integer.valueOf(prio));
else
{
tmp = call.getProperty(JMSConstants.PRIORITY);
if(tmp != null && tmp instanceof Integer)
context.setProperty(JMSConstants.PRIORITY, tmp);
else
context.removeProperty(JMSConstants.PRIORITY);
}
String ttl = null;
if (jmsurl != null)
ttl = jmsurl.getPropertyValue(JMSConstants._TIME_TO_LIVE);
if (ttl != null)
context.setProperty(JMSConstants.TIME_TO_LIVE, Long.valueOf(ttl));
else
{
tmp = call.getProperty(JMSConstants.TIME_TO_LIVE);
if(tmp != null && tmp instanceof Long)
context.setProperty(JMSConstants.TIME_TO_LIVE, tmp);
else
context.removeProperty(JMSConstants.TIME_TO_LIVE);
}
String wait = null;
if (jmsurl != null)
wait = jmsurl.getPropertyValue(JMSConstants._WAIT_FOR_RESPONSE);
if (wait != null)
context.setProperty(JMSConstants.WAIT_FOR_RESPONSE, Boolean.valueOf(wait));
else
{
tmp = call.getProperty(JMSConstants.WAIT_FOR_RESPONSE);
if(tmp != null && tmp instanceof Boolean)
context.setProperty(JMSConstants.WAIT_FOR_RESPONSE, tmp);
else
context.removeProperty(JMSConstants.WAIT_FOR_RESPONSE);
}
setupApplicationProperties(context, call, jmsurl);
}
public void setupApplicationProperties(MessageContext context,
Call call,
JMSURLHelper jmsurl)
{
//start with application properties from the URL
Map appProps = new HashMap();
if (jmsurl != null && jmsurl.getApplicationProperties() != null) {
for(Iterator itr=jmsurl.getApplicationProperties().iterator();
itr.hasNext();) {
String name = (String)itr.next();
appProps.put(name,jmsurl.getPropertyValue(name));
}
}
//next add application properties from the message context
Map ctxProps =
(Map)context.getProperty(JMSConstants.JMS_APPLICATION_MSG_PROPS);
if (ctxProps != null) {
appProps.putAll(ctxProps);
}
//finally add the properties from the call
Map callProps =
(Map)call.getProperty(JMSConstants.JMS_APPLICATION_MSG_PROPS);
if (callProps != null) {
appProps.putAll(callProps);
}
//now tore these properties within the context
context.setProperty(JMSConstants.JMS_APPLICATION_MSG_PROPS,appProps);
}
} | 6,916 |
0 | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-transport-jms/src/main/java/org/apache/axis/components/jms/JMSVendorAdapterFactory.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.components.jms;
import org.apache.axis.AxisProperties;
import java.util.HashMap;
/**
* Discovery class used to locate vendor adapters. Switch the default
* JNDI-based implementation by using the
* org.apache.axis.components.jms.JMSVendorAdapter system property
*
* @author Jaime Meritt (jmeritt@sonicsoftware.com)
* @author Ray Chun (rchun@sonicsoftware.com)
*/
public class JMSVendorAdapterFactory
{
private static HashMap s_adapters = new HashMap();
private final static String VENDOR_PKG = "org.apache.axis.components.jms";
static {
AxisProperties.setClassDefault(JMSVendorAdapter.class,
VENDOR_PKG + ".JNDIVendorAdapter");
}
public static final JMSVendorAdapter getJMSVendorAdapter()
{
return (JMSVendorAdapter)AxisProperties.newInstance(JMSVendorAdapter.class);
}
public static final JMSVendorAdapter getJMSVendorAdapter(String vendorId)
{
// check to see if the adapter has already been instantiated
if (s_adapters.containsKey(vendorId))
return (JMSVendorAdapter)s_adapters.get(vendorId);
// create a new instance
JMSVendorAdapter adapter = null;
try
{
Class vendorClass = Class.forName(getVendorAdapterClassname(vendorId));
adapter = (JMSVendorAdapter)vendorClass.newInstance();
}
catch (Exception e)
{
return null;
}
synchronized (s_adapters)
{
if (s_adapters.containsKey(vendorId))
return (JMSVendorAdapter)s_adapters.get(vendorId);
if (adapter != null)
s_adapters.put(vendorId, adapter);
}
return adapter;
}
private static String getVendorAdapterClassname(String vendorId)
{
StringBuffer sb = new StringBuffer(VENDOR_PKG).append(".");
sb.append(vendorId);
sb.append("VendorAdapter");
return sb.toString();
}
} | 6,917 |
0 | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis/monitor/SOAPMonitorService.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.monitor;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
/**
* This is a SOAP Monitor Service class.
*
* During the HTTP server startup, the servlet init method
* is invoked. This allows the code to open a server
* socket that will be used to communicate with running
* applets.
*
* When an HTTP GET request is received, the servlet
* dynamically produces an HTML document to load the SOAP
* monitor applet and supply the port number being used by
* the server socket (so the applet will know how to
* connect back to the server).
*
* Each time a socket connection is established, a new
* thread is created to handle communications from the
* applet.
*
* The publishMethod routine is invoked by the SOAP monitor
* handler when a SOAP message request or response is
* detected. The information about the SOAP message is
* then forwared to all current socket connections for
* display by the applet.
*
* @author Brian Price (pricebe@us.ibm.com)
*/
public class SOAPMonitorService extends HttpServlet {
/**
* Private data
*/
private static ServerSocket server_socket = null;
private static Vector connections = null;
/**
* Constructor
*/
public SOAPMonitorService() {
}
/**
* Publish a SOAP message to listeners
*/
public static void publishMessage(Long id,
Integer type,
String target,
String soap) {
if (connections != null) {
Enumeration e = connections.elements();
while (e.hasMoreElements()) {
ConnectionThread ct = (ConnectionThread) e.nextElement();
ct.publishMessage(id,type,target,soap);
}
}
}
/**
* Servlet initialiation
*/
public void init() throws ServletException {
if (connections == null) {
// Create vector to hold connection information
connections = new Vector();
}
if (server_socket == null) {
// Get the server socket port from the init params
ServletConfig config = super.getServletConfig();
String port = config.getInitParameter(SOAPMonitorConstants.SOAP_MONITOR_PORT);
if (port == null) {
// No port defined, so let the system assign a port
port = "0";
}
try {
// Try to open the server socket
server_socket = new ServerSocket(Integer.parseInt(port));
} catch (Exception e) {
// Let someone know we could not open the socket
// System. out.println("Unable to open server socket using port "+port+".");
server_socket = null;
}
if (server_socket != null) {
// Start the server socket thread
new Thread(new ServerSocketThread()).start();
}
}
}
/**
* Servlet termination
*/
public void destroy() {
// End all connection threads
Enumeration e = connections.elements();
while (e.hasMoreElements()) {
ConnectionThread ct = (ConnectionThread) e.nextElement();
ct.close();
}
// End main server socket thread
if (server_socket != null) {
try {
server_socket.close();
} catch (Exception x) {}
server_socket = null;
}
}
/**
* HTTP GET request
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// Create HTML to load the SOAP monitor applet
int port = 0;
if (server_socket != null) {
port = server_socket.getLocalPort();
}
response.setContentType("text/html");
response.getWriter().println("<html>");
response.getWriter().println("<head>");
response.getWriter().println("<title>SOAP Monitor</title>");
response.getWriter().println("</head>");
response.getWriter().println("<body>");
response.getWriter().println("<object classid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\" width=100% height=100% codebase=\"http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0\">");
response.getWriter().println("<param name=code value=SOAPMonitorApplet.class>");
response.getWriter().println("<param name=\"type\" value=\"application/x-java-applet;version=1.3\">");
response.getWriter().println("<param name=\"scriptable\" value=\"false\">");
response.getWriter().println("<param name=\"port\" value=\""+port+"\">");
response.getWriter().println("<comment>");
response.getWriter().println("<embed type=\"application/x-java-applet;version=1.3\" code=SOAPMonitorApplet.class width=100% height=100% port=\""+port+"\" scriptable=false pluginspage=\"http://java.sun.com/products/plugin/1.3/plugin-install.html\">");
response.getWriter().println("<noembed>");
response.getWriter().println("</comment>");
response.getWriter().println("</noembed>");
response.getWriter().println("</embed>");
response.getWriter().println("</object>");
response.getWriter().println("</body>");
response.getWriter().println("</html>");
}
/**
* Thread class for handling the server socket
*/
class ServerSocketThread implements Runnable {
/**
* Thread for handling the server socket
*/
public void run() {
// Wait for socket connections
while (server_socket != null) {
try {
Socket socket = server_socket.accept();
new Thread(new ConnectionThread(socket)).start();
} catch (IOException ioe) {}
}
}
}
/**
* Thread class for handling socket connections
*/
class ConnectionThread implements Runnable {
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
private boolean closed = false;
/**
* Constructor
*/
public ConnectionThread(Socket s) {
socket = s;
try {
// Use object streams for input and output
//
// NOTE: We need to be sure to create and flush the
// output stream first because the ObjectOutputStream
// constructor writes a header to the stream that is
// needed by the ObjectInputStream on the other end
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
} catch (Exception e) {}
// Add the connection to our list
synchronized (connections) {
connections.addElement(this);
}
}
/**
* Close the socket connection
*/
public void close() {
closed = true;
try {
socket.close();
} catch (IOException ioe) {}
}
/**
* Thread to handle the socket connection
*/
public void run() {
try {
while (!closed) {
Object o = in.readObject();
}
} catch (Exception e) {}
// Cleanup connection list
synchronized (connections) {
connections.removeElement(this);
}
// Cleanup I/O streams
if (out != null) {
try {
out.close();
} catch (IOException ioe) {}
out = null;
}
if (in != null) {
try {
in.close();
} catch (IOException ioe) {}
in = null;
}
// Be sure the socket is closed
close();
}
/**
* Publish SOAP message information
*/
public synchronized void publishMessage(Long id,
Integer message_type,
String target,
String soap) {
// If we have a valid output stream, then
// send the data to the applet
if (out != null) {
try {
switch (message_type.intValue()) {
case SOAPMonitorConstants.SOAP_MONITOR_REQUEST:
out.writeObject(message_type);
out.writeObject(id);
out.writeObject(target);
out.writeObject(soap);
out.flush();
break;
case SOAPMonitorConstants.SOAP_MONITOR_RESPONSE:
out.writeObject(message_type);
out.writeObject(id);
out.writeObject(soap);
out.flush();
break;
}
} catch (Exception e) {}
}
}
}
}
| 6,918 |
0 | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis/monitor/SOAPMonitorConstants.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.monitor;
/**
* SOAP Monitor Service constants
*
* @author Brian Price (pricebe@us.ibm.com)
*/
public class SOAPMonitorConstants {
/**
* SOAP message types
*/
public static final int SOAP_MONITOR_REQUEST = 0;
public static final int SOAP_MONITOR_RESPONSE = 1;
/**
* Servlet initialization parameter names
*/
public static final String SOAP_MONITOR_PORT = "SOAPMonitorPort";
/**
* Unique SOAP monitor id tag
*/
public static final String SOAP_MONITOR_ID = "SOAPMonitorId";
}
| 6,919 |
0 | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-soapmonitor/src/main/java/org/apache/axis/handlers/SOAPMonitorHandler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.handlers;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.SOAPPart;
import org.apache.axis.monitor.SOAPMonitorConstants;
import org.apache.axis.monitor.SOAPMonitorService;
/**
* This handler is used to route SOAP messages to the
* SOAP monitor service.
*
* @author Brian Price (pricebe@us.ibm.com)
*/
public class SOAPMonitorHandler extends BasicHandler {
private static long next_message_id = 1;
/**
* Constructor
*/
public SOAPMonitorHandler() {
super();
}
/**
* Process and SOAP message
*/
public void invoke(MessageContext messageContext) throws AxisFault {
String target = messageContext.getTargetService();
// Check for null target
if (target == null) {
target = "";
}
// Get id, type and content
Long id;
Integer type;
Message message;
if (!messageContext.getPastPivot()) {
id = assignMessageId(messageContext);
type = new Integer(SOAPMonitorConstants.SOAP_MONITOR_REQUEST);
message = messageContext.getRequestMessage();
} else {
id = getMessageId(messageContext);
type = new Integer(SOAPMonitorConstants.SOAP_MONITOR_RESPONSE);
message = messageContext.getResponseMessage();
}
// Get the SOAP portion of the message
String soap = null;
if (message != null) {
soap = ((SOAPPart)message.getSOAPPart()).getAsString();
}
// If we have an id and a SOAP portion, then send the
// message to the SOAP monitor service
if ((id != null) && (soap != null)) {
SOAPMonitorService.publishMessage(id,type,target,soap);
}
}
/**
* Assign a new message id
*/
private Long assignMessageId(MessageContext messageContext) {
Long id = null;
synchronized(SOAPMonitorConstants.SOAP_MONITOR_ID) {
id = new Long(next_message_id);
next_message_id++;
}
messageContext.setProperty(SOAPMonitorConstants.SOAP_MONITOR_ID, id);
return id;
}
/**
* Get the already assigned message id
*/
private Long getMessageId(MessageContext messageContext) {
Long id = null;
id = (Long) messageContext.getProperty(SOAPMonitorConstants.SOAP_MONITOR_ID);
return id;
}
}
| 6,920 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/configuration/DefaultEngineConfigurationFactory.java | /*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.configuration;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.EngineConfigurationFactory;
/**
* This is a 'front' for replacement logic.
* Use EngineConfigurationFactoryFinder.newFactory().
*
* @author Richard A. Sitze
* @author Glyn Normington (glyn@apache.org)
*
* @deprecated
*/
public class DefaultEngineConfigurationFactory
implements EngineConfigurationFactory
{
protected final EngineConfigurationFactory factory;
protected DefaultEngineConfigurationFactory(EngineConfigurationFactory factory) {
this.factory = factory;
}
/**
* Create the default engine configuration and detect whether the user
* has overridden this with their own.
*/
public DefaultEngineConfigurationFactory() {
this(EngineConfigurationFactoryFinder.newFactory());
}
/**
* Get a default client engine configuration.
*
* @return a client EngineConfiguration
*/
public EngineConfiguration getClientEngineConfig() {
return factory == null ? null : factory.getClientEngineConfig();
}
/**
* Get a default server engine configuration.
*
* @return a server EngineConfiguration
*/
public EngineConfiguration getServerEngineConfig() {
return factory == null ? null : factory.getServerEngineConfig();
}
}
| 6,921 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/configuration/ServletEngineConfigurationFactory.java | /*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.configuration;
import javax.servlet.ServletContext;
/**
* This is a 'front' for replacement logic.
* Use EngineConfigurationFactoryFinder.newFactory(yourServletContext).
*
* @author Richard A. Sitze
* @author Glyn Normington (glyn@apache.org)
*
* @deprecated
*/
public class ServletEngineConfigurationFactory
extends DefaultEngineConfigurationFactory
{
public ServletEngineConfigurationFactory(ServletContext ctx) {
super(EngineConfigurationFactoryFinder.newFactory(ctx));
}
}
| 6,922 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport/http/NonBlockingBufferedInputStream.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.transport.http;
import java.io.IOException;
import java.io.InputStream;
public class NonBlockingBufferedInputStream extends InputStream {
// current stream to be processed
private InputStream in;
// maximum number of bytes allowed to be returned.
private int remainingContent = Integer.MAX_VALUE;
// Internal buffer for the input stream
private byte[] buffer = new byte[4096];
private int offset = 0; // bytes before this offset have been processed
private int numbytes = 0; // number of valid bytes in this buffer
/**
* set the input stream to be used for subsequent reads
* @param in the InputStream
*/
public void setInputStream (InputStream in) {
this.in = in;
numbytes = 0;
offset = 0;
remainingContent = (in==null)? 0 : Integer.MAX_VALUE;
}
/**
* set the maximum number of bytes allowed to be read from this input
* stream.
* @param value the Content Length
*/
public void setContentLength (int value) {
if (in != null) this.remainingContent = value - (numbytes-offset);
}
/**
* Replenish the buffer with data from the input stream. This is
* guaranteed to read atleast one byte or throw an exception. When
* possible, it will read up to the length of the buffer
* the data is buffered for efficiency.
* @return the byte read
*/
private void refillBuffer() throws IOException {
if (remainingContent <= 0 || in == null) return;
// determine number of bytes to read
numbytes = in.available();
if (numbytes > remainingContent) numbytes=remainingContent;
if (numbytes > buffer.length) numbytes=buffer.length;
if (numbytes <= 0) numbytes = 1;
// actually attempt to read those bytes
numbytes = in.read(buffer, 0, numbytes);
// update internal state to reflect this read
remainingContent -= numbytes;
offset = 0;
}
/**
* Read a byte from the input stream, blocking if necessary. Internally
* the data is buffered for efficiency.
* @return the byte read
*/
public int read() throws IOException {
if (in == null) return -1;
if (offset >= numbytes) refillBuffer();
if (offset >= numbytes) return -1;
return buffer[offset++] & 0xFF;
}
/**
* Read bytes from the input stream. This is guaranteed to return at
* least one byte or throw an exception. When possible, it will return
* more bytes, up to the length of the array, as long as doing so would
* not require waiting on bytes from the input stream.
* @param dest byte array to read into
* @return the number of bytes actually read
*/
public int read(byte[] dest) throws IOException {
return read(dest, 0, dest.length);
}
/**
* Read a specified number of bytes from the input stream. This is
* guaranteed to return at least one byte or throw an execption. When
* possible, it will return more bytes, up to the length specified,
* as long as doing so would not require waiting on bytes from the
* input stream.
* @param dest byte array to read into
* @param off starting offset into the byte array
* @param len maximum number of bytes to read
* @return the number of bytes actually read
*/
public int read(byte[] dest, int off, int len) throws IOException {
int ready = numbytes - offset;
if (ready >= len) {
System.arraycopy(buffer, offset, dest, off, len);
offset += len;
return len;
} else if (ready>0) {
System.arraycopy(buffer, offset, dest, off, ready);
offset = numbytes;
return ready;
} else {
if (in == null) return -1;
refillBuffer();
if (offset >= numbytes) return -1;
return read(dest,off,len);
}
}
/**
* skip over (and discard) a specified number of bytes in this input
* stream
* @param len the number of bytes to be skipped
* @return the action number of bytes skipped
*/
public int skip(int len) throws IOException {
int count = 0;
while (len-->0 && read()>=0) count++;
return count;
}
/**
* return the number of bytes available to be read without blocking
* @return the number of bytes
*/
public int available() throws IOException {
if (in == null) return 0;
// return buffered + available from the stream
return (numbytes-offset) + in.available();
}
/**
* disassociate from the underlying input stream
*/
public void close() throws IOException {
setInputStream(null);
}
/**
* Just like read except byte is not removed from the buffer.
* the data is buffered for efficiency.
* Was added to support multiline http headers. ;-)
* @return the byte read
*/
public int peek() throws IOException {
if (in == null) return -1;
if (offset >= numbytes) refillBuffer();
if (offset >= numbytes) return -1;
return buffer[offset] & 0xFF;
}
}
| 6,923 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport/http/SimpleAxisServer.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.transport.http;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.components.threadpool.ThreadPool;
import org.apache.axis.server.AxisServer;
import org.apache.axis.session.Session;
import org.apache.axis.session.SimpleSession;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.Options;
import org.apache.axis.utils.NetworkUtils;
import org.apache.axis.collections.LRUMap;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.management.ServiceAdmin;
import org.apache.axis.configuration.EngineConfigurationFactoryFinder;
import org.apache.commons.logging.Log;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.io.IOException;
import java.io.File;
/**
* This is a simple implementation of an HTTP server for processing
* SOAP requests via Apache's xml-axis. This is not intended for production
* use. Its intended uses are for demos, debugging, and performance
* profiling.
*
* Note this classes uses static objects to provide a thread pool, so you should
* not use multiple instances of this class in the same JVM/classloader unless
* you want bad things to happen at shutdown.
* @author Sam Ruby (ruby@us.ibm.com)
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Alireza Taherkordi (a_taherkordi@users.sourceforge.net)
*/
public class SimpleAxisServer implements Runnable {
protected static Log log =
LogFactory.getLog(SimpleAxisServer.class.getName());
// session state.
// This table maps session keys (random numbers) to SimpleAxisSession objects.
//
// There is a simple LRU based session cleanup mechanism, but if clients are not
// passing cookies, then a new session will be created for *every* request.
private Map sessions;
//Maximum capacity of the LRU Map used for session cleanup
private int maxSessions;
public static final int MAX_SESSIONS_DEFAULT = 100;
/**
* get the thread pool
* @return
*/
public static ThreadPool getPool() {
return pool;
}
/**
* pool of threads
*/
private static ThreadPool pool;
/** Are we doing threads?
* */
private static boolean doThreads = true;
/* Are we doing sessions?
Set this to false if you don't want any session overhead.
*/
private static boolean doSessions = true;
/**
* create a server with the default threads and sessions.
*/
public SimpleAxisServer() {
this(ThreadPool.DEFAULT_MAX_THREADS);
}
/**
* Create a server with a configurable pool side; sessions set to the default
* limit
* @param maxPoolSize maximum thread pool size
*/
public SimpleAxisServer(int maxPoolSize) {
this(maxPoolSize, MAX_SESSIONS_DEFAULT);
}
/**
* Constructor
* @param maxPoolSize max number of threads
* @param maxSessions maximum sessions
*/
public SimpleAxisServer(int maxPoolSize, int maxSessions) {
this.maxSessions = maxSessions;
sessions = new LRUMap(maxSessions);
pool = new ThreadPool(maxPoolSize);
}
/**
* stop the server if not already told to.
* @throws Throwable
*/
protected void finalize() throws Throwable {
stop();
super.finalize();
}
/**
* get max session count
* @return
*/
public int getMaxSessions() {
return maxSessions;
}
/**
* Resize the session map
* @param maxSessions maximum sessions
*/
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
((LRUMap)sessions).setMaximumSize(maxSessions);
}
//---------------------------------------------------
protected boolean isSessionUsed() {
return doSessions;
}
/**
* turn threading on or off. This sets a static value
* @param value
*/
public void setDoThreads(boolean value) {
doThreads = value ;
}
public boolean getDoThreads() {
return doThreads ;
}
public EngineConfiguration getMyConfig() {
return myConfig;
}
public void setMyConfig(EngineConfiguration myConfig) {
this.myConfig = myConfig;
}
/**
* demand create a session if there is not already one for the string
* @param cooky
* @return a session.
*/
protected Session createSession(String cooky) {
// is there a session already?
Session session = null;
if (sessions.containsKey(cooky)) {
session = (Session) sessions.get(cooky);
} else {
// no session for this cooky, bummer
session = new SimpleSession();
// ADD CLEANUP LOGIC HERE if needed
sessions.put(cooky, session);
}
return session;
}
// What is our current session index?
// This is a monotonically increasing, non-thread-safe integer
// (thread safety not considered crucial here)
public static int sessionIndex = 0;
// Axis server (shared between instances)
private static AxisServer myAxisServer = null;
private EngineConfiguration myConfig = null;
/**
* demand create an axis server; return an existing one if one exists.
* The configuration for the axis server is derived from #myConfig if not null,
* the default config otherwise.
* @return
*/
public synchronized AxisServer getAxisServer() {
if (myAxisServer == null) {
if (myConfig == null) {
myConfig = EngineConfigurationFactoryFinder.newFactory().getServerEngineConfig();
}
myAxisServer = new AxisServer(myConfig);
ServiceAdmin.setEngine(myAxisServer, NetworkUtils.getLocalHostname() + "@" + serverSocket.getLocalPort());
}
return myAxisServer;
}
/**
are we stopped?
latch to true if stop() is called
*/
private boolean stopped = false;
/**
* Accept requests from a given TCP port and send them through the
* Axis engine for processing.
*/
public void run() {
log.info(Messages.getMessage("start01", "SimpleAxisServer",
new Integer(getServerSocket().getLocalPort()).toString(),getCurrentDirectory()));
// Accept and process requests from the socket
while (!stopped) {
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (java.io.InterruptedIOException iie) {
} catch (Exception e) {
log.debug(Messages.getMessage("exception00"), e);
break;
}
if (socket != null) {
SimpleAxisWorker worker = new SimpleAxisWorker(this, socket);
if (doThreads) {
pool.addWorker(worker);
} else {
worker.run();
}
}
}
log.info(Messages.getMessage("quit00", "SimpleAxisServer"));
}
/**
* Gets the current directory
* @return current directory
*/
private String getCurrentDirectory() {
return System.getProperty("user.dir");
}
/**
* per thread socket information
*/
private ServerSocket serverSocket;
/**
* Obtain the serverSocket that that SimpleAxisServer is listening on.
*/
public ServerSocket getServerSocket() {
return serverSocket;
}
/**
* Set the serverSocket this server should listen on.
* (note : changing this will not affect a running server, but if you
* stop() and then start() the server, the new socket will be used).
*/
public void setServerSocket(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
/**
* Start this server.
*
* Spawns a worker thread to listen for HTTP requests.
*
* @param daemon a boolean indicating if the thread should be a daemon.
*/
public void start(boolean daemon) throws Exception {
stopped=false;
if (doThreads) {
Thread thread = new Thread(this);
thread.setDaemon(daemon);
thread.start();
} else {
run();
}
}
/**
* Start this server as a NON-daemon.
*/
public void start() throws Exception {
start(false);
}
/**
* Stop this server. Can be called safely if the system is already stopped,
* or if it was never started.
*
* This will interrupt any pending accept().
*/
public void stop() {
//recognise use before we are live
if(stopped ) {
return;
}
/*
* Close the server socket cleanly, but avoid fresh accepts while
* the socket is closing.
*/
stopped = true;
try {
if(serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
log.info(Messages.getMessage("exception00"), e);
} finally {
serverSocket=null;
}
log.info(Messages.getMessage("quit00", "SimpleAxisServer"));
//shut down the pool
pool.shutdown();
}
/**
* Server process.
*/
public static void main(String args[]) {
Options opts = null;
try {
opts = new Options(args);
} catch (MalformedURLException e) {
log.error(Messages.getMessage("malformedURLException00"), e);
return;
}
String maxPoolSize = opts.isValueSet('t');
if (maxPoolSize==null) maxPoolSize = ThreadPool.DEFAULT_MAX_THREADS + "";
String maxSessions = opts.isValueSet('m');
if (maxSessions==null) maxSessions = MAX_SESSIONS_DEFAULT + "";
SimpleAxisServer sas = new SimpleAxisServer(Integer.parseInt(maxPoolSize),
Integer.parseInt(maxSessions));
try {
doThreads = (opts.isFlagSet('t') > 0);
int port = opts.getPort();
ServerSocket ss = null;
// Try five times
final int retries = 5;
for (int i = 0; i < retries; i++) {
try {
ss = new ServerSocket(port);
break;
} catch (java.net.BindException be){
log.debug(Messages.getMessage("exception00"), be);
if (i < (retries-1)) {
// At 3 second intervals.
Thread.sleep(3000);
} else {
throw new Exception(Messages.getMessage("unableToStartServer00",
Integer.toString(port)));
}
}
}
sas.setServerSocket(ss);
sas.start();
} catch (Exception e) {
log.error(Messages.getMessage("exception00"), e);
return;
}
}
}
| 6,924 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport/http/JettyAxisServer.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.transport.http;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.Options;
import org.apache.commons.logging.Log;
import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpServer;
import org.mortbay.http.SocketListener;
import org.mortbay.http.handler.ResourceHandler;
import org.mortbay.jetty.servlet.ServletHandler;
import java.net.MalformedURLException;
public class JettyAxisServer {
protected static Log log =
LogFactory.getLog(JettyAxisServer.class.getName());
/**
* Jetty HTTP Server *
*/
HttpServer server = new HttpServer();
/**
* Socket Listener *
*/
SocketListener listener = new SocketListener();
/**
* HTTP Context
*/
HttpContext context = new HttpContext();
public JettyAxisServer() {
// Create a context
context.setContextPath("/axis/*");
server.addContext(context);
// Create a servlet container
ServletHandler servlets = new ServletHandler();
context.addHandler(servlets);
// Map a servlet onto the container
servlets.addServlet("AdminServlet", "/servlet/AdminServlet",
"org.apache.axis.transport.http.AdminServlet");
servlets.addServlet("AxisServlet", "/servlet/AxisServlet",
"org.apache.axis.transport.http.AxisServlet");
servlets.addServlet("AxisServlet", "/services/*",
"org.apache.axis.transport.http.AxisServlet");
servlets.addServlet("AxisServlet", "*.jws",
"org.apache.axis.transport.http.AxisServlet");
context.addHandler(new ResourceHandler());
}
/**
* Set the port
*
* @param port
*/
public void setPort(int port) {
listener.setPort(port);
server.addListener(listener);
}
/**
* Set the resource base
*
* @param dir
*/
public void setResourceBase(String dir) {
context.setResourceBase(dir);
}
/**
* Start the server
*
* @throws Exception
*/
public void start() throws Exception {
server.start();
log.info(
Messages.getMessage("start00", "JettyAxisServer",
new Integer(listener.getServerSocket().getLocalPort()).toString()));
}
public static void main(String[] args) {
Options opts = null;
try {
opts = new Options(args);
} catch (MalformedURLException e) {
log.error(Messages.getMessage("malformedURLException00"), e);
return;
}
JettyAxisServer server = new JettyAxisServer();
server.setPort(opts.getPort());
String dir = opts.isValueSet('d');
if (dir == null) {
// Serve static content from the context
dir = System.getProperty("jetty.home", ".") + "/webapps/axis/";
}
server.setResourceBase(dir);
// Start the http server
try {
server.start();
} catch (Exception e) {
log.error(Messages.getMessage("exception00"), e);
}
}
} | 6,925 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/transport/http/SimpleAxisWorker.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.transport.http;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.encoding.Base64;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPFault;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.utils.NetworkUtils;
import org.apache.commons.logging.Log;
import org.w3c.dom.Document;
import javax.xml.namespace.QName;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPMessage;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class SimpleAxisWorker implements Runnable {
protected static Log log =
LogFactory.getLog(SimpleAxisWorker.class.getName());
private SimpleAxisServer server;
private Socket socket;
// Axis specific constants
private static String transportName = "SimpleHTTP";
// HTTP status codes
private static byte OK[] = ("200 " + Messages.getMessage("ok00")).getBytes();
private static byte NOCONTENT[] = ("202 " + Messages.getMessage("ok00") + "\n\n").getBytes();
private static byte UNAUTH[] = ("401 " + Messages.getMessage("unauth00")).getBytes();
private static byte SENDER[] = "400".getBytes();
private static byte ISE[] = ("500 " + Messages.getMessage("internalError01")).getBytes();
// HTTP prefix
private static byte HTTP[] = "HTTP/1.0 ".getBytes();
// Standard MIME headers for XML payload
private static byte XML_MIME_STUFF[] =
("\r\nContent-Type: text/xml; charset=utf-8\r\n" +
"Content-Length: ").getBytes();
// Standard MIME headers for HTML payload
private static byte HTML_MIME_STUFF[] =
("\r\nContent-Type: text/html; charset=utf-8\r\n" +
"Content-Length: ").getBytes();
// Mime/Content separator
private static byte SEPARATOR[] = "\r\n\r\n".getBytes();
// Tiddly little response
// private static final String responseStr =
// "<html><head><title>SimpleAxisServer</title></head>" +
// "<body><h1>SimpleAxisServer</h1>" +
// Messages.getMessage("reachedServer00") +
// "</html>";
// private static byte cannedHTMLResponse[] = responseStr.getBytes();
// ASCII character mapping to lower case
private static final byte[] toLower = new byte[256];
static {
for (int i = 0; i < 256; i++) {
toLower[i] = (byte) i;
}
for (int lc = 'a'; lc <= 'z'; lc++) {
toLower[lc + 'A' - 'a'] = (byte) lc;
}
}
// buffer for IO
private static final int BUFSIZ = 4096;
// mime header for content length
private static final byte lenHeader[] = "content-length: ".getBytes();
private static final int lenLen = lenHeader.length;
// mime header for content type
private static final byte typeHeader[] = (HTTPConstants.HEADER_CONTENT_TYPE.toLowerCase() + ": ").getBytes();
private static final int typeLen = typeHeader.length;
// mime header for content location
private static final byte locationHeader[] = (HTTPConstants.HEADER_CONTENT_LOCATION.toLowerCase() + ": ").getBytes();
private static final int locationLen = locationHeader.length;
// mime header for soap action
private static final byte actionHeader[] = "soapaction: ".getBytes();
private static final int actionLen = actionHeader.length;
// mime header for cookie
private static final byte cookieHeader[] = "cookie: ".getBytes();
private static final int cookieLen = cookieHeader.length;
// mime header for cookie2
private static final byte cookie2Header[] = "cookie2: ".getBytes();
private static final int cookie2Len = cookie2Header.length;
// HTTP header for authentication
private static final byte authHeader[] = "authorization: ".getBytes();
private static final int authLen = authHeader.length;
// mime header for GET
private static final byte getHeader[] = "GET".getBytes();
// mime header for POST
private static final byte postHeader[] = "POST".getBytes();
// header ender
private static final byte headerEnder[] = ": ".getBytes();
// "Basic" auth string
private static final byte basicAuth[] = "basic ".getBytes();
public SimpleAxisWorker(SimpleAxisServer server, Socket socket) {
this.server = server;
this.socket = socket;
}
/**
* Run method
*/
public void run() {
try {
execute();
} finally {
SimpleAxisServer.getPool().workerDone(this, false);
}
}
/**
* The main workhorse method.
*/
public void execute () {
byte buf[] = new byte[BUFSIZ];
// create an Axis server
AxisServer engine = server.getAxisServer();
// create and initialize a message context
MessageContext msgContext = new MessageContext(engine);
Message requestMsg = null;
// Reusuable, buffered, content length controlled, InputStream
NonBlockingBufferedInputStream is =
new NonBlockingBufferedInputStream();
// buffers for the headers we care about
StringBuffer soapAction = new StringBuffer();
StringBuffer httpRequest = new StringBuffer();
StringBuffer fileName = new StringBuffer();
StringBuffer cookie = new StringBuffer();
StringBuffer cookie2 = new StringBuffer();
StringBuffer authInfo = new StringBuffer();
StringBuffer contentType = new StringBuffer();
StringBuffer contentLocation = new StringBuffer();
Message responseMsg = null;
// prepare request (do as much as possible while waiting for the
// next connection). Note the next two statements are commented
// out. Uncomment them if you experience any problems with not
// resetting state between requests:
// msgContext = new MessageContext();
// requestMsg = new Message("", "String");
//msgContext.setProperty("transport", "HTTPTransport");
msgContext.setTransportName(transportName);
responseMsg = null;
try {
// assume the best
byte[] status = OK;
// assume we're not getting WSDL
boolean doWsdl = false;
// cookie for this session, if any
String cooky = null;
String methodName = null;
try {
// wipe cookies if we're doing sessions
if (server.isSessionUsed()) {
cookie.delete(0, cookie.length());
cookie2.delete(0, cookie2.length());
}
authInfo.delete(0, authInfo.length());
// read headers
is.setInputStream(socket.getInputStream());
// parse all headers into hashtable
MimeHeaders requestHeaders = new MimeHeaders();
int contentLength = parseHeaders(is, buf, contentType,
contentLocation, soapAction,
httpRequest, fileName,
cookie, cookie2, authInfo, requestHeaders);
is.setContentLength(contentLength);
int paramIdx = fileName.toString().indexOf('?');
if (paramIdx != -1) {
// Got params
String params = fileName.substring(paramIdx + 1);
fileName.setLength(paramIdx);
log.debug(Messages.getMessage("filename00",
fileName.toString()));
log.debug(Messages.getMessage("params00",
params));
if ("wsdl".equalsIgnoreCase(params))
doWsdl = true;
if (params.startsWith("method=")) {
methodName = params.substring(7);
}
}
// Real and relative paths are the same for the
// SimpleAxisServer
msgContext.setProperty(Constants.MC_REALPATH,
fileName.toString());
msgContext.setProperty(Constants.MC_RELATIVE_PATH,
fileName.toString());
msgContext.setProperty(Constants.MC_JWS_CLASSDIR,
"jwsClasses");
msgContext.setProperty(Constants.MC_HOME_DIR, ".");
// !!! Fix string concatenation
String url = "http://" + getLocalHost() + ":" +
server.getServerSocket().getLocalPort() + "/" +
fileName.toString();
msgContext.setProperty(MessageContext.TRANS_URL, url);
String filePart = fileName.toString();
if (filePart.startsWith("axis/services/")) {
String servicePart = filePart.substring(14);
int separator = servicePart.indexOf('/');
if (separator > -1) {
msgContext.setProperty("objectID",
servicePart.substring(separator + 1));
servicePart = servicePart.substring(0, separator);
}
msgContext.setTargetService(servicePart);
}
if (authInfo.length() > 0) {
// Process authentication info
//authInfo = new StringBuffer("dXNlcjE6cGFzczE=");
byte[] decoded = Base64.decode(authInfo.toString());
StringBuffer userBuf = new StringBuffer();
StringBuffer pwBuf = new StringBuffer();
StringBuffer authBuf = userBuf;
for (int i = 0; i < decoded.length; i++) {
if ((char) (decoded[i] & 0x7f) == ':') {
authBuf = pwBuf;
continue;
}
authBuf.append((char) (decoded[i] & 0x7f));
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("user00",
userBuf.toString()));
}
msgContext.setUsername(userBuf.toString());
msgContext.setPassword(pwBuf.toString());
}
// if get, then return simpleton document as response
if (httpRequest.toString().equals("GET")) {
OutputStream out = socket.getOutputStream();
out.write(HTTP);
if(fileName.length()==0) {
out.write("301 Redirect\nLocation: /axis/\n\n".getBytes());
out.flush();
return;
}
out.write(status);
if (methodName != null) {
String body =
"<" + methodName + ">" +
// args +
"</" + methodName + ">";
String msgtxt =
"<SOAP-ENV:Envelope" +
" xmlns:SOAP-ENV=\"" + Constants.URI_SOAP12_ENV + "\">" +
"<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
ByteArrayInputStream istream =
new ByteArrayInputStream(msgtxt.getBytes());
requestMsg = new Message(istream);
} else if (doWsdl) {
engine.generateWSDL(msgContext);
Document doc = (Document) msgContext.getProperty("WSDL");
if (doc != null) {
XMLUtils.normalize(doc.getDocumentElement());
String response = XMLUtils.PrettyDocumentToString(doc);
byte[] respBytes = response.getBytes();
out.write(XML_MIME_STUFF);
putInt(buf, out, respBytes.length);
out.write(SEPARATOR);
out.write(respBytes);
out.flush();
return;
}
} else {
StringBuffer sb = new StringBuffer();
sb.append("<h2>And now... Some Services</h2>\n");
Iterator i = engine.getConfig().getDeployedServices();
sb.append("<ul>\n");
while (i.hasNext()) {
ServiceDesc sd = (ServiceDesc)i.next();
sb.append("<li>\n");
sb.append(sd.getName());
sb.append(" <a href=\"services/");
sb.append(sd.getName());
sb.append("?wsdl\"><i>(wsdl)</i></a></li>\n");
ArrayList operations = sd.getOperations();
if (!operations.isEmpty()) {
sb.append("<ul>\n");
for (Iterator it = operations.iterator(); it.hasNext();) {
OperationDesc desc = (OperationDesc) it.next();
sb.append("<li>" + desc.getName());
}
sb.append("</ul>\n");
}
}
sb.append("</ul>\n");
byte [] bytes = sb.toString().getBytes();
out.write(HTML_MIME_STUFF);
putInt(buf, out, bytes.length);
out.write(SEPARATOR);
out.write(bytes);
out.flush();
return;
}
} else {
// this may be "" if either SOAPAction: "" or if no SOAPAction at all.
// for now, do not complain if no SOAPAction at all
String soapActionString = soapAction.toString();
if (soapActionString != null) {
msgContext.setUseSOAPAction(true);
msgContext.setSOAPActionURI(soapActionString);
}
requestMsg = new Message(is,
false,
contentType.toString(),
contentLocation.toString()
);
}
// Transfer HTTP headers to MIME headers for request message.
MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
for (Iterator i = requestHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader requestHeader = (MimeHeader) i.next();
requestMimeHeaders.addHeader(requestHeader.getName(), requestHeader.getValue());
}
msgContext.setRequestMessage(requestMsg);
// put character encoding of request to message context
// in order to reuse it during the whole process.
String requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
if (requestEncoding != null) {
msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
}
// set up session, if any
if (server.isSessionUsed()) {
// did we get a cookie?
if (cookie.length() > 0) {
cooky = cookie.toString().trim();
} else if (cookie2.length() > 0) {
cooky = cookie2.toString().trim();
}
// if cooky is null, cook up a cooky
if (cooky == null) {
// fake one up!
// make it be an arbitrarily increasing number
// (no this is not thread safe because ++ isn't atomic)
int i = SimpleAxisServer.sessionIndex++;
cooky = "" + i;
}
msgContext.setSession(server.createSession(cooky));
}
// invoke the Axis engine
engine.invoke(msgContext);
// Retrieve the response from Axis
responseMsg = msgContext.getResponseMessage();
if (responseMsg == null) {
status = NOCONTENT;
}
} catch (Exception e) {
AxisFault af;
if (e instanceof AxisFault) {
af = (AxisFault) e;
log.debug(Messages.getMessage("serverFault00"), af);
QName faultCode = af.getFaultCode();
if (Constants.FAULT_SOAP12_SENDER.equals(faultCode)) {
status = SENDER;
} else if ("Server.Unauthorized".equals(af.getFaultCode().getLocalPart())) {
status = UNAUTH; // SC_UNAUTHORIZED
} else {
status = ISE; // SC_INTERNAL_SERVER_ERROR
}
} else {
status = ISE; // SC_INTERNAL_SERVER_ERROR
af = AxisFault.makeFault(e);
}
// There may be headers we want to preserve in the
// response message - so if it's there, just add the
// FaultElement to it. Otherwise, make a new one.
responseMsg = msgContext.getResponseMessage();
if (responseMsg == null) {
responseMsg = new Message(af);
responseMsg.setMessageContext(msgContext);
} else {
try {
SOAPEnvelope env = responseMsg.getSOAPEnvelope();
env.clearBody();
env.addBodyElement(new SOAPFault((AxisFault) e));
} catch (AxisFault fault) {
// Should never reach here!
}
}
}
// synchronize the character encoding of request and response
String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
if (responseEncoding != null && responseMsg != null) {
responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
}
// Send it on its way...
OutputStream out = socket.getOutputStream();
out.write(HTTP);
out.write(status);
if (responseMsg != null) {
if (server.isSessionUsed() && null != cooky &&
0 != cooky.trim().length()) {
// write cookie headers, if any
// don't sweat efficiency *too* badly
// optimize at will
StringBuffer cookieOut = new StringBuffer();
cookieOut.append("\r\nSet-Cookie: ")
.append(cooky)
.append("\r\nSet-Cookie2: ")
.append(cooky);
// OH, THE HUMILITY! yes this is inefficient.
out.write(cookieOut.toString().getBytes());
}
//out.write(XML_MIME_STUFF);
out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_TYPE + ": " + responseMsg.getContentType(msgContext.getSOAPConstants())).getBytes());
// Writing the length causes the entire message to be decoded twice.
//out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_LENGTH + ": " + responseMsg.getContentLength()).getBytes());
// putInt(out, response.length);
// Transfer MIME headers to HTTP headers for response message.
for (Iterator i = responseMsg.getMimeHeaders().getAllHeaders(); i.hasNext(); ) {
MimeHeader responseHeader = (MimeHeader) i.next();
out.write('\r');
out.write('\n');
out.write(responseHeader.getName().getBytes());
out.write(headerEnder);
out.write(responseHeader.getValue().getBytes());
}
out.write(SEPARATOR);
responseMsg.writeTo(out);
}
// out.write(response);
out.flush();
} catch (Exception e) {
log.info(Messages.getMessage("exception00"), e);
} finally {
try {
if (socket != null) socket.close();
} catch (Exception e) {
}
}
if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
// why then, quit!
try {
server.stop();
} catch (Exception e) {
}
}
}
protected void invokeMethodFromGet(String methodName, String args) throws Exception {
}
/**
* Read all mime headers, returning the value of Content-Length and
* SOAPAction.
* @param is InputStream to read from
* @param contentType The content type.
* @param contentLocation The content location
* @param soapAction StringBuffer to return the soapAction into
* @param httpRequest StringBuffer for GET / POST
* @param cookie first cookie header (if doSessions)
* @param cookie2 second cookie header (if doSessions)
* @param headers HTTP headers to transfer to MIME headers
* @return Content-Length
*/
private int parseHeaders(NonBlockingBufferedInputStream is,
byte buf[],
StringBuffer contentType,
StringBuffer contentLocation,
StringBuffer soapAction,
StringBuffer httpRequest,
StringBuffer fileName,
StringBuffer cookie,
StringBuffer cookie2,
StringBuffer authInfo,
MimeHeaders headers)
throws java.io.IOException {
int n;
int len = 0;
// parse first line as GET or POST
n = this.readLine(is, buf, 0, buf.length);
if (n < 0) {
// nothing!
throw new java.io.IOException(Messages.getMessage("unexpectedEOS00"));
}
// which does it begin with?
httpRequest.delete(0, httpRequest.length());
fileName.delete(0, fileName.length());
contentType.delete(0, contentType.length());
contentLocation.delete(0, contentLocation.length());
if (buf[0] == getHeader[0]) {
httpRequest.append("GET");
for (int i = 0; i < n - 5; i++) {
char c = (char) (buf[i + 5] & 0x7f);
if (c == ' ')
break;
fileName.append(c);
}
log.debug(Messages.getMessage("filename01", "SimpleAxisServer", fileName.toString()));
return 0;
} else if (buf[0] == postHeader[0]) {
httpRequest.append("POST");
for (int i = 0; i < n - 6; i++) {
char c = (char) (buf[i + 6] & 0x7f);
if (c == ' ')
break;
fileName.append(c);
}
log.debug(Messages.getMessage("filename01", "SimpleAxisServer", fileName.toString()));
} else {
throw new java.io.IOException(Messages.getMessage("badRequest00"));
}
while ((n = readLine(is, buf, 0, buf.length)) > 0) {
if ((n <= 2) && (buf[0] == '\n' || buf[0] == '\r') && (len > 0)) break;
// RobJ gutted the previous logic; it was too hard to extend for more headers.
// Now, all it does is search forwards for ": " in the buf,
// then do a length / byte compare.
// Hopefully this is still somewhat efficient (Sam is watching!).
// First, search forwards for ": "
int endHeaderIndex = 0;
while (endHeaderIndex < n && toLower[buf[endHeaderIndex]] != headerEnder[0]) {
endHeaderIndex++;
}
endHeaderIndex += 2;
// endHeaderIndex now points _just past_ the ": ", and is
// comparable to the various lenLen, actionLen, etc. values
// convenience; i gets pre-incremented, so initialize it to one less
int i = endHeaderIndex - 1;
// which header did we find?
if (endHeaderIndex == lenLen && matches(buf, lenHeader)) {
// parse content length
while ((++i < n) && (buf[i] >= '0') && (buf[i] <= '9')) {
len = (len * 10) + (buf[i] - '0');
}
headers.addHeader(HTTPConstants.HEADER_CONTENT_LENGTH, String.valueOf(len));
} else if (endHeaderIndex == actionLen
&& matches(buf, actionHeader)) {
soapAction.delete(0, soapAction.length());
// skip initial '"'
i++;
while ((++i < n) && (buf[i] != '"')) {
soapAction.append((char) (buf[i] & 0x7f));
}
headers.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + soapAction.toString() + "\"");
} else if (server.isSessionUsed() && endHeaderIndex == cookieLen
&& matches(buf, cookieHeader)) {
// keep everything up to first ;
while ((++i < n) && (buf[i] != ';') && (buf[i] != '\r') && (buf[i] != '\n')) {
cookie.append((char) (buf[i] & 0x7f));
}
headers.addHeader("Set-Cookie", cookie.toString());
} else if (server.isSessionUsed() && endHeaderIndex == cookie2Len
&& matches(buf, cookie2Header)) {
// keep everything up to first ;
while ((++i < n) && (buf[i] != ';') && (buf[i] != '\r') && (buf[i] != '\n')) {
cookie2.append((char) (buf[i] & 0x7f));
}
headers.addHeader("Set-Cookie2", cookie.toString());
} else if (endHeaderIndex == authLen && matches(buf, authHeader)) {
if (matches(buf, endHeaderIndex, basicAuth)) {
i += basicAuth.length;
while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
if (buf[i] == ' ') continue;
authInfo.append((char) (buf[i] & 0x7f));
}
headers.addHeader(HTTPConstants.HEADER_AUTHORIZATION, new String(basicAuth) + authInfo.toString());
} else {
throw new java.io.IOException(
Messages.getMessage("badAuth00"));
}
} else if (endHeaderIndex == locationLen && matches(buf, locationHeader)) {
while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
if (buf[i] == ' ') continue;
contentLocation.append((char) (buf[i] & 0x7f));
}
headers.addHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation.toString());
} else if (endHeaderIndex == typeLen && matches(buf, typeHeader)) {
while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
if (buf[i] == ' ') continue;
contentType.append((char) (buf[i] & 0x7f));
}
headers.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentLocation.toString());
} else {
String customHeaderName = new String(buf, 0, endHeaderIndex - 2);
StringBuffer customHeaderValue = new StringBuffer();
while (++i < n && (buf[i] != '\r') && (buf[i] != '\n')) {
if (buf[i] == ' ') continue;
customHeaderValue.append((char) (buf[i] & 0x7f));
}
headers.addHeader(customHeaderName, customHeaderValue.toString());
}
}
return len;
}
/**
* does tolower[buf] match the target byte array, up to the target's length?
*/
public boolean matches(byte[] buf, byte[] target) {
for (int i = 0; i < target.length; i++) {
if (toLower[buf[i]] != target[i]) {
return false;
}
}
return true;
}
/**
* Case-insensitive match of a target byte [] to a source byte [],
* starting from a particular offset into the source.
*/
public boolean matches(byte[] buf, int bufIdx, byte[] target) {
for (int i = 0; i < target.length; i++) {
if (toLower[buf[bufIdx + i]] != target[i]) {
return false;
}
}
return true;
}
/**
* output an integer into the output stream
* @param out OutputStream to be written to
* @param value Integer value to be written.
*/
private void putInt(byte buf[], OutputStream out, int value)
throws java.io.IOException {
int len = 0;
int offset = buf.length;
// negative numbers
if (value < 0) {
buf[--offset] = (byte) '-';
value = -value;
len++;
}
// zero
if (value == 0) {
buf[--offset] = (byte) '0';
len++;
}
// positive numbers
while (value > 0) {
buf[--offset] = (byte) (value % 10 + '0');
value = value / 10;
len++;
}
// write the result
out.write(buf, offset, len);
}
/**
* Read a single line from the input stream
* @param is inputstream to read from
* @param b byte array to read into
* @param off starting offset into the byte array
* @param len maximum number of bytes to read
*/
private int readLine(NonBlockingBufferedInputStream is, byte[] b, int off, int len)
throws java.io.IOException {
int count = 0, c;
while ((c = is.read()) != -1) {
if (c != '\n' && c != '\r') {
b[off++] = (byte) c;
count++;
}
if (count == len) break;
if ('\n' == c) {
int peek = is.peek(); //If the next line begins with tab or space then this is a continuation.
if (peek != ' ' && peek != '\t') break;
}
}
return count > 0 ? count : -1;
}
/**
* One method for all host name lookups.
*/
public static String getLocalHost() {
return NetworkUtils.getLocalHostname();
}
}
| 6,926 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/enum/Use.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.enum;
/**
* Simple wrapper around org.apache.axis.constants.Use
* @author dims@yahoo.com
* @deprecated please use org.apache.axis.constants.Scope
*/
public class Use extends org.apache.axis.constants.Use {
};
| 6,927 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/enum/Style.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.enum;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import javax.xml.namespace.QName;
/**
* Simple wrapper around org.apache.axis.constants.Style
* @author dims@yahoo.com
* @deprecated please use org.apache.axis.constants.Scope
*/
public class Style extends org.apache.axis.constants.Style {
}
| 6,928 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/enum/Scope.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.enum;
/**
* Simple wrapper around org.apache.axis.constants.Scope
* @author dims@yahoo.com
* @deprecated please use org.apache.axis.constants.Scope
*/
public class Scope extends org.apache.axis.constants.Scope {
}
| 6,929 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/encoding/DefaultSOAP12TypeMappingImpl.java | package org.apache.axis.encoding;
/**
* @author James M Snell <jasnell@us.ibm.com>
* @deprecated Please use DefaultSOAPEncodingTypeMappingImpl.java
* @see org.apache.axis.encoding.DefaultSOAPEncodingTypeMappingImpl
*/
public class DefaultSOAP12TypeMappingImpl
extends DefaultSOAPEncodingTypeMappingImpl {
public DefaultSOAP12TypeMappingImpl() {
}
}
| 6,930 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/components | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/components/threadpool/ThreadPool.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.threadpool;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.i18n.Messages;
import org.apache.commons.logging.Log;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
/**
* @author James M Snell (jasnell@us.ibm.com)
*/
public class ThreadPool {
protected static Log log =
LogFactory.getLog(ThreadPool.class.getName());
public static final int DEFAULT_MAX_THREADS = 100;
protected Map threads = new Hashtable();
protected long threadcount;
public boolean _shutdown;
private int maxPoolSize = DEFAULT_MAX_THREADS;
public ThreadPool() {
}
public ThreadPool(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public void cleanup()
throws InterruptedException {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::cleanup");
}
if (!isShutdown()) {
safeShutdown();
awaitShutdown();
}
synchronized(this) {
threads.clear();
_shutdown = false;
}
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::cleanup");
}
}
/**
* Returns true if all workers have been shutdown
*/
public boolean isShutdown() {
synchronized (this) {
return _shutdown && threadcount == 0;
}
}
/**
* Returns true if all workers are in the process of shutting down
*/
public boolean isShuttingDown() {
synchronized (this) {
return _shutdown;
}
}
/**
* Returns the total number of currently active workers
*/
public long getWorkerCount() {
synchronized (this) {
return threadcount;
}
}
/**
* Adds a new worker to the pool
*/
public void addWorker(
Runnable worker) {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::addWorker");
}
if (_shutdown || threadcount == maxPoolSize) {
throw new IllegalStateException(Messages.getMessage("illegalStateException00"));
}
Thread thread = new Thread(worker);
threads.put(worker, thread);
threadcount++;
thread.start();
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::addWorker");
}
}
/**
* Forcefully interrupt all workers
*/
public void interruptAll() {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::interruptAll");
}
synchronized (threads) {
for (Iterator i = threads.values().iterator(); i.hasNext();) {
Thread t = (Thread) i.next();
t.interrupt();
}
}
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::interruptAll");
}
}
/**
* Forcefully shutdown the pool
*/
public void shutdown() {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::shutdown");
}
synchronized (this) {
_shutdown = true;
}
interruptAll();
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::shutdown");
}
}
/**
* Forcefully shutdown the pool
*/
public void safeShutdown() {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::safeShutdown");
}
synchronized (this) {
_shutdown = true;
}
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::safeShutdown");
}
}
/**
* Await shutdown of the worker
*/
public synchronized void awaitShutdown()
throws InterruptedException {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::awaitShutdown");
}
if (!_shutdown)
throw new IllegalStateException(Messages.getMessage("illegalStateException00"));
while (threadcount > 0)
wait();
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::awaitShutdown");
}
}
/**
* Await shutdown of the worker
*/
public synchronized boolean awaitShutdown(long timeout)
throws InterruptedException {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::awaitShutdown");
}
if (!_shutdown)
throw new IllegalStateException(Messages.getMessage("illegalStateException00"));
if (threadcount == 0) {
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::awaitShutdown");
}
return true;
}
long waittime = timeout;
if (waittime <= 0) {
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::awaitShutdown");
}
return false;
}
for (; ;) {
wait(waittime);
if (threadcount == 0) {
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::awaitShutdown");
}
return true;
}
waittime = timeout - System.currentTimeMillis();
if (waittime <= 0) {
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::awaitShutdown");
}
return false;
}
}
}
/**
* Used by MessageWorkers to notify the pool that it is done
*/
public void workerDone(
Runnable worker,
boolean restart) {
if (log.isDebugEnabled()) {
log.debug("Enter: ThreadPool::workerDone");
}
synchronized(this) {
threads.remove(worker);
if (--threadcount == 0 && _shutdown) {
notifyAll();
}
if (!_shutdown && restart) {
addWorker(worker);
}
}
if (log.isDebugEnabled()) {
log.debug("Exit: ThreadPool::workerDone");
}
}
}
| 6,931 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/collections/LRUMap.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.collections;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
/**
* <p>
* An implementation of a Map which has a maximum size and uses a Least Recently Used
* algorithm to remove items from the Map when the maximum size is reached and new items are added.
* </p>
*
* <p>
* A synchronized version can be obtained with:
* <code>Collections.synchronizedMap( theMapToSynchronize )</code>
* If it will be accessed by multiple threads, you _must_ synchronize access
* to this Map. Even concurrent get(Object) operations produce indeterminate
* behaviour.
* </p>
*
* <p>
* Unlike the Collections 1.0 version, this version of LRUMap does use a true
* LRU algorithm. The keys for all gets and puts are moved to the front of
* the list. LRUMap is now a subclass of SequencedHashMap, and the "LRU"
* key is now equivalent to LRUMap.getFirst().
* </p>
*
* @since Commons Collections 1.0
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @author <a href="mailto:morgand@apache.org">Morgan Delagrange</a>
*/
public class LRUMap extends SequencedHashMap implements Externalizable {
private int maximumSize = 0;
/**
* Default constructor, primarily for the purpose of
* de-externalization. This constructors sets a default
* LRU limit of 100 keys, but this value may be overridden
* internally as a result of de-externalization.
*/
public LRUMap() {
this( 100 );
}
/**
* Create a new LRUMap with a maximum capacity of <i>i</i>.
* Once <i>i</i> capacity is achieved, subsequent gets
* and puts will push keys out of the map. See .
*
* @param i Maximum capacity of the LRUMap
*/
public LRUMap(int i) {
super( i );
maximumSize = i;
}
/**
* <p>Get the value for a key from the Map. The key
* will be promoted to the Most Recently Used position.
* Note that get(Object) operations will modify
* the underlying Collection. Calling get(Object)
* inside of an iteration over keys, values, etc. is
* currently unsupported.</p>
*
* @param key Key to retrieve
* @return Returns the value. Returns null if the key has a
* null value <i>or</i> if the key has no value.
*/
public Object get(Object key) {
if(!containsKey(key)) return null;
Object value = remove(key);
super.put(key,value);
return value;
}
/**
* <p>Removes the key and its Object from the Map.</p>
*
* <p>(Note: this may result in the "Least Recently Used"
* object being removed from the Map. In that case,
* the removeLRU() method is called. See javadoc for
* removeLRU() for more details.)</p>
*
* @param key Key of the Object to add.
* @param value Object to add
* @return Former value of the key
*/
public Object put( Object key, Object value ) {
int mapSize = size();
Object retval = null;
if ( mapSize >= maximumSize ) {
// don't retire LRU if you are just
// updating an existing key
if (!containsKey(key)) {
// lets retire the least recently used item in the cache
removeLRU();
}
}
retval = super.put(key,value);
return retval;
}
/**
* This method is used internally by the class for
* finding and removing the LRU Object.
*/
protected void removeLRU() {
Object key = getFirstKey();
// be sure to call super.get(key), or you're likely to
// get infinite promotion recursion
Object value = super.get(key);
remove(key);
processRemovedLRU(key,value);
}
/**
* Subclasses of LRUMap may hook into this method to
* provide specialized actions whenever an Object is
* automatically removed from the cache. By default,
* this method does nothing.
*
* @param key key that was removed
* @param value value of that key (can be null)
*/
protected void processRemovedLRU(Object key, Object value) {
}
// Externalizable interface
//-------------------------------------------------------------------------
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
maximumSize = in.readInt();
int size = in.readInt();
for( int i = 0; i < size; i++ ) {
Object key = in.readObject();
Object value = in.readObject();
put(key,value);
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
out.writeInt( maximumSize );
out.writeInt( size() );
for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) {
Object key = iterator.next();
out.writeObject( key );
// be sure to call super.get(key), or you're likely to
// get infinite promotion recursion
Object value = super.get( key );
out.writeObject( value );
}
}
// Properties
//-------------------------------------------------------------------------
/** Getter for property maximumSize.
* @return Value of property maximumSize.
*/
public int getMaximumSize() {
return maximumSize;
}
/** Setter for property maximumSize.
* @param maximumSize New value of property maximumSize.
*/
public void setMaximumSize(int maximumSize) {
this.maximumSize = maximumSize;
while (size() > maximumSize) {
removeLRU();
}
}
// add a serial version uid, so that if we change things in the future
// without changing the format, we can still deserialize properly.
private static final long serialVersionUID = 2197433140769957051L;
}
| 6,932 |
0 | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis | Create_ds/axis-axis1-java/axis-rt-compat/src/main/java/org/apache/axis/collections/SequencedHashMap.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.collections;
import org.apache.axis.i18n.Messages;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A map of objects whose mapping entries are sequenced based on the order in
* which they were added. This data structure has fast <i>O(1)</i> search
* time, deletion time, and insertion time.
*
* <p>Although this map is sequenced, it cannot implement {@link
* java.util.List} because of incompatible interface definitions. The remove
* methods in List and Map have different return values (see: {@link
* java.util.List#remove(Object)} and {@link java.util.Map#remove(Object)}).
*
* <p>This class is not thread safe. When a thread safe implementation is
* required, use {@link Collections#synchronizedMap(Map)} as it is documented,
* or use explicit synchronization controls.
*
* @since Commons Collections 2.0
*
* @author <a href="mailto:mas@apache.org">Michael A. Smith</A>
* @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
* @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
* @author Stephen Colebourne
*/
public class SequencedHashMap implements Map, Cloneable, Externalizable {
/**
* {@link java.util.Map.Entry} that doubles as a node in the linked list
* of sequenced mappings.
**/
private static class Entry implements Map.Entry {
// Note: This class cannot easily be made clonable. While the actual
// implementation of a clone would be simple, defining the semantics is
// difficult. If a shallow clone is implemented, then entry.next.prev !=
// entry, which is unintuitive and probably breaks all sorts of assumptions
// in code that uses this implementation. If a deep clone is
// implementated, then what happens when the linked list is cyclical (as is
// the case with SequencedHashMap)? It's impossible to know in the clone
// when to stop cloning, and thus you end up in a recursive loop,
// continuously cloning the "next" in the list.
private final Object key;
private Object value;
// package private to allow the SequencedHashMap to access and manipulate
// them.
Entry next = null;
Entry prev = null;
public Entry(Object key, Object value) {
this.key = key;
this.value = value;
}
// per Map.Entry.getKey()
public Object getKey() {
return this.key;
}
// per Map.Entry.getValue()
public Object getValue() {
return this.value;
}
// per Map.Entry.setValue()
public Object setValue(Object value) {
Object oldValue = this.value;
this.value = value;
return oldValue;
}
public int hashCode() {
// implemented per api docs for Map.Entry.hashCode()
return ((getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()));
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Map.Entry))
return false;
Map.Entry other = (Map.Entry) obj;
// implemented per api docs for Map.Entry.equals(Object)
return (
(getKey() == null ? other.getKey() == null : getKey().equals(other.getKey()))
&& (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())));
}
public String toString() {
return "[" + getKey() + "=" + getValue() + "]";
}
}
/**
* Construct an empty sentinel used to hold the head (sentinel.next) and the
* tail (sentinel.prev) of the list. The sentinal has a <code>null</code>
* key and value.
**/
private static final Entry createSentinel() {
Entry s = new Entry(null, null);
s.prev = s;
s.next = s;
return s;
}
/**
* Sentinel used to hold the head and tail of the list of entries.
**/
private Entry sentinel;
/**
* Map of keys to entries
**/
private HashMap entries;
/**
* Holds the number of modifications that have occurred to the map,
* excluding modifications made through a collection view's iterator
* (e.g. entrySet().iterator().remove()). This is used to create a
* fail-fast behavior with the iterators.
**/
private transient long modCount = 0;
/**
* Construct a new sequenced hash map with default initial size and load
* factor.
**/
public SequencedHashMap() {
sentinel = createSentinel();
entries = new HashMap();
}
/**
* Construct a new sequenced hash map with the specified initial size and
* default load factor.
*
* @param initialSize the initial size for the hash table
*
* @see HashMap#HashMap(int)
**/
public SequencedHashMap(int initialSize) {
sentinel = createSentinel();
entries = new HashMap(initialSize);
}
/**
* Construct a new sequenced hash map with the specified initial size and
* load factor.
*
* @param initialSize the initial size for the hash table
*
* @param loadFactor the load factor for the hash table.
*
* @see HashMap#HashMap(int,float)
**/
public SequencedHashMap(int initialSize, float loadFactor) {
sentinel = createSentinel();
entries = new HashMap(initialSize, loadFactor);
}
/**
* Construct a new sequenced hash map and add all the elements in the
* specified map. The order in which the mappings in the specified map are
* added is defined by {@link #putAll(Map)}.
**/
public SequencedHashMap(Map m) {
this();
putAll(m);
}
/**
* Removes an internal entry from the linked list. This does not remove
* it from the underlying map.
**/
private void removeEntry(Entry entry) {
entry.next.prev = entry.prev;
entry.prev.next = entry.next;
}
/**
* Inserts a new internal entry to the tail of the linked list. This does
* not add the entry to the underlying map.
**/
private void insertEntry(Entry entry) {
entry.next = sentinel;
entry.prev = sentinel.prev;
sentinel.prev.next = entry;
sentinel.prev = entry;
}
// per Map.size()
/**
* Implements {@link Map#size()}.
*/
public int size() {
// use the underlying Map's size since size is not maintained here.
return entries.size();
}
/**
* Implements {@link Map#isEmpty()}.
*/
public boolean isEmpty() {
// for quick check whether the map is entry, we can check the linked list
// and see if there's anything in it.
return sentinel.next == sentinel;
}
/**
* Implements {@link Map#containsKey(Object)}.
*/
public boolean containsKey(Object key) {
// pass on to underlying map implementation
return entries.containsKey(key);
}
/**
* Implements {@link Map#containsValue(Object)}.
*/
public boolean containsValue(Object value) {
// unfortunately, we cannot just pass this call to the underlying map
// because we are mapping keys to entries, not keys to values. The
// underlying map doesn't have an efficient implementation anyway, so this
// isn't a big deal.
// do null comparison outside loop so we only need to do it once. This
// provides a tighter, more efficient loop at the expense of slight
// code duplication.
if (value == null) {
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
if (pos.getValue() == null)
return true;
}
} else {
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
if (value.equals(pos.getValue()))
return true;
}
}
return false;
}
/**
* Implements {@link Map#get(Object)}.
*/
public Object get(Object o) {
// find entry for the specified key object
Entry entry = (Entry) entries.get(o);
if (entry == null)
return null;
return entry.getValue();
}
/**
* Return the entry for the "oldest" mapping. That is, return the Map.Entry
* for the key-value pair that was first put into the map when compared to
* all the other pairings in the map. This behavior is equivalent to using
* <code>entrySet().iterator().next()</code>, but this method provides an
* optimized implementation.
*
* @return The first entry in the sequence, or <code>null</code> if the
* map is empty.
**/
public Map.Entry getFirst() {
// sentinel.next points to the "first" element of the sequence -- the head
// of the list, which is exactly the entry we need to return. We must test
// for an empty list though because we don't want to return the sentinel!
return (isEmpty()) ? null : sentinel.next;
}
/**
* Return the key for the "oldest" mapping. That is, return the key for the
* mapping that was first put into the map when compared to all the other
* objects in the map. This behavior is equivalent to using
* <code>getFirst().getKey()</code>, but this method provides a slightly
* optimized implementation.
*
* @return The first key in the sequence, or <code>null</code> if the
* map is empty.
**/
public Object getFirstKey() {
// sentinel.next points to the "first" element of the sequence -- the head
// of the list -- and the requisite key is returned from it. An empty list
// does not need to be tested. In cases where the list is empty,
// sentinel.next will point to the sentinel itself which has a null key,
// which is exactly what we would want to return if the list is empty (a
// nice convient way to avoid test for an empty list)
return sentinel.next.getKey();
}
/**
* Return the value for the "oldest" mapping. That is, return the value for
* the mapping that was first put into the map when compared to all the
* other objects in the map. This behavior is equivalent to using
* <code>getFirst().getValue()</code>, but this method provides a slightly
* optimized implementation.
*
* @return The first value in the sequence, or <code>null</code> if the
* map is empty.
**/
public Object getFirstValue() {
// sentinel.next points to the "first" element of the sequence -- the head
// of the list -- and the requisite value is returned from it. An empty
// list does not need to be tested. In cases where the list is empty,
// sentinel.next will point to the sentinel itself which has a null value,
// which is exactly what we would want to return if the list is empty (a
// nice convient way to avoid test for an empty list)
return sentinel.next.getValue();
}
/**
* Return the entry for the "newest" mapping. That is, return the Map.Entry
* for the key-value pair that was first put into the map when compared to
* all the other pairings in the map. The behavior is equivalent to:
*
* <pre>
* Object obj = null;
* Iterator iter = entrySet().iterator();
* while(iter.hasNext()) {
* obj = iter.next();
* }
* return (Map.Entry)obj;
* </pre>
*
* However, the implementation of this method ensures an O(1) lookup of the
* last key rather than O(n).
*
* @return The last entry in the sequence, or <code>null</code> if the map
* is empty.
**/
public Map.Entry getLast() {
// sentinel.prev points to the "last" element of the sequence -- the tail
// of the list, which is exactly the entry we need to return. We must test
// for an empty list though because we don't want to return the sentinel!
return (isEmpty()) ? null : sentinel.prev;
}
/**
* Return the key for the "newest" mapping. That is, return the key for the
* mapping that was last put into the map when compared to all the other
* objects in the map. This behavior is equivalent to using
* <code>getLast().getKey()</code>, but this method provides a slightly
* optimized implementation.
*
* @return The last key in the sequence, or <code>null</code> if the map is
* empty.
**/
public Object getLastKey() {
// sentinel.prev points to the "last" element of the sequence -- the tail
// of the list -- and the requisite key is returned from it. An empty list
// does not need to be tested. In cases where the list is empty,
// sentinel.prev will point to the sentinel itself which has a null key,
// which is exactly what we would want to return if the list is empty (a
// nice convient way to avoid test for an empty list)
return sentinel.prev.getKey();
}
/**
* Return the value for the "newest" mapping. That is, return the value for
* the mapping that was last put into the map when compared to all the other
* objects in the map. This behavior is equivalent to using
* <code>getLast().getValue()</code>, but this method provides a slightly
* optimized implementation.
*
* @return The last value in the sequence, or <code>null</code> if the map
* is empty.
**/
public Object getLastValue() {
// sentinel.prev points to the "last" element of the sequence -- the tail
// of the list -- and the requisite value is returned from it. An empty
// list does not need to be tested. In cases where the list is empty,
// sentinel.prev will point to the sentinel itself which has a null value,
// which is exactly what we would want to return if the list is empty (a
// nice convient way to avoid test for an empty list)
return sentinel.prev.getValue();
}
/**
* Implements {@link Map#put(Object, Object)}.
*/
public Object put(Object key, Object value) {
modCount++;
Object oldValue = null;
// lookup the entry for the specified key
Entry e = (Entry) entries.get(key);
// check to see if it already exists
if (e != null) {
// remove from list so the entry gets "moved" to the end of list
removeEntry(e);
// update value in map
oldValue = e.setValue(value);
// Note: We do not update the key here because its unnecessary. We only
// do comparisons using equals(Object) and we know the specified key and
// that in the map are equal in that sense. This may cause a problem if
// someone does not implement their hashCode() and/or equals(Object)
// method properly and then use it as a key in this map.
} else {
// add new entry
e = new Entry(key, value);
entries.put(key, e);
}
// assert(entry in map, but not list)
// add to list
insertEntry(e);
return oldValue;
}
/**
* Implements {@link Map#remove(Object)}.
*/
public Object remove(Object key) {
Entry e = removeImpl(key);
return (e == null) ? null : e.getValue();
}
/**
* Fully remove an entry from the map, returning the old entry or null if
* there was no such entry with the specified key.
**/
private Entry removeImpl(Object key) {
Entry e = (Entry) entries.remove(key);
if (e == null)
return null;
modCount++;
removeEntry(e);
return e;
}
/**
* Adds all the mappings in the specified map to this map, replacing any
* mappings that already exist (as per {@link Map#putAll(Map)}). The order
* in which the entries are added is determined by the iterator returned
* from {@link Map#entrySet()} for the specified map.
*
* @param t the mappings that should be added to this map.
*
* @throws NullPointerException if <code>t</code> is <code>null</code>
**/
public void putAll(Map t) {
Iterator iter = t.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
put(entry.getKey(), entry.getValue());
}
}
/**
* Implements {@link Map#clear()}.
*/
public void clear() {
modCount++;
// remove all from the underlying map
entries.clear();
// and the list
sentinel.next = sentinel;
sentinel.prev = sentinel;
}
/**
* Implements {@link Map#equals(Object)}.
*/
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Map))
return false;
return entrySet().equals(((Map) obj).entrySet());
}
/**
* Implements {@link Map#hashCode()}.
*/
public int hashCode() {
return entrySet().hashCode();
}
/**
* Provides a string representation of the entries within the map. The
* format of the returned string may change with different releases, so this
* method is suitable for debugging purposes only. If a specific format is
* required, use {@link #entrySet()}.{@link Set#iterator() iterator()} and
* iterate over the entries in the map formatting them as appropriate.
**/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append('[');
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
buf.append(pos.getKey());
buf.append('=');
buf.append(pos.getValue());
if (pos.next != sentinel) {
buf.append(',');
}
}
buf.append(']');
return buf.toString();
}
/**
* Implements {@link Map#keySet()}.
*/
public Set keySet() {
return new AbstractSet() {
// required impls
public Iterator iterator() {
return new OrderedIterator(KEY);
}
public boolean remove(Object o) {
Entry e = SequencedHashMap.this.removeImpl(o);
return (e != null);
}
// more efficient impls than abstract set
public void clear() {
SequencedHashMap.this.clear();
}
public int size() {
return SequencedHashMap.this.size();
}
public boolean isEmpty() {
return SequencedHashMap.this.isEmpty();
}
public boolean contains(Object o) {
return SequencedHashMap.this.containsKey(o);
}
};
}
/**
* Implements {@link Map#values()}.
*/
public Collection values() {
return new AbstractCollection() {
// required impl
public Iterator iterator() {
return new OrderedIterator(VALUE);
}
public boolean remove(Object value) {
// do null comparison outside loop so we only need to do it once. This
// provides a tighter, more efficient loop at the expense of slight
// code duplication.
if (value == null) {
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
if (pos.getValue() == null) {
SequencedHashMap.this.removeImpl(pos.getKey());
return true;
}
}
} else {
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
if (value.equals(pos.getValue())) {
SequencedHashMap.this.removeImpl(pos.getKey());
return true;
}
}
}
return false;
}
// more efficient impls than abstract collection
public void clear() {
SequencedHashMap.this.clear();
}
public int size() {
return SequencedHashMap.this.size();
}
public boolean isEmpty() {
return SequencedHashMap.this.isEmpty();
}
public boolean contains(Object o) {
return SequencedHashMap.this.containsValue(o);
}
};
}
/**
* Implements {@link Map#entrySet()}.
*/
public Set entrySet() {
return new AbstractSet() {
// helper
private Entry findEntry(Object o) {
if (o == null)
return null;
if (!(o instanceof Map.Entry))
return null;
Map.Entry e = (Map.Entry) o;
Entry entry = (Entry) entries.get(e.getKey());
if (entry != null && entry.equals(e))
return entry;
else
return null;
}
// required impl
public Iterator iterator() {
return new OrderedIterator(ENTRY);
}
public boolean remove(Object o) {
Entry e = findEntry(o);
if (e == null)
return false;
return SequencedHashMap.this.removeImpl(e.getKey()) != null;
}
// more efficient impls than abstract collection
public void clear() {
SequencedHashMap.this.clear();
}
public int size() {
return SequencedHashMap.this.size();
}
public boolean isEmpty() {
return SequencedHashMap.this.isEmpty();
}
public boolean contains(Object o) {
return findEntry(o) != null;
}
};
}
// constants to define what the iterator should return on "next"
private static final int KEY = 0;
private static final int VALUE = 1;
private static final int ENTRY = 2;
private static final int REMOVED_MASK = 0x80000000;
private class OrderedIterator implements Iterator {
/**
* Holds the type that should be returned from the iterator. The value
* should be either {@link #KEY}, {@link #VALUE}, or {@link #ENTRY}. To
* save a tiny bit of memory, this field is also used as a marker for when
* remove has been called on the current object to prevent a second remove
* on the same element. Essientially, if this value is negative (i.e. the
* bit specified by {@link #REMOVED_MASK} is set), the current position
* has been removed. If positive, remove can still be called.
**/
private int returnType;
/**
* Holds the "current" position in the iterator. When pos.next is the
* sentinel, we've reached the end of the list.
**/
private Entry pos = sentinel;
/**
* Holds the expected modification count. If the actual modification
* count of the map differs from this value, then a concurrent
* modification has occurred.
**/
private transient long expectedModCount = modCount;
/**
* Construct an iterator over the sequenced elements in the order in which
* they were added. The {@link #next()} method returns the type specified
* by <code>returnType</code> which must be either {@link #KEY}, {@link
* #VALUE}, or {@link #ENTRY}.
**/
public OrderedIterator(int returnType) {
// Set the "removed" bit so that the iterator starts in a state where
// "next" must be called before "remove" will succeed.
this.returnType = returnType | REMOVED_MASK;
}
/**
* Returns whether there is any additional elements in the iterator to be
* returned.
*
* @return <code>true</code> if there are more elements left to be
* returned from the iterator; <code>false</code> otherwise.
**/
public boolean hasNext() {
return pos.next != sentinel;
}
/**
* Returns the next element from the iterator.
*
* @return the next element from the iterator.
*
* @throws NoSuchElementException if there are no more elements in the
* iterator.
*
* @throws ConcurrentModificationException if a modification occurs in
* the underlying map.
**/
public Object next() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException(Messages.getMessage("seqHashMapConcurrentModificationException00"));
}
if (pos.next == sentinel) {
throw new NoSuchElementException(Messages.getMessage("seqHashMapNoSuchElementException00"));
}
// clear the "removed" flag
returnType = returnType & ~REMOVED_MASK;
pos = pos.next;
switch (returnType) {
case KEY :
return pos.getKey();
case VALUE :
return pos.getValue();
case ENTRY :
return pos;
default :
// should never happen
throw new Error(Messages.getMessage("seqHashMapBadIteratorType01", new Integer(returnType).toString()));
}
}
/**
* Removes the last element returned from the {@link #next()} method from
* the sequenced map.
*
* @throws IllegalStateException if there isn't a "last element" to be
* removed. That is, if {@link #next()} has never been called, or if
* {@link #remove()} was already called on the element.
*
* @throws ConcurrentModificationException if a modification occurs in
* the underlying map.
**/
public void remove() {
if ((returnType & REMOVED_MASK) != 0) {
throw new IllegalStateException(Messages.getMessage("seqHashMapIllegalStateException00"));
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException(Messages.getMessage("seqHashMapConcurrentModificationException00"));
}
SequencedHashMap.this.removeImpl(pos.getKey());
// update the expected mod count for the remove operation
expectedModCount++;
// set the removed flag
returnType = returnType | REMOVED_MASK;
}
}
// APIs maintained from previous version of SequencedHashMap for backwards
// compatibility
/**
* Creates a shallow copy of this object, preserving the internal structure
* by copying only references. The keys and values themselves are not
* <code>clone()</code>'d. The cloned object maintains the same sequence.
*
* @return A clone of this instance.
*
* @throws CloneNotSupportedException if clone is not supported by a
* subclass.
*/
public Object clone() throws CloneNotSupportedException {
// yes, calling super.clone() silly since we're just blowing away all
// the stuff that super might be doing anyway, but for motivations on
// this, see:
// http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html
SequencedHashMap map = (SequencedHashMap) super.clone();
// create new, empty sentinel
map.sentinel = createSentinel();
// create a new, empty entry map
// note: this does not preserve the initial capacity and load factor.
map.entries = new HashMap();
// add all the mappings
map.putAll(this);
// Note: We cannot just clone the hashmap and sentinel because we must
// duplicate our internal structures. Cloning those two will not clone all
// the other entries they reference, and so the cloned hash map will not be
// able to maintain internal consistency because there are two objects with
// the same entries. See discussion in the Entry implementation on why we
// cannot implement a clone of the Entry (and thus why we need to recreate
// everything).
return map;
}
/**
* Returns the Map.Entry at the specified index
*
* @throws ArrayIndexOutOfBoundsException if the specified index is
* <code>< 0</code> or <code>></code> the size of the map.
**/
private Map.Entry getEntry(int index) {
Entry pos = sentinel;
if (index < 0) {
throw new ArrayIndexOutOfBoundsException(Messages.getMessage("seqHashMapArrayIndexOutOfBoundsException01", new Integer(index).toString()));
}
// loop to one before the position
int i = -1;
while (i < (index - 1) && pos.next != sentinel) {
i++;
pos = pos.next;
}
// pos.next is the requested position
// if sentinel is next, past end of list
if (pos.next == sentinel) {
throw new ArrayIndexOutOfBoundsException(Messages.getMessage("seqHashMapArrayIndexOutOfBoundsException02",
new Integer(index).toString(),
new Integer(i + 1).toString()));
}
return pos.next;
}
/**
* Gets the key at the specified index.
*
* @param index the index to retrieve
* @return the key at the specified index, or null
* @throws ArrayIndexOutOfBoundsException if the <code>index</code> is
* <code>< 0</code> or <code>></code> the size of the map.
*/
public Object get(int index) {
return getEntry(index).getKey();
}
/**
* Gets the value at the specified index.
*
* @param index the index to retrieve
* @return the value at the specified index, or null
* @throws ArrayIndexOutOfBoundsException if the <code>index</code> is
* <code>< 0</code> or <code>></code> the size of the map.
*/
public Object getValue(int index) {
return getEntry(index).getValue();
}
/**
* Gets the index of the specified key.
*
* @param key the key to find the index of
* @return the index, or -1 if not found
*/
public int indexOf(Object key) {
Entry e = (Entry) entries.get(key);
if (e == null) {
return -1;
}
int pos = 0;
while (e.prev != sentinel) {
pos++;
e = e.prev;
}
return pos;
}
/**
* Gets an iterator over the keys.
*
* @return an iterator over the keys
*/
public Iterator iterator() {
return keySet().iterator();
}
/**
* Gets the last index of the specified key.
*
* @param key the key to find the index of
* @return the index, or -1 if not found
*/
public int lastIndexOf(Object key) {
// keys in a map are guarunteed to be unique
return indexOf(key);
}
/**
* Returns a List view of the keys rather than a set view. The returned
* list is unmodifiable. This is required because changes to the values of
* the list (using {@link java.util.ListIterator#set(Object)}) will
* effectively remove the value from the list and reinsert that value at
* the end of the list, which is an unexpected side effect of changing the
* value of a list. This occurs because changing the key, changes when the
* mapping is added to the map and thus where it appears in the list.
*
* <p>An alternative to this method is to use {@link #keySet()}
*
* @see #keySet()
* @return The ordered list of keys.
*/
public List sequence() {
List l = new ArrayList(size());
Iterator iter = keySet().iterator();
while (iter.hasNext()) {
l.add(iter.next());
}
return Collections.unmodifiableList(l);
}
/**
* Removes the element at the specified index.
*
* @param index The index of the object to remove.
* @return The previous value coressponding the <code>key</code>, or
* <code>null</code> if none existed.
*
* @throws ArrayIndexOutOfBoundsException if the <code>index</code> is
* <code>< 0</code> or <code>></code> the size of the map.
*/
public Object remove(int index) {
return remove(get(index));
}
// per Externalizable.readExternal(ObjectInput)
/**
* Deserializes this map from the given stream.
*
* @param in the stream to deserialize from
* @throws IOException if the stream raises it
* @throws ClassNotFoundException if the stream raises it
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
int size = in.readInt();
for (int i = 0; i < size; i++) {
Object key = in.readObject();
Object value = in.readObject();
put(key, value);
}
}
/**
* Serializes this map to the given stream.
*
* @param out the stream to serialize to
* @throws IOException if the stream raises it
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(size());
for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {
out.writeObject(pos.getKey());
out.writeObject(pos.getValue());
}
}
// add a serial version uid, so that if we change things in the future
// without changing the format, we can still deserialize properly.
private static final long serialVersionUID = 3380552487888102930L;
}
| 6,933 |
0 | Create_ds/axis-axis1-java/samples/faults-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/faults-sample/src/test/java/test/functional/TestFaultsSample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import samples.faults.EmployeeClient;
/** Test the faults sample code.
*/
public class TestFaultsSample extends TestCase {
static Log log =
LogFactory.getLog(TestFaultsSample.class.getName());
public void test1 () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"), "#001" };
EmployeeClient.main(args);
}
public void test2 () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"), "#002" };
try {
EmployeeClient.main(args);
} catch (samples.faults.NoSuchEmployeeFault nsef) {
return;
}
fail("Should not reach here");
}
}
| 6,934 |
0 | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples/faults/NoSuchEmployeeFault.java | /**
* NoSuchEmployeeFault.java
*
* This file was auto-generated from WSDL
* by the Apache Axis WSDL2Java emitter.
*/
package samples.faults;
import java.rmi.RemoteException;
public class NoSuchEmployeeFault extends RemoteException implements java.io.Serializable {
private java.lang.String info;
public NoSuchEmployeeFault() {
}
public NoSuchEmployeeFault(
java.lang.String info) {
this.info = info;
}
public java.lang.String getInfo() {
return info;
}
public void setInfo(java.lang.String info) {
this.info = info;
}
}
| 6,935 |
0 | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples/faults/EmployeeInfo.java | package samples.faults;
import samples.faults.Employee;
import java.util.Collection;
import java.util.HashMap;
public class EmployeeInfo {
static HashMap map = new HashMap();
static {
Employee emp = new Employee();
emp.setEmployeeID("#001");
emp.setEmployeeName("Bill Gates");
map.put(emp.getEmployeeID(), emp);
}
public void addEmployee(Employee in) {
map.put(in.getEmployeeID(), in);
}
public Employee getEmployee(java.lang.String id) throws NoSuchEmployeeFault {
Employee emp = (Employee) map.get(id);
if (emp == null) {
NoSuchEmployeeFault fault = new NoSuchEmployeeFault();
fault.setInfo("Could not find employee:" + id);
throw fault;
}
return emp;
}
public Employee[] getEmployees() {
Collection values = map.values();
Employee[] emps = new Employee[values.size()];
values.toArray(emps);
return emps;
}
}
| 6,936 |
0 | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples/faults/EmployeeClient.java | package samples.faults;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.utils.Options;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Service;
import javax.xml.rpc.Call;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import javax.xml.rpc.encoding.TypeMapping;
import javax.xml.namespace.QName;
import java.net.URL;
import samples.faults.Employee;
public class EmployeeClient {
public static void main(String[] args) throws Exception {
Options opts = new Options(args);
String uri = "http://faults.samples";
String serviceName = "EmployeeInfoService";
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(new QName(uri, serviceName));
TypeMappingRegistry registry = service.getTypeMappingRegistry();
TypeMapping map = registry.getDefaultTypeMapping();
QName employeeQName = new QName("http://faults.samples", "Employee");
map.register(Employee.class, employeeQName, new BeanSerializerFactory(Employee.class, employeeQName), new BeanDeserializerFactory(Employee.class, employeeQName));
QName faultQName = new QName("http://faults.samples", "NoSuchEmployeeFault");
map.register(NoSuchEmployeeFault.class, faultQName, new BeanSerializerFactory(NoSuchEmployeeFault.class, faultQName), new BeanDeserializerFactory(NoSuchEmployeeFault.class, faultQName));
Call call = service.createCall();
call.setTargetEndpointAddress(new URL(opts.getURL()).toString());
call.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
call.setProperty(Call.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "http://faults.samples");
call.setOperationName( new QName(uri, "getEmployee") );
String[] args2 = opts.getRemainingArgs();
System.out.println("Trying :" + args2[0]);
Employee emp = (Employee) call.invoke(new Object[]{ args2[0] });
System.out.println("Got :" + emp.getEmployeeID());
}
}
| 6,937 |
0 | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/faults-sample/src/main/java/samples/faults/Employee.java | /**
* Employee.java
*
* This file was auto-generated from WSDL
* by the Apache Axis WSDL2Java emitter.
*/
package samples.faults;
public class Employee {
private java.lang.String employeeID;
private java.lang.String employeeName;
public Employee() {
}
public java.lang.String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(java.lang.String employeeID) {
this.employeeID = employeeID;
}
public java.lang.String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(java.lang.String employeeName) {
this.employeeName = employeeName;
}
}
| 6,938 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/encoding-sample/src/test/java/test/functional/TestElementSample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.utils.NetworkUtils;
import samples.encoding.TestElem;
/** Test the ElementService sample code.
*/
public class TestElementSample extends TestCase {
public void testElement () throws Exception {
String thisHost = NetworkUtils.getLocalHostname();
String thisPort = System.getProperty("test.functional.ServicePort","8080");
String[] args = {thisHost,thisPort};
String xml = "<x:hello xmlns:x=\"urn:foo\">a string</x:hello>";
System.out.println("Sending : " + xml );
String res = TestElem.doit(args, xml);
System.out.println("Received: " + res );
assertEquals("TestElementSample.doit(): xml must match", res, xml);
}
}
| 6,939 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/DataSerFactory.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializerFactory;
import java.util.Iterator;
import java.util.Vector;
/**
* SerializerFactory for DataSer
*
* @author Rich Scheuerle <scheu@us.ibm.com>
*/
public class DataSerFactory implements SerializerFactory {
private Vector mechanisms;
public DataSerFactory() {
}
public javax.xml.rpc.encoding.Serializer getSerializerAs(String mechanismType) {
return new DataSer();
}
public Iterator getSupportedMechanismTypes() {
if (mechanisms == null) {
mechanisms = new Vector();
mechanisms.add(Constants.AXIS_SAX);
}
return mechanisms.iterator();
}
}
| 6,940 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/DataSer.java | package samples.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.wsdl.fromJava.Types;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import javax.xml.namespace.QName;
import java.io.IOException;
public class DataSer implements Serializer
{
public static final String STRINGMEMBER = "stringMember";
public static final String FLOATMEMBER = "floatMember";
public static final String DATAMEMBER = "dataMember";
public static final QName myTypeQName = new QName("typeNS", "Data");
/** SERIALIZER STUFF
*/
/**
* Serialize an element named name, with the indicated attributes
* and value.
* @param name is the element name
* @param attributes are the attributes...serialize is free to add more.
* @param value is the value
* @param context is the SerializationContext
*/
public void serialize(QName name, Attributes attributes,
Object value, SerializationContext context)
throws IOException
{
if (!(value instanceof Data))
throw new IOException("Can't serialize a " + value.getClass().getName() + " with a DataSerializer.");
Data data = (Data)value;
context.startElement(name, attributes);
context.serialize(new QName("", STRINGMEMBER), null, data.stringMember);
context.serialize(new QName("", FLOATMEMBER), null, data.floatMember);
context.serialize(new QName("", DATAMEMBER), null, data.dataMember);
context.endElement();
}
public String getMechanismType() { return Constants.AXIS_SAX; }
public Element writeSchema(Class javaType, Types types) throws Exception {
return null;
}
}
| 6,941 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/TestSer.java | package samples.encoding;
import org.apache.axis.Constants;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/** Little serialization test with a struct.
*/
public class TestSer
{
public static final String myNS = "urn:myNS";
public static void main(String args[]) {
MessageContext msgContext = new MessageContext(new AxisServer());
SOAPEnvelope msg = new SOAPEnvelope();
RPCParam arg1 = new RPCParam("urn:myNamespace", "testParam", "this is a string");
QName dataQName = new QName("typeNS", "Data");
Data data = new Data();
Data data2 = new Data();
data.stringMember = "String member";
data.floatMember = new Float("1.23");
data.dataMember = data2;
data2.stringMember = "another str member";
data2.floatMember = new Float("4.56");
data2.dataMember = null; // "data;" for loop-test of multi-refs
RPCParam arg2 = new RPCParam("", "struct", data);
RPCElement body = new RPCElement("urn:myNamespace", "method1", new Object[]{ arg1, arg2 });
msg.addBodyElement(body);
try {
Reader reader = null;
if (args.length == 0) {
Writer stringWriter = new StringWriter();
SerializationContext context = new SerializationContext(stringWriter, msgContext);
TypeMappingRegistry reg = context.getTypeMappingRegistry();
TypeMapping tm = (TypeMapping) reg.getOrMakeTypeMapping(Constants.URI_SOAP11_ENC);
tm.register(Data.class, dataQName, new DataSerFactory(), new DataDeserFactory());
msg.output(context);
String msgString = stringWriter.toString();
System.out.println("Serialized msg:");
System.out.println(msgString);
System.out.println("-------");
System.out.println("Testing deserialization...");
reader = new StringReader(msgString);
} else {
reader = new FileReader(args[0]);
}
DeserializationContext dser = new DeserializationContext(
new InputSource(reader), msgContext, org.apache.axis.Message.REQUEST);
dser.parse();
SOAPEnvelope env = dser.getEnvelope();
RPCElement rpcElem = (RPCElement)env.getFirstBody();
RPCParam struct = rpcElem.getParam("struct");
if (struct == null)
throw new Exception("No <struct> param");
if (!(struct.getObjectValue() instanceof Data)) {
System.out.println("Not a Data object! ");
System.out.println(struct.getObjectValue());
System.exit(1);
}
Data val = (Data)struct.getObjectValue();
if (val == null)
throw new Exception("No value for struct param");
System.out.println(val.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 6,942 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/Data.java | package samples.encoding;
public class Data
{
public String stringMember;
public Float floatMember;
public Data dataMember;
public String toString()
{
return getStringVal("", this);
}
public String getStringVal(String indent, Data topLevel)
{
String ret = "\n" + indent + "Data:\n";
ret += indent + " str[" + stringMember + "]\n";
ret += indent + " float[" + floatMember + "]\n";
ret += indent + " data[";
if (dataMember != null) {
if (dataMember == topLevel) {
ret += " top level";
} else
ret += dataMember.getStringVal(indent + " ", topLevel) + "\n" + indent;
} else
ret += " null";
ret += " ]";
return ret;
}
}
| 6,943 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/DataDeser.java | package samples.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.DeserializationContext;
import org.apache.axis.encoding.Deserializer;
import org.apache.axis.encoding.DeserializerImpl;
import org.apache.axis.encoding.FieldTarget;
import org.apache.axis.message.SOAPHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import java.util.Hashtable;
public class DataDeser extends DeserializerImpl
{
public static final String STRINGMEMBER = "stringMember";
public static final String FLOATMEMBER = "floatMember";
public static final String DATAMEMBER = "dataMember";
public static final QName myTypeQName = new QName("typeNS", "Data");
private Hashtable typesByMemberName = new Hashtable();
public DataDeser()
{
typesByMemberName.put(STRINGMEMBER, Constants.XSD_STRING);
typesByMemberName.put(FLOATMEMBER, Constants.XSD_FLOAT);
typesByMemberName.put(DATAMEMBER, myTypeQName);
value = new Data();
}
/** DESERIALIZER STUFF - event handlers
*/
/**
* This method is invoked when an element start tag is encountered.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the element's prefix
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*/
public SOAPHandler onStartChild(String namespace,
String localName,
String prefix,
Attributes attributes,
DeserializationContext context)
throws SAXException
{
QName typeQName = (QName)typesByMemberName.get(localName);
if (typeQName == null)
throw new SAXException("Invalid element in Data struct - " + localName);
// These can come in either order.
Deserializer dSer = context.getDeserializerForType(typeQName);
try {
dSer.registerValueTarget(new FieldTarget(value, localName));
} catch (NoSuchFieldException e) {
throw new SAXException(e);
}
if (dSer == null)
throw new SAXException("No deserializer for a " + typeQName + "???");
return (SOAPHandler)dSer;
}
}
| 6,944 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/ElementService.java | package samples.encoding;
import org.w3c.dom.Element;
public class ElementService {
public Element echoElement(String str, Element elem) {
return( elem );
}
}
| 6,945 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/DataDeserFactory.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.encoding;
import org.apache.axis.Constants;
import org.apache.axis.encoding.DeserializerFactory;
import java.util.Iterator;
import java.util.Vector;
/**
* DeserializerFactory for DataDeser
*
* @author Rich Scheuerle <scheu@us.ibm.com>
*/
public class DataDeserFactory implements DeserializerFactory {
private Vector mechanisms;
public DataDeserFactory() {
}
public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType) {
return new DataDeser();
}
public Iterator getSupportedMechanismTypes() {
if (mechanisms == null) {
mechanisms = new Vector();
mechanisms.add(Constants.AXIS_SAX);
}
return mechanisms.iterator();
}
}
| 6,946 |
0 | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/encoding-sample/src/main/java/samples/encoding/TestElem.java | package samples.encoding;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.utils.Options;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.net.URL;
public class TestElem {
static String xml = "<x:hello xmlns:x=\"urn:foo\">a string</x:hello>" ;
public static String doit(String[] args,String xml) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
String sURL = "http://" + args[0] + ":" + args[1] + "/axis/services/ElementService" ;
QName sqn = new QName(sURL, "ElementService" );
QName pqn = new QName(sURL, "ElementService" );
//Service service=new Service(new URL("file:ElementService.wsdl"),sqn);
Service service = new Service(new URL(sURL+"?wsdl"),sqn);
Call call = (Call) service.createCall( pqn, "echoElement" );
Options opts = new Options(args);
opts.setDefaultURL( call.getTargetEndpointAddress() );
call.setTargetEndpointAddress( new URL(opts.getURL()) );
Element elem = XMLUtils.newDocument(bais).getDocumentElement();
elem = (Element) call.invoke( new Object[] { "a string", elem } );
return( XMLUtils.ElementToString( elem ) );
}
public static void main(String[] args) throws Exception {
System.out.println("Sent: " + xml );
String res = doit(args, xml);
System.out.println("Returned: " + res );
}
}
| 6,947 |
0 | Create_ds/axis-axis1-java/samples/handler-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/handler-sample/src/test/java/test/functional/TestMimeHeaders.java | package test.functional;
import javax.xml.messaging.URLEndpoint;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;
import junit.framework.TestCase;
/**
* Test MIME headers.
*/
public class TestMimeHeaders extends TestCase {
public void testTransferMimeHeadersToHttpHeaders() throws Exception {
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
String headerName = "foo";
String headerValue = "bar";
message.getMimeHeaders().addHeader(headerName, headerValue);
URLEndpoint endpoint = new URLEndpoint("http://localhost:"
+ System.getProperty("test.functional.ServicePort", "8080")
+ "/axis/services/TestMimeHeaderService");
SOAPMessage response = con.call(message, endpoint);
String[] responseHeader = response.getMimeHeaders().getHeader(headerName);
assertTrue("Response header was null", responseHeader != null);
assertEquals("ResponseHeader.length wasn't 1", 1, responseHeader.length);
assertEquals("Header value didn't match", headerValue, responseHeader[0]);
}
}
| 6,948 |
0 | Create_ds/axis-axis1-java/samples/handler-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/handler-sample/src/main/java/samples/handler/TestMimeHeaderHandler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.handler;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
public class TestMimeHeaderHandler extends BasicHandler {
public void invoke(MessageContext msgContext) throws AxisFault {
Message requestMessage = msgContext.getRequestMessage();
Message responseMessage = new Message(requestMessage.getSOAPEnvelope());
String[] fooHeader = requestMessage.getMimeHeaders().getHeader("foo");
if (fooHeader != null) {
responseMessage.getMimeHeaders().addHeader("foo", fooHeader[0]);
}
msgContext.setResponseMessage(responseMessage);
}
}
| 6,949 |
0 | Create_ds/axis-axis1-java/samples/jaxm-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/jaxm-sample/src/test/java/test/functional/TestJAXMSamples.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import samples.jaxm.DelayedStockQuote;
import samples.jaxm.UddiPing;
/**
* Test the JAX-RPC compliance samples.
*/
public class TestJAXMSamples extends TestCase {
static Log log = LogFactory.getLog(TestJAXMSamples.class.getName());
public TestJAXMSamples(String name) {
super(name);
} // ctor
public void testUddiPing() throws Exception {
UddiPing.searchUDDI("Microsoft", "http://localhost:" + System.getProperty("jetty.httpPort") + "/uddi_v1");
} // testGetQuote
public void testDelayedStockQuote() throws Exception {
DelayedStockQuote stockQuote = new DelayedStockQuote("http://localhost:" + System.getProperty("jetty.httpPort") + "/xmethods/delayed-quotes");
assertEquals("3.67", stockQuote.getStockQuote("SUNW"));
} // testGetQuote
public static void main(String args[]) throws Exception {
TestJAXMSamples tester = new TestJAXMSamples("tester");
//tester.testUddiPing();
} // main
}
| 6,950 |
0 | Create_ds/axis-axis1-java/samples/jaxm-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/jaxm-sample/src/main/java/samples/jaxm/DelayedStockQuote.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 samples.jaxm;
import javax.xml.messaging.URLEndpoint;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.util.Iterator;
public class DelayedStockQuote {
private final String url;
public DelayedStockQuote() {
this("http://64.124.140.30/soap");
}
public DelayedStockQuote(String url) {
this.url = url;
}
public static void main(String[] args) throws Exception {
DelayedStockQuote stockQuote = new DelayedStockQuote();
System.out.print("The last price for SUNW is " + stockQuote.getStockQuote("SUNW"));
}
public String getStockQuote(String tickerSymbol) throws Exception {
SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = scFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();
header.detachNode();
Name bodyName = envelope.createName("getQuote", "n", "urn:xmethods-delayed-quotes");
SOAPBodyElement gltp = body.addBodyElement(bodyName);
Name name = envelope.createName("symbol");
SOAPElement symbol = gltp.addChildElement(name);
symbol.addTextNode(tickerSymbol);
URLEndpoint endpoint = new URLEndpoint(url);
SOAPMessage response = con.call(message, endpoint);
con.close();
SOAPPart sp = response.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
Iterator it = sb.getChildElements();
while (it.hasNext()) {
SOAPBodyElement bodyElement = (SOAPBodyElement) it.next();
Iterator it2 = bodyElement.getChildElements();
while (it2.hasNext()) {
SOAPElement element2 = (SOAPElement) it2.next();
return element2.getValue();
}
}
return null;
}
}
| 6,951 |
0 | Create_ds/axis-axis1-java/samples/jaxm-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/jaxm-sample/src/main/java/samples/jaxm/UddiPing.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 samples.jaxm;
import javax.xml.messaging.URLEndpoint;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
public class UddiPing {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: UddiPing business-name uddi-url");
System.exit(1);
}
searchUDDI(args[0], args[1]);
}
public static void searchUDDI(String name, String url) throws Exception {
// Create the connection and the message factory.
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection connection = scf.createConnection();
MessageFactory msgFactory = MessageFactory.newInstance();
// Create a message
SOAPMessage msg = msgFactory.createMessage();
// Create an envelope in the message
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
// Get hold of the the body
SOAPBody body = envelope.getBody();
javax.xml.soap.SOAPBodyElement bodyElement = body.addBodyElement(envelope.createName("find_business", "",
"urn:uddi-org:api"));
bodyElement.addAttribute(envelope.createName("generic"), "1.0")
.addAttribute(envelope.createName("maxRows"), "100")
.addChildElement("name")
.addTextNode(name);
URLEndpoint endpoint = new URLEndpoint(url);
msg.saveChanges();
SOAPMessage reply = connection.call(msg, endpoint);
System.out.println("Received reply from: " + endpoint);
reply.writeTo(System.out);
connection.close();
}
}
| 6,952 |
0 | Create_ds/axis-axis1-java/samples/attachments-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/attachments-sample/src/test/java/test/functional/TestAttachmentsSample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.utils.Options;
import samples.attachments.EchoAttachment;
import samples.attachments.TestRef;
/** Test the attachments sample code.
*/
public class TestAttachmentsSample extends TestCase {
private Options opts;
protected void setUp() throws Exception {
opts = new Options(new String[] { "-p", System.getProperty("test.functional.ServicePort", "8080") });
}
public void testAttachments1() throws Exception {
boolean res = new EchoAttachment(opts).echo(false, "pom.xml");
assertEquals("Didn't process attachment correctly", res, true) ;
}
public void testAttachmentsD1() throws Exception {
boolean res = new EchoAttachment(opts).echo(true, "pom.xml");
assertEquals("Didn't process attachment correctly", res, true) ;
}
public void testAttachmentsDimeLeaveEmpty() throws Exception {
boolean res = new EchoAttachment(opts).echo(true, "src/test/files/leaveempty.txt");
assertEquals("Didn't process attachment correctly", res, true) ;
}
public void testAttachments2() throws Exception {
boolean res = new EchoAttachment(opts).echoDir(false, "src/main/java/samples/attachments");
assertEquals("Didn't process attachments correctly", res, true);
}
public void testAttachmentsD2() throws Exception {
boolean res = new EchoAttachment(opts).echoDir(true, "src/main/java/samples/attachments");
assertEquals("Didn't process attachments correctly", res, true);
}
public void testAttachmentsTestRef() throws Exception {
boolean res = new TestRef(opts).testit();
assertEquals("Didn't process attachments correctly", res, true);
}
}
| 6,953 |
0 | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples/attachments/EchoAttachment.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.attachments;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
import org.apache.axis.transport.http.HTTPConstants;
import org.apache.axis.utils.Options;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.File;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
/**
*
* @author Rick Rineholt
*/
/**
* An example of sending an attachment via RPC.
* This class has a main method that beside the standard arguments
* allows you to specify an attachment that will be sent to a
* service which will then send it back.
*
*/
public class EchoAttachment {
Options opts = null;
public EchoAttachment(Options opts) {
this.opts = opts;
}
/**
* This method sends a file as an attachment then
* receives it as a return. The returned file is
* compared to the source.
* @param The filename that is the source to send.
* @return True if sent and compared.
*/
public boolean echo(final boolean doTheDIME, String filename) throws Exception {
//javax.activation.MimetypesFileTypeMap map= (javax.activation.MimetypesFileTypeMap)javax.activation.MimetypesFileTypeMap.getDefaultFileTypeMap();
//map.addMimeTypes("application/x-org-apache-axis-wsdd wsdd");
//Create the data for the attached file.
DataHandler dhSource = new DataHandler(new FileDataSource(filename));
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(opts.getURL())); //Set the target service host and service location,
call.setOperationName(new QName("urn:EchoAttachmentsService", "echo")); //This is the target services method to invoke.
QName qnameAttachment = new QName("urn:EchoAttachmentsService", "DataHandler");
call.registerTypeMapping(dhSource.getClass(), //Add serializer for attachment.
qnameAttachment,
JAFDataHandlerSerializerFactory.class,
JAFDataHandlerDeserializerFactory.class);
call.addParameter("source", qnameAttachment,
ParameterMode.IN); //Add the file.
call.setReturnType(qnameAttachment);
call.setUsername(opts.getUser());
call.setPassword(opts.getPassword());
if (doTheDIME)
call.setProperty(call.ATTACHMENT_ENCAPSULATION_FORMAT,
call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME);
Object ret = call.invoke(new Object[]{
dhSource
}
); //Add the attachment.
if (null == ret) {
System.out.println("Received null ");
throw new AxisFault("", "Received null", null, null);
}
if (ret instanceof String) {
System.out.println("Received problem response from server: " + ret);
throw new AxisFault("", (String) ret, null, null);
}
if (!(ret instanceof DataHandler)) {
//The wrong type of object that what was expected.
System.out.println("Received problem response from server:" +
ret.getClass().getName());
throw new AxisFault("", "Received problem response from server:" +
ret.getClass().getName(), null, null);
}
//Still here, so far so good.
//Now lets brute force compare the source attachment
// to the one we received.
DataHandler rdh = (DataHandler) ret;
//From here we'll just treat the data resource as file.
String receivedfileName = rdh.getName();//Get the filename.
if (receivedfileName == null) {
System.err.println("Could not get the file name.");
throw new AxisFault("", "Could not get the file name.", null, null);
}
System.out.println("Going to compare the files..");
boolean retv = compareFiles(filename, receivedfileName);
java.io.File receivedFile = new java.io.File(receivedfileName);
receivedFile.delete();
return retv;
}
/**
* This method sends all the files in a directory.
* @param The directory that is the source to send.
* @return True if sent and compared.
*/
public boolean echoDir(final boolean doTheDIME, String filename) throws Exception {
boolean rc = true;
DataHandler[] attachments = getAttachmentsFromDir(filename); //Get the attachments from the directory.
if (attachments.length == 0) {
throw new java.lang.IllegalArgumentException(
"The directory \"" + filename + "\" has no files to send.");
}
Service service = new Service(); //A new axis Service.
Call call = (Call) service.createCall(); //Create a call to the service.
/*Un comment the below statement to do HTTP/1.1 protocol*/
//call.setScopedProperty(MessageContext.HTTP_TRANSPORT_VERSION,HTTPConstants.HEADER_PROTOCOL_V11);
Hashtable myhttp = new Hashtable();
myhttp.put("dddd", "yyy"); //Send extra soap headers
myhttp.put("SOAPAction", "dyyy");
myhttp.put("SOAPActions", "prova");
/*Un comment the below to do http chunking to avoid the need to calculate content-length. (Needs HTTP/1.1)*/
//myhttp.put(HTTPConstants.HEADER_TRANSFER_ENCODING, HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED);
/*Un comment the below to force a 100-Continue... This will cause httpsender to wait for
* this response on a post. If HTTP 1.1 and this is not set, *SOME* servers *MAY* reply with this anyway.
* Currently httpsender won't handle this situation, this will require the resp. which it will handle.
*/
//myhttp.put(HTTPConstants.HEADER_EXPECT, HTTPConstants.HEADER_EXPECT_100_Continue);
call.setProperty(HTTPConstants.REQUEST_HEADERS, myhttp);
call.setTargetEndpointAddress(new URL(opts.getURL())); //Set the target service host and service location,
call.setOperationName(new QName("urn:EchoAttachmentsService", "echoDir")); //This is the target services method to invoke.
QName qnameAttachment = new QName("urn:EchoAttachmentsService", "DataHandler");
call.registerTypeMapping(attachments[0].getClass(), //Add serializer for attachment.
qnameAttachment,
JAFDataHandlerSerializerFactory.class,
JAFDataHandlerDeserializerFactory.class);
call.addParameter("source", XMLType.SOAP_ARRAY, // new XMLType(qnameAttachment),
ParameterMode.IN); //Add the file.
call.setReturnType(XMLType.SOAP_ARRAY); // new XMLType(qnameAttachment));
call.setUsername(opts.getUser());
call.setPassword(opts.getPassword());
if (doTheDIME)
call.setProperty(call.ATTACHMENT_ENCAPSULATION_FORMAT,
call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME);
Object ret = call.invoke(new Object[]{
attachments
}
); //Add the attachment.
if (null == ret) {
System.out.println("Received null ");
throw new AxisFault("", "Received null", null, null);
}
if (ret instanceof String) {
System.out.println("Received problem response from server: " + ret);
throw new AxisFault("", (String) ret, null, null);
}
if (!(ret instanceof javax.activation.DataHandler[])) {
//The wrong type of object that what was expected.
System.out.println("Received unexpected type :" +
ret.getClass().getName());
throw new AxisFault("", "Received unexpected type:" +
ret.getClass().getName(), null, null);
}
//Still here, so far so good.
//Now lets brute force compare the source attachment
// to the one we received.
javax.activation.DataHandler[] received = (javax.activation.DataHandler[]) ret;
int i = 0;
for (i = 0; i < received.length && i < attachments.length; ++i) {
DataHandler recDH = received[i];
DataHandler orginalDH = attachments[i];
if (!compareFiles(filename + java.io.File.separator + orginalDH.getName(), recDH.getName())) {
System.err.println("The attachment with the file name: \"" + orginalDH.getName() +
"\" was not received the same!.");
rc = false;
}
java.io.File receivedFile = new java.io.File(recDH.getName());
receivedFile.delete();
}
if (i < received.length) {
System.err.println("There are more file received than sent!!!!");
rc = false;
}
if (i < attachments.length) {
System.err.println("Not all the files were received!");
rc = false;
}
return rc;
}
/**
* Give a single file to send or name a directory
* to send an array of attachments of the files in
* that directory.
*/
public static void main(String args[]) {
try {
Options opts = new Options(args);
EchoAttachment echoattachment = new EchoAttachment(opts);
args = opts.getRemainingArgs();
int argpos = 0;
if (args == null || args.length == 0) {
System.err.println("Need a file or directory argument.");
System.exit(8);
}
boolean doTheDIME = false;
if (args[0].trim().equalsIgnoreCase("+FDR")) {
doTheDIME = true;
++argpos;
}
if (argpos >= args.length) {
System.err.println("Need a file or directory argument.");
System.exit(8);
}
String argFile = args[argpos];
java.io.File source = new java.io.File(argFile);
if (!source.exists()) {
System.err.println("Error \"" + argFile + "\" does not exist!");
System.exit(8);
}
if (source.isFile()) {
if (echoattachment.echoUsingSAAJ(argFile) && echoattachment.echo(doTheDIME, argFile)) {
System.out.println("Attachment sent and received ok!");
System.exit(0);
} else {
System.err.println("Problem in matching attachments");
System.exit(8);
}
} else { //a directory?
if (echoattachment.echoDir(doTheDIME, argFile)) {
System.out.println("Attachments sent and received ok!");
System.exit(0);
} else {
System.err.println("Problem in matching attachments");
System.exit(8);
}
}
} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
System.exit(18);
}
/**
* Quick and unsophisticated method to compare two file's
* byte stream.
* @param The first file to compare.
* @param The second file to compare.
* @return True if the bytestreams do compare, false for
* any other reason.
*/
protected boolean compareFiles(String one, String other)
throws java.io.FileNotFoundException, java.io.IOException {
java.io.BufferedInputStream oneStream = null;
java.io.BufferedInputStream otherStream = null;
// First compare file length.
File f1 = new File(one);
File f2 = new File(other);
if (f1.length() != f2.length())
return false;
try {
oneStream = new java.io.BufferedInputStream(
new java.io.FileInputStream(one), 1024 * 64);
otherStream = new java.io.BufferedInputStream(
new java.io.FileInputStream(other), 1024 * 64);
byte[] bufOne = new byte[1024 * 64];
byte[] bufOther = new byte[1024 * 64];
int breadOne = -1;
int breadOther = -1;
int available = 0;
do {
available = oneStream.available();
available = Math.min(available, otherStream.available());
available = Math.min(available, bufOther.length);
if (0 != available) {
java.util.Arrays.fill(bufOne, (byte) 0);
java.util.Arrays.fill(bufOther, (byte) 0);
breadOne = oneStream.read(bufOne, 0, available);
breadOther = otherStream.read(bufOther, 0, available);
if (breadOne != breadOther)
throw new RuntimeException(
"Sorry couldn't really read whats available!");
if (!java.util.Arrays.equals(bufOne, bufOther)) {
return false;
}
}
} while (available != 0 && breadOne != -1 && breadOther != -1);
if (available != 0 && (breadOne != -1 || breadOther != -1)) {
return false;
}
return true;
} finally {
if (null != oneStream) oneStream.close();
if (null != otherStream) otherStream.close();
}
}
/**
* Return an array of datahandlers for each file in the dir.
* @param the name of the directory
* @return return an array of datahandlers.
*/
protected DataHandler[] getAttachmentsFromDir(String dirName) {
java.util.LinkedList retList = new java.util.LinkedList();
DataHandler[] ret = new DataHandler[0];// empty
java.io.File sourceDir = new java.io.File(dirName);
java.io.File[] files = sourceDir.listFiles();
for (int i = files.length - 1; i >= 0; --i) {
java.io.File cf = files[i];
if (cf.isFile() && cf.canRead()) {
String fname = null;
try {
fname = cf.getAbsoluteFile().getCanonicalPath();
} catch (java.io.IOException e) {
System.err.println("Couldn't get file \"" + fname + "\" skipping...");
continue;
}
retList.add(new DataHandler(new FileDataSource(fname)));
}
}
if (!retList.isEmpty()) {
ret = new DataHandler[retList.size()];
ret = (DataHandler[]) retList.toArray(ret);
}
return ret;
}
/**
* This method sends a file as an attachment then
* receives it as a return. The returned file is
* compared to the source. Uses SAAJ API.
* @param The filename that is the source to send.
* @return True if sent and compared.
*/
public boolean echoUsingSAAJ(String filename) throws Exception {
String endPointURLString = "http://localhost:" +opts.getPort() + "/axis/services/urn:EchoAttachmentsService";
SOAPConnectionFactory soapConnectionFactory =
javax.xml.soap.SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();
SOAPMessage soapMessage =
messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope requestEnvelope =
soapPart.getEnvelope();
SOAPBody body = requestEnvelope.getBody();
SOAPBodyElement operation = body.addBodyElement
(requestEnvelope.createName("echo"));
Vector dataHandlersToAdd = new Vector();
dataHandlersToAdd.add(new DataHandler(new FileDataSource(new
File(filename))));
if (dataHandlersToAdd != null) {
ListIterator dataHandlerIterator =
dataHandlersToAdd.listIterator();
while (dataHandlerIterator.hasNext()) {
DataHandler dataHandler = (DataHandler)
dataHandlerIterator.next();
javax.xml.soap.SOAPElement element =
operation.addChildElement(requestEnvelope.createName("source"));
javax.xml.soap.AttachmentPart attachment =
soapMessage.createAttachmentPart(dataHandler);
soapMessage.addAttachmentPart(attachment);
element.addAttribute(requestEnvelope.createName
("href"), "cid:" + attachment.getContentId());
}
}
javax.xml.soap.SOAPMessage returnedSOAPMessage =
soapConnection.call(soapMessage, endPointURLString);
Iterator iterator = returnedSOAPMessage.getAttachments();
if (!iterator.hasNext()) {
//The wrong type of object that what was expected.
System.out.println("Received problem response from server");
throw new AxisFault("", "Received problem response from server", null, null);
}
//Still here, so far so good.
//Now lets brute force compare the source attachment
// to the one we received.
DataHandler rdh = (DataHandler) ((AttachmentPart)iterator.next()).getDataHandler();
//From here we'll just treat the data resource as file.
String receivedfileName = rdh.getName();//Get the filename.
if (receivedfileName == null) {
System.err.println("Could not get the file name.");
throw new AxisFault("", "Could not get the file name.", null, null);
}
System.out.println("Going to compare the files..");
boolean retv = compareFiles(filename, receivedfileName);
java.io.File receivedFile = new java.io.File(receivedfileName);
receivedFile.delete();
return retv;
}
}
| 6,954 |
0 | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples/attachments/EchoAttachmentsService.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.attachments;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.activation.DataHandler;
/**
* @author Rick Rineholt
*/
/**
* An example of
* This class has a main method that beside the standard arguments
* allows you to specify an attachment that will be sent to a
* service which will then send it back.
*
*/
public class EchoAttachmentsService {
/**
* This method implements a web service that sends back
* any attachment it receives.
*/
public DataHandler echo( DataHandler dh) {
System.err.println("In echo");
//Attachments are sent by default back as a MIME stream if no attachments were
// received. If attachments are received the same format that was received will
// be the default stream type for any attachments sent.
//The following two commented lines would force any attachments sent back.
// to be in DIME format.
//Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
//rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
if (dh == null ) System.err.println("dh is null");
else System.err.println("Received \""+dh.getClass().getName()+"\".");
return dh;
}
/**
* This method implements a web service that sends back
* an array of attachment it receives.
*/
public DataHandler[] echoDir( DataHandler[] attachments) {
System.err.println("In echoDir");
//Attachments are sent by default back as a MIME stream if no attachments were
// received. If attachments are received the same format that was received will
// be the default stream type for any attachments sent.
//The following two commented lines would force any attachments sent back.
// to be in DIME format.
//Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
//rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
if (attachments == null ) System.err.println("attachments is null!");
else System.err.println("Got " + attachments.length + " attachments!");
return attachments;
}
public Document attachments( Document xml)
throws org.apache.axis.AxisFault,java.io.IOException, org.xml.sax.SAXException,
java.awt.datatransfer.UnsupportedFlavorException,javax.xml.parsers.ParserConfigurationException,
java.lang.ClassNotFoundException,javax.xml.soap.SOAPException {
System.err.println("In message handling attachments directly.");
org.apache.axis.MessageContext msgContext= org.apache.axis.MessageContext.getCurrentContext();
org.apache.axis.Message reqMsg= msgContext.getRequestMessage();
org.apache.axis.attachments.Attachments attachments=reqMsg.getAttachmentsImpl();
if(null == attachments){
throw new org.apache.axis.AxisFault("No support for attachments" );
}
Element rootEl= xml.getDocumentElement();
Element caEl= getNextFirstChildElement(rootEl);
StringBuffer fullmsg= new StringBuffer();
java.util.Vector reply= new java.util.Vector();
for(int count=1 ;caEl != null; caEl= getNextSiblingElement(caEl), ++count){
String href= caEl.getAttribute("href");
org.apache.axis.Part p= attachments.getAttachmentByReference(href);
if(null == p)
throw new org.apache.axis.AxisFault("Attachment for ref='"+href+"' not found." );
String ordinalStr =getOrdinalHeaders(p);
if( null == ordinalStr || ordinalStr.trim().length()==0)
throw new org.apache.axis.AxisFault("Ordinal for attachment ref='"+href+"' not found." );
int ordinal= Integer.parseInt(ordinalStr);
if(count != ordinal)
throw new org.apache.axis.AxisFault("Ordinal for attachment ref='"+href+"' excpected" + count + " got " + ordinal +"." );
//check content type.
if(!"text/plain".equals(p.getContentType()))
throw new org.apache.axis.AxisFault("Attachment ref='"+href+"' bad content-type:'"+p.getContentType()+"'." );
//now get at the data...
DataHandler dh= ((org.apache.axis.attachments.AttachmentPart)p).getDataHandler();
String pmsg=(String )dh.getContent();
fullmsg.append(pmsg);
reply.add(pmsg);
}
if(!(samples.attachments.TestRef .TheKey.equals(fullmsg.toString())))
throw new org.apache.axis.AxisFault("Fullmsg not correct'"+fullmsg +"'." );
System.out.println(fullmsg.toString());
//Now lets Java serialize the reply...
java.io.ByteArrayOutputStream byteStream = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(byteStream);
oos.writeObject(reply);
oos.close();
byte[] replyJavaSerialized= byteStream.toByteArray();
byteStream=null; oos= null;
org.apache.axis.attachments.AttachmentPart replyPart= new
org.apache.axis.attachments.AttachmentPart(
new DataHandler( new MemoryOnlyDataSource(replyJavaSerialized,
java.awt.datatransfer.DataFlavor.javaSerializedObjectMimeType+"; class=\""
+ reply.getClass().getName()+"\"")));
//Now lets add the attachment to the response message.
org.apache.axis.Message rspMsg= msgContext.getResponseMessage();
rspMsg.addAttachmentPart(replyPart);
//Iterate over the attachments... not by reference.
String ordinalPattern="";
for(java.util.Iterator ai=reqMsg.getAttachments(); ai.hasNext();){
org.apache.axis.Part p= (org.apache.axis.Part) ai.next();
ordinalPattern += getOrdinalHeaders(p);
}
//Now build the return document in a string buffer...
StringBuffer msgBody = new StringBuffer("\n<attachments xmlns=\"");
msgBody.append(rootEl.getNamespaceURI())
.append("\">\n")
.append("\t<attachment href=\"")
.append(replyPart.getContentIdRef())
.append("\" ordinalPattern=\"")
.append(ordinalPattern)
.append("\"/>\n")
.append("</attachments>\n");
//Convert the string buffer to an XML document and return it.
return
org.apache.axis.utils.XMLUtils.newDocument(
new org.xml.sax.InputSource(new java.io.ByteArrayInputStream(
msgBody.toString().getBytes())));
}
Element getNextFirstChildElement(Node n) {
if(n== null) return null;
n= n.getFirstChild();
for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
return (Element)n;
}
Element getNextSiblingElement(Node n) {
if(n== null) return null;
n= n.getNextSibling();
for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
return (Element)n;
}
String getOrdinalHeaders( org.apache.axis.Part p){
StringBuffer ret= new StringBuffer();
for(java.util.Iterator i= p.getMatchingMimeHeaders( new String[]{samples.attachments.TestRef.positionHTTPHeader});
i.hasNext();){
javax.xml.soap.MimeHeader mh= (javax.xml.soap.MimeHeader) i.next();
String v= mh.getValue();
if(v != null) ret.append(v.trim());
}
return ret.toString();
}
/**This class should store all attachment data in memory */
static class MemoryOnlyDataSource extends org.apache.axis.attachments.ManagedMemoryDataSource{
MemoryOnlyDataSource( byte [] in, String contentType) throws java.io.IOException{
super( new java.io.ByteArrayInputStream( in) , Integer.MAX_VALUE -2, contentType, true);
}
MemoryOnlyDataSource( String in, String contentType)throws java.io.IOException{
this( in.getBytes() , contentType);
}
}
}
| 6,955 |
0 | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/attachments-sample/src/main/java/samples/attachments/TestRef.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.attachments;
import org.apache.axis.AxisFault;
import org.apache.axis.attachments.AttachmentPart;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.transport.http.HTTPConstants;
import org.apache.axis.utils.Options;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
/**
*
* @author Rick Rineholt
*/
/**
* An example of sending an attachment via messages.
* The main purpose is to validate the different types of attachment references
* by content Id, content location both absolute and relative.
*
* Creates 5 separate attachments referenced differently by a SOAP document.
* Each attachment contains a string that is assembled and tested to see if
* if the attachments are correctly sent and referenced. Each attachment also
* contains a mime header indicating its position and validated on the server
* to see if mime headers are correctly sent with attachments.
*
* Sends the same message again however the second attachments are placed in the
* stream in reverse to see if they are still referenced ok.
*
*
* The return SOAP document references a single attachment which is the a Java
* serialized vector holding strings to the individual attachments sent.
*
* Demos using attachments directly.
*
*/
public class TestRef {
Options opts = null;
public static final String positionHTTPHeader="Ordinal";
public static final String TheKey= "Now is the time for all good men to come to the aid of their country.";
public TestRef( Options opts) {
this.opts = opts;
}
/**
* This method sends all the files in a directory.
* @param The directory that is the source to send.
* @return True if sent and compared.
*/
public boolean testit() throws Exception {
boolean rc = true;
String baseLoc= "http://axis.org/attachTest";
Vector refs= new Vector(); //holds a string of references to attachments.
Service service = new Service(); //A new axis Service.
Call call = (Call) service.createCall(); //Create a call to the service.
/*Un comment the below statement to do HTTP/1.1 protocol*/
//call.setScopedProperty(MessageContext.HTTP_TRANSPORT_VERSION,HTTPConstants.HEADER_PROTOCOL_V11);
Hashtable myhttp= new Hashtable();
myhttp.put(HTTPConstants.HEADER_CONTENT_LOCATION, baseLoc); //Send extra soap headers
/*Un comment the below to do http chunking to avoid the need to calculate content-length. (Needs HTTP/1.1)*/
//myhttp.put(HTTPConstants.HEADER_TRANSFER_ENCODING, HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED);
/*Un comment the below to force a 100-Continue... This will cause httpsender to wait for
* this response on a post. If HTTP 1.1 and this is not set, *SOME* servers *MAY* reply with this anyway.
* Currently httpsender won't handle this situation, this will require the resp. which it will handle.
*/
//myhttp.put(HTTPConstants.HEADER_EXPECT, HTTPConstants.HEADER_EXPECT_100_Continue);
call.setProperty(HTTPConstants.REQUEST_HEADERS,myhttp);
call.setTargetEndpointAddress( new URL(opts.getURL()) ); //Set the target service host and service location,
java.util.Stack rev= new java.util.Stack();
//Create an attachment referenced by a generated contentId.
AttachmentPart ap= new AttachmentPart(new javax.activation.DataHandler(
"Now is the time", "text/plain" ));
refs.add(ap.getContentIdRef()); //reference the attachment by contentId.
ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
call.addAttachmentPart(ap);
rev.push(ap);
//Create an attachment referenced by a set contentId.
String setContentId="rick_did_this";
ap= new AttachmentPart(new DataHandler(" for all good", "text/plain" ));
//new MemoryOnlyDataSource(
ap.setContentId(setContentId);
refs.add("cid:" + setContentId); //reference the attachment by contentId.
ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
call.addAttachmentPart(ap);
rev.push(ap);
//Create an attachment referenced by a absolute contentLocation.
ap= new AttachmentPart(new DataHandler( " men to", "text/plain" ));
//new MemoryOnlyDataSource( " men to", "text/plain" )));
ap.setContentLocation(baseLoc+ "/firstLoc");
refs.add(baseLoc+ "/firstLoc"); //reference the attachment by contentId.
ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
call.addAttachmentPart(ap);
rev.push(ap);
//Create an attachment referenced by relative location to a absolute location.
ap= new AttachmentPart(new DataHandler( " come to", "text/plain" ));
// new MemoryOnlyDataSource( " come to", "text/plain" )));
ap.setContentLocation(baseLoc+ "/secondLoc");
refs.add("secondLoc"); //reference the attachment by contentId.
ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
call.addAttachmentPart(ap);
rev.push(ap);
//Create an attachment referenced by relative location to a relative location.
ap= new AttachmentPart(new DataHandler( " the aid of their country.", "text/plain" ));
// new MemoryOnlyDataSource( " the aid of their country.", "text/plain" )));
ap.setContentLocation("thirdLoc");
refs.add("thirdLoc"); //reference the attachment by contentId.
ap.setMimeHeader(positionHTTPHeader, ""+refs.size() ); //create a MIME header indicating postion.
call.addAttachmentPart(ap);
rev.push(ap);
//Now build the message....
String namespace="urn:attachmentsTestRef"; //needs to match name of service.
StringBuffer msg = new StringBuffer("\n<attachments xmlns=\"" +namespace +"\">\n");
for (java.util.Iterator i = refs.iterator(); i.hasNext() ; )
msg.append(" <attachment href=\"" + (String) i.next() + "\"/>\n");
msg.append( "</attachments>");
call.setUsername( opts.getUser());
call.setPassword( opts.getPassword() );
call.setOperationStyle("document");
call.setOperationUse("literal");
//Now do the call....
Object ret = call.invoke(new Object[]{
new SOAPBodyElement(new ByteArrayInputStream(msg.toString().getBytes("UTF-8"))) } );
validate(ret, call, "12345");
//Note: that even though the attachments are sent in reverse they are still
// retreived by reference so the ordinal will still match.
int revc=1;
for( ap= (AttachmentPart)rev.pop(); ap!=null ;ap= rev.empty()? null : (AttachmentPart)rev.pop()){
call.addAttachmentPart(ap);
}
//Now do the call....
ret = call.invoke(new Object[]{
new SOAPBodyElement(new ByteArrayInputStream(msg.toString().getBytes("UTF-8"))) } );
validate(ret, call, "54321");
return rc;
}
void validate(Object ret, Call call, final String expOrdPattern) throws Exception{
if (null == ret) {
System.out.println("Received null ");
throw new AxisFault("", "Received null", null, null);
}
if (ret instanceof String) {
System.out.println("Received problem response from server: " + ret);
throw new AxisFault("", (String) ret, null, null);
}
Vector vret= (Vector) ret;
if (!(ret instanceof java.util.Vector )) {
//The wrong type of object that what was expected.
System.out.println("Received unexpected type :" +
ret.getClass().getName());
throw new AxisFault("", "Received unexpected type:" +
ret.getClass().getName(), null, null);
}
org.apache.axis.message.RPCElement retrpc= (org.apache.axis.message.RPCElement )
((Vector)ret).elementAt(0);
Document retDoc= org.apache.axis.utils.XMLUtils.newDocument(
new org.xml.sax.InputSource(new java.io.ByteArrayInputStream(
retrpc.toString().getBytes())));
//get at the attachments.
org.apache.axis.attachments.Attachments attachments=
call.getResponseMessage().getAttachmentsImpl();
//Still here, so far so good.
Element rootEl= retDoc.getDocumentElement();
Element caEl= getNextFirstChildElement(rootEl);
//this should be the only child element with the ref to our attachment
// response.
String href= caEl.getAttribute("href");
org.apache.axis.Part p= attachments.getAttachmentByReference(href);
if(null == p)
throw new org.apache.axis.AxisFault("Attachment for ref='"+href+"' not found." );
//Check to see the the attachment were sent in order
String ordPattern= caEl.getAttribute("ordinalPattern");
if(!expOrdPattern.equals(ordPattern))
throw new org.apache.axis.AxisFault(
"Attachments sent out of order expected:'" +expOrdPattern + "', got:'"+ordPattern+"'." );
//now get at the data...
DataHandler dh= ((org.apache.axis.attachments.AttachmentPart)p).getDataHandler();
System.err.println("content-type:" + dh.getContentType());
java.util.Vector rspVector= null;
Object rspObject = dh.getContent();//This SHOULD just return the vector but reality strikes...
if(rspObject == null)
throw new AxisFault("", "Received unexpected object:null", null, null);
else if(rspObject instanceof java.util.Vector) rspVector= (java.util.Vector)rspObject;
else if(rspObject instanceof java.io.InputStream)
rspVector= (java.util.Vector)
new java.io.ObjectInputStream((java.io.InputStream)rspObject ).readObject();
else
throw new AxisFault("", "Received unexpected object:" +
rspObject.getClass().getName(), null, null);
StringBuffer fullmsg= new StringBuffer();
for(java.util.Iterator ri= rspVector.iterator(); ri.hasNext();){
String part= (String)ri.next();
fullmsg.append(part);
System.out.print(part);
}
System.out.println("");
if(!(TheKey.equals (fullmsg.toString())))
throw new org.apache.axis.AxisFault("Fullmsg not correct'"+fullmsg +"'." );
}
Element getNextFirstChildElement(Node n) {
if(n== null) return null;
n= n.getFirstChild();
for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
return (Element)n;
}
Element getNextSiblingElement(Node n) {
if(n== null) return null;
n= n.getNextSibling();
for(; n!= null && !(n instanceof Element); n= n.getNextSibling());
return (Element)n;
}
/**
* Give a single file to send or name a directory
* to send an array of attachments of the files in
* that directory.
*/
public static void main(String args[]) {
try {
Options opts = new Options(args);
TestRef echoattachment = new TestRef(opts);
args = opts.getRemainingArgs();
int argpos=0;
if (echoattachment.testit()) {
System.out.println("Attachments sent and received ok!");
System.exit(0);
}
}
catch ( Exception e ) {
System.err.println(e);
e.printStackTrace();
}
System.exit(18);
}
/**
* Return an array of datahandlers for each file in the dir.
* @param the name of the directory
* @return return an array of datahandlers.
*/
protected DataHandler[] getAttachmentsFromDir(String dirName) {
java.util.LinkedList retList = new java.util.LinkedList();
DataHandler[] ret = new DataHandler[0];// empty
java.io.File sourceDir = new java.io.File(dirName);
java.io.File[] files = sourceDir.listFiles();
for ( int i = files.length - 1; i >= 0; --i) {
java.io.File cf = files[i];
if (cf.isFile() && cf.canRead()) {
String fname = null;
try {
fname = cf.getAbsoluteFile().getCanonicalPath();
}
catch ( java.io.IOException e) {
System.err.println("Couldn't get file \"" + fname + "\" skipping...");
continue;
}
retList.add( new DataHandler( new FileDataSource( fname )));
}
}
if (!retList.isEmpty()) {
ret = new DataHandler[ retList.size()];
ret = (DataHandler[]) retList.toArray(ret);
}
return ret;
}
/**This class should store all attachment data in memory */
static class MemoryOnlyDataSource extends org.apache.axis.attachments.ManagedMemoryDataSource{
MemoryOnlyDataSource( byte [] in, String contentType) throws java.io.IOException{
super( new java.io.ByteArrayInputStream( in) , Integer.MAX_VALUE -2, contentType, true);
}
MemoryOnlyDataSource( String in, String contentType)throws java.io.IOException{
this( in.getBytes() , contentType);
}
}
}
| 6,956 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/test/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/test/java/samples/integrationGuide/example2/VerifyFilesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package samples.integrationGuide.example2;
import java.io.File;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
public class VerifyFilesTest extends TestCase {
public void testDeployUseless() throws Exception {
File file = new File("target/work/example2/com/examples/www/wsdl/HelloService_wsdl/deploy.useless");
assertTrue(file.exists());
assertEquals("Hi ho! Hi ho! It's off to work we go.", FileUtils.readFileToString(file).trim());
}
} | 6,957 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/test/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/test/java/samples/integrationGuide/example1/VerifyFilesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package samples.integrationGuide.example1;
import java.io.File;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
public class VerifyFilesTest extends TestCase {
public void testDeployUseless() throws Exception {
File file = new File("target/work/example1/com/examples/www/wsdl/HelloService_wsdl/Hello_Service.lst");
assertTrue(file.exists());
assertEquals("Hello_Port", FileUtils.readFileToString(file).trim());
}
} | 6,958 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example2/MyDeployWriter.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example2;
import org.apache.axis.wsdl.symbolTable.SymbolTable;
import org.apache.axis.wsdl.toJava.Emitter;
import org.apache.axis.wsdl.toJava.JavaWriter;
import javax.wsdl.Definition;
import java.io.IOException;
import java.io.PrintWriter;
public class MyDeployWriter extends JavaWriter {
private String filename;
public MyDeployWriter(Emitter emitter, Definition definition,
SymbolTable symbolTable) {
super(emitter, "deploy");
// Create the fully-qualified file name
String dir = emitter.getNamespaces().getAsDir(
definition.getTargetNamespace());
filename = dir + "deploy.useless";
} // ctor
public void generate() throws IOException {
if (emitter.isServerSide()) {
super.generate();
}
} // generate
protected String getFileName() {
return filename;
} // getFileName
/**
* Override the common JavaWriter header to a no-op.
*/
protected void writeFileHeader(PrintWriter pw) throws IOException {
} // writeFileHeader
/**
* Write the service list file.
*/
protected void writeFileBody(PrintWriter pw) throws IOException {
MyEmitter myEmitter = (MyEmitter) emitter;
if (myEmitter.getSong() == MyEmitter.RUM) {
pw.println("Yo! Ho! Ho! And a bottle of rum.");
}
else if (myEmitter.getSong() == MyEmitter.WORK) {
pw.println("Hi ho! Hi ho! It's off to work we go.");
}
else {
pw.println("Feelings... Nothing more than feelings...");
}
} // writeFileBody
} // class MyDeployWriter
| 6,959 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example2/WSDL2Useless.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example2;
import org.apache.axis.utils.CLOption;
import org.apache.axis.utils.CLOptionDescriptor;
import org.apache.axis.wsdl.WSDL2Java;
import org.apache.axis.wsdl.gen.Parser;
public class WSDL2Useless extends WSDL2Java {
protected static final int SONG_OPT = 'g';
protected static final CLOptionDescriptor[] options = new CLOptionDescriptor[]{
new CLOptionDescriptor("song",
CLOptionDescriptor.ARGUMENT_REQUIRED,
SONG_OPT,
"Choose a song for deploy.useless: work or rum")
};
public WSDL2Useless() {
addOptions(options);
} // ctor
protected Parser createParser() {
return new MyEmitter();
} // createParser
protected void parseOption(CLOption option) {
if (option.getId() == SONG_OPT) {
String arg = option.getArgument();
if (arg.equals("rum")) {
((MyEmitter) parser).setSong(MyEmitter.RUM);
}
else if (arg.equals("work")) {
((MyEmitter) parser).setSong(MyEmitter.WORK);
}
}
else {
super.parseOption(option);
}
} // parseOption
/**
* Main
*/
public static void main(String args[]) {
WSDL2Useless useless = new WSDL2Useless();
useless.run(args);
} // main
} // class WSDL2Useless
| 6,960 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example2/MyGeneratorFactory.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example2;
import org.apache.axis.wsdl.toJava.JavaDefinitionWriter;
import org.apache.axis.wsdl.toJava.JavaGeneratorFactory;
import org.apache.axis.wsdl.toJava.JavaUndeployWriter;
import javax.wsdl.Definition;
/**
* IBM Extension to WSDL2Java Emitter
* This class is used to locate the IBM extension writers.
* (For example the IBM JavaType Writer)
*
* @author Rich Scheuerle (scheu@us.ibm.com)
* @author Russell Butek (butek@us.ibm.com)
*/
public class MyGeneratorFactory extends JavaGeneratorFactory {
/*
* NOTE! addDefinitionGenerators is the ONLY addXXXGenerators method
* that works at this point in time (2002-17-May). This rest of them
* are soon to be implemented.
*/
protected void addDefinitionGenerators() {
addGenerator(Definition.class, JavaDefinitionWriter.class); // WSDL2Java's JavaDefinitionWriter
addGenerator(Definition.class, MyDeployWriter.class); // our DeployWriter
addGenerator(Definition.class, JavaUndeployWriter.class); // WSDL2Java's JavaUndeployWriter
} // addDefinitionGenerators
} // class MyGeneratorFactory
| 6,961 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example2/MyEmitter.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example2;
import org.apache.axis.wsdl.toJava.Emitter;
public class MyEmitter extends Emitter {
public static final int RUM = 0;
public static final int WORK = 1;
private int song = -1;
public MyEmitter() {
MyGeneratorFactory factory = new MyGeneratorFactory();
setFactory(factory);
factory.setEmitter(this);
} // ctor
public int getSong() {
return song;
} // getSong
public void setSong(int song) {
this.song = song;
} // setSong
} // class MyEmitter
| 6,962 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example1/MyWSDL2Java.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example1;
import org.apache.axis.wsdl.WSDL2Java;
import org.apache.axis.wsdl.toJava.JavaGeneratorFactory;
import javax.wsdl.Service;
public class MyWSDL2Java extends WSDL2Java {
/**
* Main
*/
public static void main(String args[]) {
MyWSDL2Java myWSDL2Java = new MyWSDL2Java();
JavaGeneratorFactory factory = (JavaGeneratorFactory) myWSDL2Java.getParser().getFactory();
factory.addGenerator(Service.class, MyListPortsWriter.class);
myWSDL2Java.run(args);
} // main
} // MyWSDL2Java
| 6,963 |
0 | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide | Create_ds/axis-axis1-java/samples/integrationguide-sample/src/main/java/samples/integrationGuide/example1/MyListPortsWriter.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.integrationGuide.example1;
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.JavaWriter;
import org.apache.axis.wsdl.toJava.Utils;
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 my example of a class that writes a list of a service's
* ports to a file named <serviceName>Lst.lst.
*
* Note: because of a name clash problem, I add the suffix "Lst".
* I hope to remove this in a future version of this example.
*
* Details of the JavaWriter bug: JavaWriter looks to make sure a
* class doesn't already exist before creating a file, but not all
* files that we generate are .class files! This works with
* deploy.wsdd and undeploy.wsdd because these files just happen
* to begin with lowercase letters, where Java classes begin with
* uppercase letters. But this example shows the problem quite
* well. I would LIKE to call the file <serviceName>.lst, but
* JavaWriter sees that we already have a class called
* <serviceName> and won't let me proceed.
*/
public class MyListPortsWriter extends JavaWriter {
private Service service;
private String fileName;
/**
* Constructor.
*/
public MyListPortsWriter(
Emitter emitter,
ServiceEntry sEntry,
SymbolTable symbolTable) {
super(emitter, "service list");
this.service = sEntry.getService();
// Create the fully-qualified file name
String javaName = sEntry.getName();
fileName = emitter.getNamespaces().toDir(
Utils.getJavaPackageName(javaName))
+ Utils.getJavaLocalName(javaName) + ".lst";
} // ctor
protected String getFileName() {
return fileName;
} // getFileName
/**
* Override the common JavaWriter header to a no-op.
*/
protected void writeFileHeader(PrintWriter pw) throws IOException {
} // writeFileHeader
/**
* Write the service list file.
*/
protected void writeFileBody(PrintWriter pw) throws IOException {
Map portMap = service.getPorts();
Iterator portIterator = portMap.values().iterator();
while (portIterator.hasNext()) {
Port p = (Port) portIterator.next();
pw.println(p.getName());
}
pw.close(); // Note: this really should be done in JavaWriter.
} // writeFileBody
} // class MyListPortsWriter
| 6,964 |
0 | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/test/java/samples | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/test/java/samples/mtomstub/TestDownloadFile.java | package samples.mtomstub;
import java.net.URL;
import javax.xml.ws.Endpoint;
import org.apache.axiom.testutils.PortAllocator;
import junit.framework.TestCase;
import samples.mtomstub.service.DownloadFileImpl;
import samples.mtomstub.stub.DownloadFile;
import samples.mtomstub.stub.DownloadFileServiceLocator;
public class TestDownloadFile extends TestCase {
public void test() throws Exception {
String url = "http://localhost:" + PortAllocator.allocatePort() + "/DownloadFile";
Endpoint endpoint = Endpoint.publish(url, new DownloadFileImpl());
DownloadFile downloadFile = new DownloadFileServiceLocator().getDownloadFilePort(new URL(url));
downloadFile.getFile().getFile().writeTo(System.out);
endpoint.stop();
}
}
| 6,965 |
0 | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub/service/DownloadFileImpl.java | package samples.mtomstub.service;
import javax.activation.DataHandler;
import javax.jws.WebService;
import javax.mail.util.ByteArrayDataSource;
@WebService(endpointInterface="samples.mtomstub.service.DownloadFile", serviceName = "DownloadFileWS")
public class DownloadFileImpl implements DownloadFile {
public ResponseDownloadFile getFile() throws Exception {
ResponseDownloadFile rdf = new ResponseDownloadFile();
String contentType = "text/plain; charset='UTF-8'";
rdf.setFileName("readme.txt");
rdf.setFileType(contentType);
rdf.setFile(new DataHandler(new ByteArrayDataSource("This is the content".getBytes("UTF-8"), contentType)));
return rdf;
}
}
| 6,966 |
0 | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub/service/ResponseDownloadFile.java | package samples.mtomstub.service;
import javax.activation.DataHandler;
public class ResponseDownloadFile {
private String fileName;
private String fileType;
private DataHandler file;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public DataHandler getFile() {
return file;
}
public void setFile(DataHandler file) {
this.file = file;
}
}
| 6,967 |
0 | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub | Create_ds/axis-axis1-java/samples/mtomstub-sample/src/main/java/samples/mtomstub/service/DownloadFile.java | package samples.mtomstub.service;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;
@WebService
@MTOM
public interface DownloadFile {
ResponseDownloadFile getFile() throws Exception;
}
| 6,968 |
0 | Create_ds/axis-axis1-java/samples/addr-sample/src/test/java/samples | Create_ds/axis-axis1-java/samples/addr-sample/src/test/java/samples/addr/AddressBookTestCase.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.addr;
import junit.framework.TestCase;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
/** Test the address book sample code.
*/
public class AddressBookTestCase extends TestCase {
static Log log =
LogFactory.getLog(AddressBookTestCase.class.getName());
public AddressBookTestCase(String name) {
super(name);
}
public void doTest () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080") };
Main.main(args);
}
public void testAddressBookService () throws Exception {
try {
log.info("Testing address book sample.");
doTest();
log.info("Test complete.");
}
catch( Exception e ) {
e.printStackTrace();
throw new Exception("Fault returned from test: "+e);
}
}
}
| 6,969 |
0 | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples/addr/DOMUtils.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.addr;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author Matthew J. Duftler
* @author Sanjiva Weerawarana
*/
public class DOMUtils {
/**
* The namespaceURI represented by the prefix <code>xmlns</code>.
*/
private static String NS_URI_XMLNS = "http://www.w3.org/2000/xmlns/";
/**
* Returns the value of an attribute of an element. Returns null
* if the attribute is not found (whereas Element.getAttribute
* returns "" if an attrib is not found).
*
* @param el Element whose attrib is looked for
* @param attrName name of attribute to look for
* @return the attribute value
*/
static public String getAttribute (Element el, String attrName) {
String sRet = null;
Attr attr = el.getAttributeNode(attrName);
if (attr != null) {
sRet = attr.getValue();
}
return sRet;
}
/**
* Returns the value of an attribute of an element. Returns null
* if the attribute is not found (whereas Element.getAttributeNS
* returns "" if an attrib is not found).
*
* @param el Element whose attrib is looked for
* @param namespaceURI namespace URI of attribute to look for
* @param localPart local part of attribute to look for
* @return the attribute value
*/
static public String getAttributeNS (Element el,
String namespaceURI,
String localPart) {
String sRet = null;
Attr attr = el.getAttributeNodeNS (namespaceURI, localPart);
if (attr != null) {
sRet = attr.getValue ();
}
return sRet;
}
/**
* Concat all the text and cdata node children of this elem and return
* the resulting text.
*
* @param parentEl the element whose cdata/text node values are to
* be combined.
* @return the concatanated string.
*/
static public String getChildCharacterData (Element parentEl) {
if (parentEl == null) {
return null;
}
Node tempNode = parentEl.getFirstChild();
StringBuffer strBuf = new StringBuffer();
CharacterData charData;
while (tempNode != null) {
switch (tempNode.getNodeType()) {
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE : charData = (CharacterData)tempNode;
strBuf.append(charData.getData());
break;
}
tempNode = tempNode.getNextSibling();
}
return strBuf.toString();
}
/**
* Return the first child element of the given element. Null if no
* children are found.
*
* @param elem Element whose child is to be returned
* @return the first child element.
*/
public static Element getFirstChildElement (Element elem) {
for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
if (n.getNodeType () == Node.ELEMENT_NODE) {
return (Element) n;
}
}
return null;
}
/**
* Return the next sibling element of the given element. Null if no
* more sibling elements are found.
*
* @param elem Element whose sibling element is to be returned
* @return the next sibling element.
*/
public static Element getNextSiblingElement (Element elem) {
for (Node n = elem.getNextSibling (); n != null; n = n.getNextSibling ()) {
if (n.getNodeType () == Node.ELEMENT_NODE) {
return (Element) n;
}
}
return null;
}
/**
* Return the first child element of the given element which has the
* given attribute with the given value.
*
* @param elem the element whose children are to be searched
* @param attrName the attrib that must be present
* @param attrValue the desired value of the attribute
*
* @return the first matching child element.
*/
public static Element findChildElementWithAttribute (Element elem,
String attrName,
String attrValue) {
for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
if (n.getNodeType () == Node.ELEMENT_NODE) {
if (attrValue.equals (DOMUtils.getAttribute ((Element) n, attrName))) {
return (Element) n;
}
}
}
return null;
}
/**
* Count number of children of a certain type of the given element.
*
* @param elem the element whose kids are to be counted
*
* @return the number of matching kids.
*/
public static int countKids (Element elem, short nodeType) {
int nkids = 0;
for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
if (n.getNodeType () == nodeType) {
nkids++;
}
}
return nkids;
}
/**
* Given a prefix and a node, return the namespace URI that the prefix
* has been associated with. This method is useful in resolving the
* namespace URI of attribute values which are being interpreted as
* QNames. If prefix is null, this method will return the default
* namespace.
*
* @param context the starting node (looks up recursively from here)
* @param prefix the prefix to find an xmlns:prefix=uri for
*
* @return the namespace URI or null if not found
*/
public static String getNamespaceURIFromPrefix (Node context,
String prefix) {
short nodeType = context.getNodeType ();
Node tempNode = null;
switch (nodeType)
{
case Node.ATTRIBUTE_NODE :
{
tempNode = ((Attr) context).getOwnerElement ();
break;
}
case Node.ELEMENT_NODE :
{
tempNode = context;
break;
}
default :
{
tempNode = context.getParentNode ();
break;
}
}
while (tempNode != null && tempNode.getNodeType () == Node.ELEMENT_NODE)
{
Element tempEl = (Element) tempNode;
String namespaceURI = (prefix == null)
? getAttribute (tempEl, "xmlns")
: getAttributeNS (tempEl, NS_URI_XMLNS, prefix);
if (namespaceURI != null)
{
return namespaceURI;
}
else
{
tempNode = tempEl.getParentNode ();
}
}
return null;
}
public static Element getElementByID(Element el, String id)
{
if (el == null)
return null;
String thisId = el.getAttribute("id");
if (id.equals(thisId))
return el;
NodeList list = el.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node instanceof Element) {
Element ret = getElementByID((Element)node, id);
if (ret != null)
return ret;
}
}
return null;
}
}
| 6,970 |
0 | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples/addr/AddressBookSOAPBindingImpl.java | /**
* AddressBookSOAPBindingImpl.java
*
* This file was hand modified from the Emmitter generated code.
*/
package samples.addr;
import java.util.Hashtable;
import java.util.Map;
public class AddressBookSOAPBindingImpl implements AddressBook {
private Map addresses = new Hashtable();
public void addEntry(java.lang.String name, samples.addr.Address address) throws java.rmi.RemoteException {
this.addresses.put(name, address);
}
public samples.addr.Address getAddressFromName(java.lang.String name) throws java.rmi.RemoteException {
return (samples.addr.Address) this.addresses.get(name);
}
}
| 6,971 |
0 | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/addr-sample/src/main/java/samples/addr/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.
*/
package samples.addr;
import org.apache.axis.utils.Options;
import java.net.URL;
/**
* This class shows how to use the Call object's ability to
* become session aware.
*
* @author Rob Jellinghaus (robj@unrealities.com)
* @author Sanjiva Weerawarana <sanjiva@watson.ibm.com>
*/
public class Main {
static String name1;
static Address addr1;
static Phone phone1;
static {
name1 = "Purdue Boilermaker";
addr1 = new Address();
phone1 = new Phone();
addr1.setStreetNum(1);
addr1.setStreetName("University Drive");
addr1.setCity("West Lafayette");
addr1.setState(StateType.IN);
addr1.setZip(47907);
phone1.setAreaCode(765);
phone1.setExchange("494");
phone1.setNumber("4900");
addr1.setPhoneNumber(phone1);
}
private static void printAddress (Address ad) {
if (ad == null) {
System.err.println ("\t[ADDRESS NOT FOUND!]");
return;
}
System.err.println ("\t" + ad.getStreetNum() + " " +
ad.getStreetName());
System.err.println ("\t" + ad.getCity() + ", " + ad.getState() + " " +
ad.getZip());
Phone ph = ad.getPhoneNumber();
System.err.println ("\tPhone: (" + ph.getAreaCode() + ") " +
ph.getExchange() + "-" + ph.getNumber());
}
private static Object doit (AddressBook ab) throws Exception {
System.err.println (">> Storing address for '" + name1 + "'");
ab.addEntry (name1, addr1);
System.err.println (">> Querying address for '" + name1 + "'");
Address resp = ab.getAddressFromName (name1);
System.err.println (">> Response is:");
printAddress (resp);
// if we are NOT maintaining session, resp must be == null.
// If we ARE, resp must be != null.
System.err.println (">> Querying address for '" + name1 + "' again");
resp = ab.getAddressFromName (name1);
System.err.println (">> Response is:");
printAddress (resp);
return resp;
}
public static void main (String[] args) throws Exception {
Options opts = new Options(args);
System.err.println ("Using proxy without session maintenance.");
System.err.println ("(queries without session should say: \"ADDRESS NOT FOUND!\")");
AddressBookService abs = new AddressBookServiceLocator();
opts.setDefaultURL( abs.getAddressBookAddress() );
URL serviceURL = new URL(opts.getURL());
AddressBook ab1 = null;
if (serviceURL == null) {
ab1 = abs.getAddressBook();
}
else {
ab1 = abs.getAddressBook(serviceURL);
}
Object ret = doit (ab1);
if (ret != null) {
throw new Exception("non-session test expected null response, got " + ret);
}
System.err.println ("\n\nUsing proxy with session maintenance.");
AddressBook ab2 = null;
if (serviceURL == null) {
ab2 = abs.getAddressBook();
}
else {
ab2 = abs.getAddressBook(serviceURL);
}
((AddressBookSOAPBindingStub) ab2).setMaintainSession (true);
ret = doit (ab2);
if (ret == null) {
throw new Exception("session test expected non-null response, got " + ret);
}
}
}
| 6,972 |
0 | Create_ds/axis-axis1-java/samples/message-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/message-sample/src/test/java/test/functional/TestMessageSample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import samples.message.TestMsg;
/** Test the message sample code.
*/
public class TestMessageSample extends TestCase {
public void testMessage() throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080") };
String res = (new TestMsg()).doit(args);
String expected="Res elem[0]=<ns1:e1 xmlns:ns1=\"urn:foo\">Hello</ns1:e1>"
+"Res elem[1]=<ns2:e1 xmlns:ns2=\"urn:foo\">World</ns2:e1>"
+"Res elem[2]=<ns3:e3 xmlns:ns3=\"urn:foo\">"
+"<![CDATA["
+"Text with\n\tImportant <b> whitespace </b> and tags! "
+"]]>"
+"</ns3:e3>";
assertEquals("test result elements", expected, res);
}
}
| 6,973 |
0 | Create_ds/axis-axis1-java/samples/message-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/message-sample/src/main/java/samples/message/TestMsg.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 samples.message;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.utils.Options;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Vector;
/**
* Simple test driver for our message service.
*/
public class TestMsg {
public String doit(String[] args) throws Exception {
Options opts = new Options(args);
opts.setDefaultURL("http://localhost:8080/axis/services/MessageService");
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(opts.getURL()) );
SOAPBodyElement[] input = new SOAPBodyElement[3];
input[0] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "Hello"));
input[1] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
"e1", "World"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element cdataElem = doc.createElementNS("urn:foo", "e3");
CDATASection cdata = doc.createCDATASection("Text with\n\tImportant <b> whitespace </b> and tags! ");
cdataElem.appendChild(cdata);
input[2] = new SOAPBodyElement(cdataElem);
Vector elems = (Vector) call.invoke( input );
SOAPBodyElement elem = null ;
Element e = null ;
elem = (SOAPBodyElement) elems.get(0);
e = elem.getAsDOM();
String str = "Res elem[0]=" + XMLUtils.ElementToString(e);
elem = (SOAPBodyElement) elems.get(1);
e = elem.getAsDOM();
str = str + "Res elem[1]=" + XMLUtils.ElementToString(e);
elem = (SOAPBodyElement) elems.get(2);
e = elem.getAsDOM();
str = str + "Res elem[2]=" + XMLUtils.ElementToString(e);
return( str );
}
public void testEnvelope(String[] args) throws Exception {
String xmlString =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <soapenv:Header>\n" +
" <shw:Hello xmlns:shw=\"http://localhost:8080/axis/services/MessageService\">\n" +
" <shw:Myname>Tony</shw:Myname>\n" +
" </shw:Hello>\n" +
" </soapenv:Header>\n" +
" <soapenv:Body>\n" +
" <shw:process xmlns:shw=\"http://message.samples\">\n" +
" <shw:City>GENT</shw:City>\n" +
" </shw:process>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage smsg =
mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
SOAPPart sp = smsg.getSOAPPart();
SOAPEnvelope se = (SOAPEnvelope)sp.getEnvelope();
SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = conn.call(smsg, "http://localhost:8080/axis/services/MessageService2");
}
public static void main(String[] args) throws Exception {
TestMsg testMsg = new TestMsg();
testMsg.doit(args);
testMsg.testEnvelope(args);
}
}
| 6,974 |
0 | Create_ds/axis-axis1-java/samples/message-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/message-sample/src/main/java/samples/message/MessageService.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 samples.message ;
import org.w3c.dom.Element;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPElement;
/**
* Simple message-style service sample.
*/
public class MessageService {
/**
* Service method, which simply echoes back any XML it receives.
*
* @param elems an array of DOM Elements, one for each SOAP body element
* @return an array of DOM Elements to be sent in the response body
*/
public Element[] echoElements(Element [] elems) {
return elems;
}
public void process(SOAPEnvelope req, SOAPEnvelope resp) throws javax.xml.soap.SOAPException {
SOAPBody body = resp.getBody();
Name ns0 = resp.createName("TestNS0", "ns0", "http://example.com");
Name ns1 = resp.createName("TestNS1", "ns1", "http://example.com");
SOAPElement bodyElmnt = body.addBodyElement(ns0);
SOAPElement el = bodyElmnt.addChildElement(ns1);
el.addTextNode("TEST RESPONSE");
}
}
| 6,975 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/test/java/test/functional/TestJAXRPCSamples.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.client.AdminClient;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import samples.jaxrpc.GetInfo;
import samples.jaxrpc.GetQuote1;
/**
* Test the JAX-RPC compliance samples.
*/
public class TestJAXRPCSamples extends TestCase {
static Log log = LogFactory.getLog(TestJAXRPCSamples.class.getName());
public TestJAXRPCSamples(String name) {
super(name);
} // ctor
public void doTestGetQuoteXXX() throws Exception {
String[] args = {"-uuser1", "-wpass1", "XXX"};
float val = new GetQuote1().getQuote1(args);
assertEquals("Stock price is not the expected 55.25 +/- 0.01", val,
55.25, 0.01);
} // doTestGetQuoteXXX
public void doTestGetQuoteMain() throws Exception {
String[] args = {"-uuser1", "-wpass1", "XXX"};
GetQuote1.main(args);
} // doTestGetQuoteMain
// public void testGetQuote() throws Exception {
// try {
// log.info("Testing JAX-RPC GetQuote1 sample.");
// log.info("Testing deployment...");
// doTestDeploy();
// log.info("Testing service...");
// doTestGetQuoteXXX();
// doTestGetQuoteMain();
// log.info("Testing undeployment...");
// doTestUndeploy();
// log.info("Test complete.");
// }
// catch (Throwable t) {
// t.printStackTrace();
// throw new Exception("Fault returned from test: " + t);
// }
// } // testGetQuote
public void testGetInfo() throws Exception {
log.info("Testing JAX-RPC GetInfo sample.");
log.info("Testing service...");
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser3", "-wpass3", "IBM", "symbol"};
GetInfo.main(args);
args = new String[] { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser3", "-wpass3", "MACR", "name"};
GetInfo.main(args);
args = new String[] { "-p", System.getProperty("test.functional.ServicePort", "8080"),
"-uuser3", "-wpass3", "CSCO", "address"};
GetInfo.main(args);
log.info("Test complete.");
} // testGetInfo
public void testHello() throws Exception {
log.info("Testing JAX-RPC hello sample.");
samples.jaxrpc.hello.HelloClient.main(new String[]{ "http://localhost:" + System.getProperty("test.functional.ServicePort", "8080") });
log.info("Test complete.");
}
public void testAddress() throws Exception {
log.info("Testing JAX-RPC Address sample.");
samples.jaxrpc.address.AddressClient.main(new String[]{ "http://localhost:" + System.getProperty("test.functional.ServicePort", "8080") });
log.info("Test complete.");
}
public static void main(String args[]) throws Exception {
TestJAXRPCSamples tester = new TestJAXRPCSamples("tester");
tester.testHello();
tester.testAddress();
} // main
}
| 6,976 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/GetInfo.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.jaxrpc;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
/**
* This version of GetInfo is a near-duplicate of the GetInfo class in
* samples/stock. This version is strictly JAX-RPC compliant. It uses
* no AXIS enhancements.
*
* @author Russell Butek (butek@us.ibm.com)
*/
public class GetInfo {
public static void main(String args[]) throws Exception {
Options opts = new Options(args);
args = opts.getRemainingArgs();
if (args == null || args.length % 2 != 0) {
System.err.println("Usage: GetInfo <symbol> <datatype>");
System.exit(1);
}
String symbol = args[0];
Service service = ServiceFactory.newInstance().createService(null);
Call call = service.createCall();
call.setTargetEndpointAddress(opts.getURL());
call.setOperationName(new QName("urn:cominfo", "getInfo"));
call.addParameter("symbol", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("info", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
if(opts.getUser()!=null)
call.setProperty(Call.USERNAME_PROPERTY, opts.getUser());
if(opts.getPassword()!=null)
call.setProperty(Call.PASSWORD_PROPERTY, opts.getPassword());
String res = (String) call.invoke(new Object[] {args[0], args[1]});
System.out.println(symbol + ": " + res);
} // main
}
| 6,977 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/GetQuote1.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.jaxrpc;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.net.URL;
/**
* This version of the ever so popular GetQuote is a near-duplicate of
* the GetQuote1 method in samples/stock which shows how to use the AXIS
* client APIs with and without WSDL. This version is strictly JAX-RPC
* compliant. It uses no AXIS enhancements.
*
* This sample supports the use of the standard options too (-p ...)
*
* @author Russell Butek (butek@us.ibm.com)
*/
public class GetQuote1 {
public String symbol;
/**
* This will use the WSDL to prefill all of the info needed to make
* the call. All that's left is filling in the args to invoke().
*/
public float getQuote1(String args[]) throws Exception {
Options opts = new Options(args);
args = opts.getRemainingArgs();
if (args == null) {
System.err.println("Usage: GetQuote <symbol>");
System.exit(1);
}
/* Define the service QName and port QName */
/*******************************************/
QName servQN = new QName("urn:xmltoday-delayed-quotes",
"GetQuoteService");
QName portQN = new QName("urn:xmltoday-delayed-quotes", "GetQuote");
/* Now use those QNames as pointers into the WSDL doc */
/******************************************************/
Service service = ServiceFactory.newInstance().createService(
new URL("file:samples/stock/GetQuote.wsdl"), servQN);
Call call = service.createCall(portQN, "getQuote");
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL(call.getTargetEndpointAddress());
call.setTargetEndpointAddress(opts.getURL());
/* Define some service specific properties */
/*******************************************/
call.setProperty(Call.USERNAME_PROPERTY, opts.getUser());
call.setProperty(Call.PASSWORD_PROPERTY, opts.getPassword());
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke(new Object[] {symbol = args[0]});
return ((Float) result).floatValue();
} // getQuote1
/**
* This will do everything manually (ie. no WSDL).
*/
public float getQuote2(String args[]) throws Exception {
Options opts = new Options(args);
args = opts.getRemainingArgs();
if (args == null) {
System.err.println("Usage: GetQuote <symbol>");
System.exit(1);
}
/* Create default/empty Service and Call object */
/************************************************/
Service service = ServiceFactory.newInstance().createService(null);
Call call = service.createCall();
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL("http://localhost:8080/axis/servlet/AxisServlet");
/* Set all of the stuff that would normally come from WSDL */
/***********************************************************/
call.setTargetEndpointAddress(opts.getURL());
call.setProperty(Call.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "getQuote");
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,
"http://schemas.xmlsoap.org/soap/encoding/");
call.setOperationName(new QName("urn:xmltoday-delayed-quotes", "getQuote"));
call.addParameter("symbol", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_FLOAT);
/* Define some service specific properties */
/*******************************************/
call.setProperty(Call.USERNAME_PROPERTY, opts.getUser());
call.setProperty(Call.PASSWORD_PROPERTY, opts.getPassword());
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke(new Object[] {symbol = args[0]});
return ((Float) result).floatValue();
} // getQuote2
/**
* This method does the same thing that getQuote1 does, but in
* addition it reuses the Call object to make another call.
*/
public float getQuote3(String args[]) throws Exception {
Options opts = new Options(args);
args = opts.getRemainingArgs();
if (args == null) {
System.err.println("Usage: GetQuote <symbol>");
System.exit(1);
}
/* Define the service QName and port QName */
/*******************************************/
QName servQN = new QName("urn:xmltoday-delayed-quotes",
"GetQuoteService");
QName portQN = new QName("urn:xmltoday-delayed-quotes", "GetQuote");
/* Now use those QNames as pointers into the WSDL doc */
/******************************************************/
Service service = ServiceFactory.newInstance().createService(
new URL("file:samples/stock/GetQuote.wsdl"), servQN);
Call call = service.createCall(portQN, "getQuote");
/* Strange - but allows the user to change just certain portions of */
/* the URL we're gonna use to invoke the service. Useful when you */
/* want to run it thru tcpmon (ie. put -p81 on the cmd line). */
/********************************************************************/
opts.setDefaultURL(call.getTargetEndpointAddress());
call.setTargetEndpointAddress(opts.getURL());
/* Define some service specific properties */
/*******************************************/
call.setProperty(Call.USERNAME_PROPERTY, opts.getUser());
call.setProperty(Call.PASSWORD_PROPERTY, opts.getPassword());
/* Get symbol and invoke the service */
/*************************************/
Object result = call.invoke(new Object[] {symbol = args[0]});
/* Reuse the Call object for a different call */
/**********************************************/
call.setOperationName(new QName("urn:xmltoday-delayed-quotes", "test"));
call.removeAllParameters();
call.setReturnType(XMLType.XSD_STRING);
System.out.println(call.invoke(new Object[]{}));
return ((Float) result).floatValue();
} // getQuote3
public static void main(String args[]) throws Exception {
String save_args[] = new String[args.length];
float val;
GetQuote1 gq = new GetQuote1();
/* Call the getQuote() that uses the WDSL */
/******************************************/
System.out.println("Using WSDL");
System.arraycopy(args, 0, save_args, 0, args.length);
val = gq.getQuote1(args);
System.out.println(gq.symbol + ": " + val);
/* Call the getQuote() that does it all manually */
/*************************************************/
System.out.println("Manually");
System.arraycopy(save_args, 0, args, 0, args.length);
val = gq.getQuote2(args);
System.out.println(gq.symbol + ": " + val);
/* Call the getQuote() that uses Axis's generated WSDL */
/*******************************************************/
System.out.println("WSDL + Reuse Call");
System.arraycopy(save_args, 0, args, 0, args.length);
val = gq.getQuote3(args);
System.out.println(gq.symbol + ": " + val);
} // main
}
| 6,978 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/address/AddressSoapBindingImpl.java | package samples.jaxrpc.address;
public class AddressSoapBindingImpl implements samples.jaxrpc.address.AddressService {
public String updateAddress(AddressBean addressBean, int newPostCode) throws java.rmi.RemoteException {
addressBean.setPostcode(newPostCode);
return ("Your street : " + addressBean.getStreet() + "\nYour postCode : " + newPostCode);
}
}
| 6,979 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/address/AddressClient.java | package samples.jaxrpc.address;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.net.URL;
public class AddressClient {
public static void main(String[] args) throws Exception {
URL urlWsdl = new URL((args.length > 0 ? args[0] : "http://localhost:8080") + "/axis/services/Address?wsdl");
String nameSpaceUri = "http://address.jaxrpc.samples";
String serviceName = "AddressServiceService";
String portName = "Address";
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(urlWsdl, new
QName(nameSpaceUri, serviceName));
AddressService myProxy = (AddressService) service.getPort(new
QName(nameSpaceUri, portName), AddressService.class);
AddressBean addressBean = new AddressBean();
addressBean.setStreet("55, rue des Lilas");
System.out.println(myProxy.updateAddress(addressBean, 75005));
}
} | 6,980 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/hello/ClientHandler.java | package samples.jaxrpc.hello;
public class ClientHandler implements javax.xml.rpc.handler.Handler {
public ClientHandler() {
}
public boolean handleRequest(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ClientHandler: In handleRequest");
return true;
}
public boolean handleResponse(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ClientHandler: In handleResponse");
return true;
}
public boolean handleFault(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ClientHandler: In handleFault");
return true;
}
public void init(javax.xml.rpc.handler.HandlerInfo config) {
}
public void destroy() {
}
public javax.xml.namespace.QName[] getHeaders() {
return null;
}
}
| 6,981 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/hello/HelloBindingImpl.java | /**
* HelloBindingImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis WSDL2Java emitter.
*/
package samples.jaxrpc.hello;
public class HelloBindingImpl implements samples.jaxrpc.hello.Hello {
public java.lang.String sayHello(java.lang.String name) throws java.rmi.RemoteException {
return "A dynamic proxy hello to " + name + "!";
}
}
| 6,982 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/hello/ServerHandler.java | package samples.jaxrpc.hello;
public class ServerHandler implements javax.xml.rpc.handler.Handler {
public ServerHandler() {
}
public boolean handleRequest(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ServerHandler: In handleRequest");
return true;
}
public boolean handleResponse(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ServerHandler: In handleResponse");
return true;
}
public boolean handleFault(javax.xml.rpc.handler.MessageContext context) {
System.out.println("ServerHandler: In handleFault");
return true;
}
public void init(javax.xml.rpc.handler.HandlerInfo config) {
}
public void destroy() {
}
public javax.xml.namespace.QName[] getHeaders() {
return null;
}
}
| 6,983 |
0 | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc | Create_ds/axis-axis1-java/samples/jaxrpc-sample/src/main/java/samples/jaxrpc/hello/HelloClient.java | package samples.jaxrpc.hello;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.net.URL;
public class HelloClient {
public static void main(String[] args) throws Exception {
String UrlString = (args.length > 0 ? args[0] : "http://localhost:8080") + "/axis/services/HelloPort?wsdl";
String nameSpaceUri = "http://hello.jaxrpc.samples/";
String serviceName = "HelloWorld";
String portName = "HelloPort";
URL helloWsdlUrl = new URL(UrlString);
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service helloService = serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
java.util.List list = helloService.getHandlerRegistry().getHandlerChain(new QName(nameSpaceUri, portName));
list.add(new javax.xml.rpc.handler.HandlerInfo(ClientHandler.class,null,null));
Hello myProxy = (Hello) helloService.getPort(
new QName(nameSpaceUri, portName),
samples.jaxrpc.hello.Hello.class);
System.out.println(myProxy.sayHello("Buzz"));
}
}
| 6,984 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/test/java/test/functional/TestBidBuySample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import samples.bidbuy.TestClient;
/** Test the stock sample code.
*/
public class TestBidBuySample extends TestCase {
public void test () throws Exception {
String[] args = { "-p", System.getProperty("test.functional.ServicePort", "8080") };
TestClient.main(args);
}
}
| 6,985 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/v3.java | package samples.bidbuy ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.Vector;
public class v3 implements vInterface {
public void register(String registryURL, samples.bidbuy.Service s)
throws Exception {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(registryURL) );
call.setOperationName( new QName("http://www.soapinterop.org/Register", "Register" ));
call.addParameter("ServiceName", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("ServiceUrl", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("ServiceType", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("ServiceWSDL", XMLType.XSD_STRING, ParameterMode.IN);
call.invoke( new Object[] { s.getServiceName(), s.getServiceUrl(),
s.getServiceType(), s.getServiceWsdl() } );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public void unregister(String registryURL, String name) throws Exception {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(registryURL) );
call.setOperationName( new QName("http://www.soapinterop.org/Unregister", "Unregister" ));
call.addParameter( "ServiceName", XMLType.XSD_STRING, ParameterMode.IN);
call.invoke( new Object[] { name } );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public Boolean ping(String serverURL) throws Exception {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(serverURL) );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "http://www.soapinterop.org/Ping" );
call.setOperationName( new QName("http://www.soapinterop.org/Bid", "Ping" ));
call.invoke( (Object[]) null );
return( new Boolean(true) );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public Vector lookupAsString(String registryURL) throws Exception
{
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(registryURL) );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "http://www.soapinterop.org/LookupAsString" );
call.setOperationName( new QName("http://www.soapinterop.org/Registry", "LookupAsString" ));
call.addParameter( "ServiceType", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType( XMLType.XSD_DOUBLE );
String res= (String) call.invoke( new Object[] { "Bid" } );
if ( res == null ) return( null );
StringTokenizer lineParser = new StringTokenizer( res, "\n" );
Vector services = new Vector();
while ( lineParser.hasMoreTokens() ) {
String line = (String) lineParser.nextElement();
StringTokenizer wordParser = new StringTokenizer( line, "\t" );
samples.bidbuy.Service s = null ;
for ( int i = 0 ; wordParser.hasMoreTokens() && i < 4 ; i++ )
switch(i) {
case 0 : s = new samples.bidbuy.Service();
if ( services == null ) services = new Vector();
services.add( s );
s.setServiceName( (String) wordParser.nextToken());
break ;
case 1 : s.setServiceUrl( (String) wordParser.nextToken());
break ;
case 2 : s.setServiceType( (String) wordParser.nextToken());
break ;
case 3 : s.setServiceWsdl( (String) wordParser.nextToken());
break ;
}
}
return( services );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public double requestForQuote(String serverURL) throws Exception {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(serverURL) );
call.setOperationName(new QName("http://www.soapinterop.org/Bid", "RequestForQuote") );
call.setReturnType( XMLType.XSD_DOUBLE );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "http://www.soapinterop.org/RequestForQuote" );
call.addParameter( "ProductName", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter( "Quantity", XMLType.XSD_INT, ParameterMode.IN);
Object r = call.invoke( new Object[] { "widget", new Integer(10) } );
/*
sd.addOutputParam("RequestForQuoteResult",
SOAPTypeMappingRegistry.XSD_DOUBLE);
sd.addOutputParam("Result",
SOAPTypeMappingRegistry.XSD_DOUBLE);
sd.addOutputParam("return",
SOAPTypeMappingRegistry.XSD_DOUBLE);
*/
// ??? if ( r instanceof Float ) r = ((Float)r).toString();
if ( r instanceof String ) r = new Double((String) r);
Double res = (Double) r ;
return( res.doubleValue() );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public String simpleBuy(String serverURL, int quantity ) throws Exception {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(serverURL) );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "http://www.soapinterop.org/SimpleBuy" );
call.setOperationName( new QName("http://www.soapinterop.org/Bid", "SimpleBuy") );
call.setReturnType( XMLType.XSD_STRING );
call.addParameter( "Address", XMLType.XSD_STRING, ParameterMode.IN );
call.addParameter( "ProductName", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter( "Quantity", XMLType.XSD_INT, ParameterMode.IN );
String res = (String) call.invoke(new Object[] { "123 Main St.",
"Widget",
new Integer(quantity)});
/* sd.addOutputParam("SimpleBuyResult",
SOAPTypeMappingRegistry.XSD_STRING);
sd.addOutputParam("Result",
SOAPTypeMappingRegistry.XSD_STRING);
sd.addOutputParam("return",
SOAPTypeMappingRegistry.XSD_STRING); */
return( res );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
public String buy(String serverURL, int quantity, int numItems, double price)
throws Exception
{
try {
int i ;
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(serverURL) );
call.setUseSOAPAction( true );
call.setSOAPActionURI( "http://www.soapinterop.org/Buy" );
call.setReturnType( XMLType.XSD_STRING );
/* sd.addOutputParam("BuyResult",
SOAPTypeMappingRegistry.XSD_STRING);
sd.addOutputParam("Result",
SOAPTypeMappingRegistry.XSD_STRING);
sd.addOutputParam("return",
SOAPTypeMappingRegistry.XSD_STRING); */
// register the PurchaseOrder class
QName poqn = new QName("http://www.soapinterop.org/Bid", "PurchaseOrder");
Class cls = PurchaseOrder.class;
call.registerTypeMapping(cls, poqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
// register the Address class
QName aqn = new QName("http://www.soapinterop.org/Bid", "Address");
cls = Address.class;
call.registerTypeMapping(cls, aqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
// register the LineItem class
QName liqn = new QName("http://www.soapinterop.org/Bid", "LineItem");
cls = LineItem.class;
call.registerTypeMapping(cls, liqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
LineItem[] lineItems = new LineItem[numItems];
for ( i = 0 ; i < numItems ; i++ )
lineItems[i] = new LineItem("Widget"+i,quantity,new BigDecimal(price));
PurchaseOrder po = new PurchaseOrder( "PO1",
Calendar.getInstance(),
new Address("Mr Big",
"40 Wildwood Lane",
"Weston",
"CT",
"06883"),
new Address("Mr Big's Dad",
"40 Wildwood Lane",
"Weston",
"CT",
"06883"),
lineItems );
call.addParameter( "PO", poqn, ParameterMode.IN );
call.setOperationName( new QName("http://www.soapinterop.org/Bid", "Buy") );
String res = (String) call.invoke( new Object[] { po } );
return( res );
}
catch( Exception e ) {
e.printStackTrace();
throw e ;
}
}
}
| 6,986 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/PurchaseOrder.java | package samples.bidbuy;
import java.util.Calendar;
public class PurchaseOrder {
// constructors
public PurchaseOrder() {};
public PurchaseOrder(String id, Calendar createDate, Address shipTo,
Address billTo, LineItem[] items)
{
this.poID=id;
this.createDate=createDate;
this.shipTo=shipTo;
this.billTo=billTo;
this.items=items;
}
// properties
private String poID;
public String getPoID() { return poID; }
public void setPoID(String value) { poID=value; }
private Calendar createDate;
public Calendar getCreateDate() { return createDate; }
public void setCreateDate(Calendar value) { createDate=value; }
private Address shipTo;
public Address getShipTo() { return shipTo; }
public void setShipTo(Address value) { shipTo=value; }
private Address billTo;
public Address getBillTo() { return billTo; }
public void setBillTo(Address value) { billTo=value; }
private LineItem[] items;
public LineItem[] getItems() { return items; }
public void setItems(LineItem[] value) { items=value; }
}
| 6,987 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/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.bidbuy ;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.apache.axis.utils.Options;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
import java.util.Calendar;
/**
* Test Client for the echo interop service. See the main entrypoint
* for more details on usage.
*
* @author Sam Ruby <rubys@us.ibm.com>
*/
public class TestClient {
private static Service service = null ;
private static Call call = null;
/**
* Test an echo method. Declares success if the response returns
* true with an Object.equal comparison with the object to be sent.
* @param method name of the method to invoke
* @param toSend object of the correct type to be sent
*/
private static void test(String method, Object toSend) {
}
/**
* Main entry point. Tests a variety of echo methods and reports
* on their results.
*
* Arguments are of the form:
* -h localhost -p 8080 -s /soap/servlet/rpcrouter
*/
public static void main(String args[]) throws Exception {
// set up the call object
Options opts = new Options(args);
service = new Service();
call = (Call) service.createCall();
call.setTargetEndpointAddress( new URL(opts.getURL()) );
call.setUseSOAPAction(true);
call.setSOAPActionURI("http://www.soapinterop.org/Bid");
// register the PurchaseOrder class
QName poqn = new QName("http://www.soapinterop.org/Bid",
"PurchaseOrder");
Class cls = PurchaseOrder.class;
call.registerTypeMapping(cls, poqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
// register the Address class
QName aqn = new QName("http://www.soapinterop.org/Bid", "Address");
cls = Address.class;
call.registerTypeMapping(cls, aqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
// register the LineItem class
QName liqn = new QName("http://www.soapinterop.org/Bid", "LineItem");
cls = LineItem.class;
call.registerTypeMapping(cls, liqn, BeanSerializerFactory.class, BeanDeserializerFactory.class);
try {
// Default return type based on what we expect
call.setOperationName( new QName("http://www.soapinterop.org/Bid", "Buy" ));
call.addParameter( "PO", poqn, ParameterMode.IN );
call.setReturnType( XMLType.XSD_STRING );
LineItem[] li = new LineItem[2];
li[0] = new LineItem("Tricorder", 1, "2500.95");
li[1] = new LineItem("Phasor", 3, "7250.95");
PurchaseOrder po = new PurchaseOrder(
"NCC-1701",
Calendar.getInstance(),
new Address("Sam Ruby", "Home", "Raleigh", "NC", "27676"),
new Address("Lou Gerstner", "Work", "Armonk", "NY", "15222"),
li
);
// issue the request
String receipt = (String) call.invoke( new Object[] {po} );
System.out.println(receipt);
} catch (Exception e) {
System.out.println("Buy failed: " + e);
throw e;
}
}
}
| 6,988 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/LineItem.java | package samples.bidbuy;
import java.math.BigDecimal;
public class LineItem {
// constructors
public LineItem() {};
public LineItem(String name, int quantity, BigDecimal price) {
this.name=name;
this.quantity=quantity;
this.price=price;
}
public LineItem(String name, int quantity, String price) {
this.name=name;
this.quantity=quantity;
this.price=new BigDecimal(price);
}
// properties
private String name;
public String getName() { return name; }
public void setName(String value) { name=value; }
private int quantity;
public int getQuantity() { return quantity; }
public void setQuantity(int value) { quantity=value; }
private BigDecimal price;
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal value) { price=value; }
}
| 6,989 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/RegistryService.java | package samples.bidbuy;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class RegistryService {
private static Hashtable registry = new Hashtable();
/**
* Find a named service in a list
* @param list of services
* @param name to search for
* @return service found (or null)
*/
public RegistryService() {
load();
}
public void load() {
try {
FileInputStream fis = new FileInputStream("bid.reg");
ObjectInputStream ois = new ObjectInputStream( fis );
registry = (Hashtable) ois.readObject();
ois.close();
fis.close();
} catch(java.io.FileNotFoundException fnfe){
// nop
} catch(Exception e){
e.printStackTrace();
}
}
public void save() {
try {
FileOutputStream fos = new FileOutputStream("bid.reg");
ObjectOutputStream oos = new ObjectOutputStream( fos );
oos.writeObject( registry );
oos.close();
fos.close();
} catch(Exception e){
e.printStackTrace();
}
}
private Service find(Vector list, String name) {
Enumeration e = list.elements();
while (e.hasMoreElements()) {
Service s = (Service) e.nextElement();
if (s.getServiceName().equals(name)) return s;
}
return null;
}
/**
* Unregister a serivce
* @param server name
*/
public void Unregister(String name) {
Enumeration e1 = registry.keys();
while (e1.hasMoreElements()) {
Vector list = (Vector) registry.get(e1.nextElement());
Enumeration e2 = list.elements();
while (e2.hasMoreElements()) {
Service s = (Service) e2.nextElement();
if (s.getServiceName().equals(name)) {
list.remove(s);
save();
}
}
}
}
/**
* Register a new serivce
* @param server name
* @param url of endpoint
* @param stype
* @param wsdl
*/
public void Register(String name, String url, String stype, String wsdl) {
Vector list = (Vector)registry.get(stype);
if (list == null) registry.put(stype, list=new Vector());
Service service = find(list, name);
if (service==null)
list.add(service=new Service());
service.setServiceName(name);
service.setServiceUrl(url);
service.setServiceType(stype);
service.setServiceWsdl(wsdl);
save();
}
/**
* Return the current list of services as an array
* @param Service Name
* @return List of servers that implement that service
*/
public Service[] Lookup(String stype) {
if (!registry.containsKey(stype)) return new Service[] {};
Vector list = (Vector)registry.get(stype);
Service[] result = new Service[list.size()];
list.copyInto(result);
return result;
}
/*
* Return the current list of services as a string
*/
public String LookupAsString(String stype) {
Service[] services = Lookup(stype);
String result = "";
for (int i=0; i<services.length; i++) {
Service service = services[i];
result += service.getServiceName() + "\t" +
service.getServiceUrl() + "\t" +
service.getServiceType() + "\t" +
service.getServiceWsdl() + "\n";
}
return result;
}
}
| 6,990 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/Address.java | package samples.bidbuy;
public class Address {
// constructors
public Address() {};
public Address(String name, String address, String city, String state,
String zipCode)
{
this.name=name;
this.address=address;
this.city=city;
this.state=state;
this.zipCode=zipCode;
}
// properties
private String name;
public String getName() { return name; }
public void setName(String value) { name=value; }
private String address;
public String getAddress() { return address; }
public void setAddress(String value) { address=value; }
private String city;
public String getCity() { return city; }
public void setCity(String value) { city=value; }
private String state;
public String getState() { return state; }
public void setState(String value) { state=value; }
private String zipCode;
public String getZipCode() { return zipCode; }
public void setZipCode(String value) { zipCode=value; }
}
| 6,991 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/vInterface.java | package samples.bidbuy ;
import java.util.Vector;
public interface vInterface {
public void register(String registryURL, Service s) throws Exception ;
public void unregister(String registryURL, String name) throws Exception ;
public Boolean ping(String serverURL) throws Exception ;
public Vector lookupAsString(String registryURL) throws Exception ;
public double requestForQuote(String serverURL) throws Exception ;
public String simpleBuy(String serverURL, int quantity ) throws Exception ;
public String buy(String serverURL, int quantity, int numItems, double price)
throws Exception;
}
| 6,992 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/rfq.java | package samples.bidbuy ;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.Vector;
public class rfq extends JPanel {
private vInterface vv = new v3();
private String regServerURL = null ;
private TitledBorder regServerBorder = null ;
private JComboBox regServerList = null ;
private JButton removeButton = null ;
private JTable serverTable = null ;
private DefaultTableModel tableModel = null ;
private JPanel regListPanel = null ;
private JButton refreshButton = null ;
private JButton pingButton = null ;
private JButton selectAllButton = null ;
private JButton deselectAllButton = null ;
private JButton requestButton = null ;
private JButton registerButton = null ;
private JButton addServerButton = null ;
private JButton removeServerButton = null ;
private JButton unregisterServerButton = null ;
private JPanel purchasePanel = null ;
private JComboBox buyList = null ;
private JTextField tServer, tQuantity, tAddress ;
private JComboBox tNumItems ;
public boolean doAxis = true ;
private static int CHECK_COLUMN = 0 ;
private static int NAME_COLUMN = 1 ;
private static int URL_COLUMN = 2 ;
private static int TYPE_COLUMN = 3 ;
private static int WSDL_COLUMN = 4 ;
private static int STATE_COLUMN = 5 ;
private static int QUOTE_COLUMN = 6 ;
private static int NUM_COLUMNS = 7 ;
class MyTableModel extends DefaultTableModel {
public MyTableModel(Object[] obj, int x) { super( obj, x); }
public Class getColumnClass(int col) {
if ( col == CHECK_COLUMN ) return( Boolean.class );
return( super.getColumnClass(col) );
}
};
public rfq() {
setLayout( new BorderLayout() );
// Do the Registration Server list area
//////////////////////////////////////////////////////////////////////////
JPanel regSelectPanel = new JPanel();
regSelectPanel.setLayout( new BoxLayout(regSelectPanel, BoxLayout.X_AXIS) );
regSelectPanel.setBorder( new EmptyBorder(5,5,5,5) );
regSelectPanel.add( new JLabel( "Registration Server: " ) );
regSelectPanel.add( regServerList = new JComboBox() );
regSelectPanel.add( Box.createRigidArea(new Dimension(5,0)) );
regSelectPanel.add( removeButton = new JButton("Remove") );
loadRegList();
regServerList.setEditable( true );
regServerList.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
String act = event.getActionCommand();
if ( act.equals( "comboBoxChanged" ) ) {
String name = (String) regServerList.getSelectedItem();
if ( name != null && !name.equals("") ) {
chooseRegServer( name );
addRegistrationServer( name );
}
else
clearTable();
}
};
});
removeButton.setEnabled( true );
removeButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Remove".equals(event.getActionCommand()) ) {
String name = (String) regServerList.getSelectedItem();
regServerList.removeItem( name );
saveRegList();
}
};
});
add( regSelectPanel, BorderLayout.NORTH );
// Do the List Of Registration Servers Table
//////////////////////////////////////////////////////////////////////////
regListPanel = new JPanel();
regListPanel.setLayout( new BorderLayout() );
regServerBorder = new TitledBorder(" Product Servers ");
regListPanel.setBorder( regServerBorder );
regListPanel.add( new JLabel( "Select the servers you want to request " +
"a price from:"), BorderLayout.NORTH );
tableModel = new MyTableModel( new Object[] {"", "Name", "URL", "Type",
"WSDL", "State", "Quote",
""}, 0 );
serverTable = new JTable( 0, NUM_COLUMNS );
serverTable.setModel( tableModel );
serverTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
TableColumn col = serverTable.getColumnModel().getColumn(CHECK_COLUMN);
col.setMaxWidth( 10 );
// col = serverTable.getColumnModel().getColumn(STATE_COLUMN);
// col.setMaxWidth( col.getPreferredWidth()/2 );
// col = serverTable.getColumnModel().getColumn(QUOTE_COLUMN);
// col.setMaxWidth( col.getPreferredWidth()/2 );
col = serverTable.getColumnModel().getColumn(TYPE_COLUMN);
col.setMaxWidth( col.getPreferredWidth()/2 );
tableModel.addTableModelListener( new TableModelListener() {
public void tableChanged(TableModelEvent event) {
int type = event.getType();
if ( type == TableModelEvent.UPDATE && event.getColumn() == 0 )
enableButtons();
};
});
regListPanel.add( new JScrollPane(serverTable), BorderLayout.CENTER );
JPanel btns = new JPanel();
// btns.setLayout( new BoxLayout( btns, BoxLayout.X_AXIS ) );
btns.setLayout( new GridBagLayout() );
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
c.fill = GridBagConstraints.HORIZONTAL ;
// row 1
btns.add( refreshButton = new JButton( "Refresh List" ), c );
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
btns.add( selectAllButton = new JButton( "Select All" ), c );
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
btns.add( requestButton = new JButton( "Request RFQs" ), c );
c.weightx = 1.0 ;
btns.add( Box.createHorizontalGlue(), c );
c.weightx = 0.0 ;
btns.add( registerButton = new JButton( "Register Server" ), c );
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
c.gridwidth = GridBagConstraints.REMAINDER ;
btns.add( addServerButton = new JButton( "Add Bid Server" ), c );
// row 2
c.gridwidth = 1 ;
c.gridx = 2 ;
btns.add( deselectAllButton = new JButton( "Deselect All" ), c );
c.gridx = GridBagConstraints.RELATIVE ;
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
btns.add( pingButton = new JButton( "Ping" ), c );
c.weightx = 1.0 ;
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
c.weightx = 0.0 ;
btns.add( unregisterServerButton = new JButton( "Unregister Server" ), c );
btns.add( Box.createRigidArea(new Dimension(5,0)), c );
// btns.add( Box.createRigidArea(new Dimension(5,0)), c );
c.gridwidth = GridBagConstraints.REMAINDER ;
btns.add( removeServerButton = new JButton( "Remove Server" ), c );
regListPanel.add( btns, BorderLayout.SOUTH );
refreshButton.setEnabled( false );
refreshButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Refresh List".equals(event.getActionCommand()) ) {
refreshList();
}
};
});
selectAllButton.setEnabled( false );
selectAllButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Select All".equals(event.getActionCommand()) ) {
for ( int i = 0 ; i < tableModel.getRowCount() ; i++ ){
tableModel.setValueAt(new Boolean(true),i,CHECK_COLUMN);
}
}
};
});
deselectAllButton.setEnabled( false );
deselectAllButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Deselect All".equals(event.getActionCommand()) ) {
for ( int i = 0 ; i < tableModel.getRowCount() ; i++ ){
tableModel.setValueAt(new Boolean(false),i,CHECK_COLUMN);
}
}
};
});
pingButton.setEnabled( false );
pingButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Ping".equals(event.getActionCommand()) ) {
ping();
}
};
});
requestButton.setEnabled( false );
requestButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Request RFQs".equals(event.getActionCommand()) ) {
requestRFQs();
}
};
});
registerButton.setEnabled( false );
registerButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Register Server".equals(event.getActionCommand()) )
registerNewServer();
};
});
addServerButton.setEnabled( true );
addServerButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Add Bid Server".equals(event.getActionCommand()) )
promptForServer();
};
});
removeServerButton.setEnabled( false );
removeServerButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Remove Server".equals(event.getActionCommand()) )
removeServers();
};
});
unregisterServerButton.setEnabled( false );
unregisterServerButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Unregister Server".equals(event.getActionCommand()) )
unregisterServer();
};
});
// Purchase data
//////////////////////////////////////////////////////////////////////////
GridBagLayout layout = new GridBagLayout();
// GridBagConstraints c = new GridBagConstraints();
c = new GridBagConstraints();
purchasePanel = new JPanel(layout);
purchasePanel.setBorder( new TitledBorder("Purchase") );
JButton tSimpleBuy ;
JButton tPOBuy ;
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
purchasePanel.add( new JLabel("Select the purchase server from the " +
"combo box" ),c );
c.anchor = GridBagConstraints.EAST ;
c.gridwidth = 1 ;
purchasePanel.add( new JLabel("Server:"), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
purchasePanel.add( buyList = new JComboBox(), c );
c.gridwidth = 1 ;
c.anchor = GridBagConstraints.EAST ;
purchasePanel.add( new JLabel("Quantity:"),c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
purchasePanel.add( tQuantity = new JTextField(6), c );
tQuantity.setText("1");
c.anchor = GridBagConstraints.EAST ;
c.gridwidth = 1 ;
purchasePanel.add( new JLabel("# Line Items:"),c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
purchasePanel.add( tNumItems = new JComboBox(), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
purchasePanel.add( tSimpleBuy = new JButton( "Simple Buy" ) );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
purchasePanel.add( tPOBuy = new JButton( "PO Buy" ) );
for ( int j = 1 ; j < 20 ; j++ )
tNumItems.addItem( ""+j );
tSimpleBuy.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Simple Buy".equals(event.getActionCommand()) ) {
simpleBuy();
}
};
});
tPOBuy.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "PO Buy".equals(event.getActionCommand()) ) {
poBuy();
}
};
});
JSplitPane splitPane = new JSplitPane( 0, regListPanel,
new JScrollPane(purchasePanel));
add( splitPane, BorderLayout.CENTER );
setSize(getPreferredSize());
splitPane.setDividerLocation( 200 );
purchasePanel.setEnabled( false );
}
public void addRegistrationServer( String name ) {
int count, i ;
if ( name == null || "".equals(name) ) return ;
count = regServerList.getItemCount();
for ( i = 0 ; i < count ; i++ )
if ( name.equals( regServerList.getItemAt(i) ) ) return ;
regServerList.addItem( name );
saveRegList();
}
public void chooseRegServer(String name) {
regServerURL = name ;
regServerBorder.setTitle( " Product Servers at ' " + name + " ' " );
regListPanel.repaint();
refreshList();
}
public void enableButtons() {
boolean flag ;
int i ;
int total = tableModel.getRowCount();
int count = 0 ;
for ( i = 0 ; i < total ; i++ ) {
flag = ((Boolean)tableModel.getValueAt(i,CHECK_COLUMN)).booleanValue();
if ( flag ) count++ ;
}
selectAllButton.setEnabled( total > 0 && count != total );
deselectAllButton.setEnabled( total > 0 && count > 0 );
pingButton.setEnabled( count > 0 );
requestButton.setEnabled( count > 0 );
removeServerButton.setEnabled( count > 0 );
unregisterServerButton.setEnabled( count > 0 );
}
public void clearTable() {
while ( tableModel.getRowCount() > 0 )
tableModel.removeRow(0);
enableButtons();
}
public void refreshList() {
clearTable();
Vector services = null ;
try {
services = vv.lookupAsString(regServerURL);
}
catch( Exception e ) {
System.err.println("---------------------------------------------");
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
for ( int i = 0 ; services != null && i < services.size() ; i++ ) {
Service s = (Service) services.elementAt(i);
addServer( s );
}
buyList.removeAllItems();
purchasePanel.setEnabled( false );
refreshButton.setEnabled( true );
registerButton.setEnabled( true );
enableButtons();
}
public void ping() {
Boolean flag ;
int i;
for ( i = 0 ; i < tableModel.getRowCount() ; i++ ) {
flag = (Boolean) tableModel.getValueAt( i, CHECK_COLUMN );
if ( flag.booleanValue() ) {
String url = (String) tableModel.getValueAt( i, URL_COLUMN );
Boolean value = new Boolean(false);
try {
value = vv.ping( url );
tableModel.setValueAt( value.booleanValue() ? "Alive" : "Down",
i, STATE_COLUMN );
serverTable.repaint();
}
catch( Exception e ) {
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
}
}
public void unregisterServer() {
Boolean flag ;
int i;
for ( i = 0 ; i < tableModel.getRowCount() ; i++ ) {
flag = (Boolean) tableModel.getValueAt( i, CHECK_COLUMN );
if ( flag.booleanValue() ) {
String name = (String) tableModel.getValueAt( i, NAME_COLUMN );
String regServer = (String) regServerList.getSelectedItem() ;
Boolean value = new Boolean(false);
try {
vv.unregister( regServer, name);
}
catch( Exception e ) {
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
}
refreshList();
}
public void requestRFQs() {
Boolean flag ;
int i, j;
// buyList.removeAllItems();
for ( i = 0 ; i < tableModel.getRowCount() ; i++ ) {
flag = (Boolean) tableModel.getValueAt( i, CHECK_COLUMN );
if ( flag.booleanValue() ) {
String url = (String) tableModel.getValueAt( i, URL_COLUMN );
double value = 0.0 ;
try {
value = vv.requestForQuote( url );
tableModel.setValueAt( new Double(value), i, QUOTE_COLUMN );
serverTable.repaint();
String str = (String) tableModel.getValueAt(i, NAME_COLUMN);
for ( j = 0 ; j < buyList.getItemCount(); j++ )
if ( ((String)buyList.getItemAt(j)).equals(str) ) break ;
if ( j == buyList.getItemCount() )
buyList.addItem( str );
}
catch( Exception e ) {
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
}
// buyList.setSelectedIndex(-1);
purchasePanel.setEnabled( true );
}
public void removeServers() {
Boolean flag ;
int i, j;
for ( i = tableModel.getRowCount()-1 ; i >= 0 ; i-- ) {
flag = (Boolean) tableModel.getValueAt( i, CHECK_COLUMN );
if ( flag.booleanValue() )
tableModel.removeRow( i );
}
enableButtons();
}
public void simpleBuy() {
try {
String url = null ;
int total = tableModel.getRowCount();
String name = (String) buyList.getSelectedItem();
for ( int i = 0 ; i < total ; i++ ) {
String val = (String) tableModel.getValueAt(i, NAME_COLUMN) ;
if ( val.equals(name) ) {
url = (String) tableModel.getValueAt(i, URL_COLUMN);
break ;
}
}
String address = "123 Main Street, Any Town, USA" ;
String product = "soap" ;
int quantity = Integer.parseInt((String) tQuantity.getText());
String value = null ;
value = vv.simpleBuy( url, quantity );
JOptionPane.showMessageDialog(this, value, "Receipt",
JOptionPane.INFORMATION_MESSAGE );
}
catch( Exception e ) {
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
public void poBuy() {
try {
String url = null ;
int total = tableModel.getRowCount();
String name = (String) buyList.getSelectedItem();
double price = 0 ;
for ( int i = 0 ; i < total ; i++ ) {
String val = (String) tableModel.getValueAt(i, NAME_COLUMN) ;
Double dval ;
if ( val.equals(name) ) {
url = (String) tableModel.getValueAt(i, URL_COLUMN);
dval = (Double) tableModel.getValueAt(i, QUOTE_COLUMN);
price = dval.doubleValue();
break ;
}
}
// String address = (String) tAddress.getText();
String product = "soap" ;
int quantity = Integer.parseInt((String) tQuantity.getText());
int numItems = Integer.parseInt((String) tNumItems.getSelectedItem());
String value = null ;
value = vv.buy( url, quantity, numItems, price );
JOptionPane.showMessageDialog(this, value, "Receipt",
JOptionPane.INFORMATION_MESSAGE );
}
catch( Exception e ) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
public void registerNewServer() {
Component parent = this ;
while ( parent != null && !(parent instanceof JFrame) )
parent = parent.getParent();
final JDialog j = new JDialog((JFrame)parent, "Register Server", true );
Container pane = j.getContentPane();
final JTextField fName = new JTextField(20),
fURL = new JTextField(20),
fType = new JTextField(20),
fWsdl = new JTextField(20);
JButton regButton, cancelButton ;
pane.setLayout( new GridBagLayout() );
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service Name" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fName, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service URL" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fURL, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service Type" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fType, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "WSDL URL" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fWsdl, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( regButton = new JButton( "Register" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( Box.createHorizontalStrut(3), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( cancelButton = new JButton( "Cancel" ), c );
fType.setText( "Bid" );
regButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Register".equals(event.getActionCommand()) ) {
Service s = new Service();
s.setServiceName( fName.getText() );
s.setServiceUrl( fURL.getText() );
s.setServiceType( fType.getText() );
s.setServiceWsdl( fWsdl.getText() );
register( s );
j.dispose();
}
};
});
cancelButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Cancel".equals(event.getActionCommand()) ) {
j.dispose();
}
};
});
j.pack();
Point p = new Point( parent.getLocation() );
Dimension d = parent.getSize();
p.setLocation( (int)(p.getX() + d.getWidth()/2),
(int)(p.getY() + d.getHeight()/2) );
d = j.getSize();
j.setLocation( (int)(p.getX() - d.getWidth()/2),
(int)(p.getY() - d.getHeight()/2) );
j.show();
}
public void promptForServer() {
Component parent = this ;
while ( parent != null && !(parent instanceof JFrame) )
parent = parent.getParent();
final JDialog j = new JDialog((JFrame)parent, "Add Bid Server", true );
Container pane = j.getContentPane();
final JTextField fName = new JTextField(20),
fURL = new JTextField(20),
fType = new JTextField(20),
fWsdl = new JTextField(20);
JButton addButton, cancelButton ;
pane.setLayout( new GridBagLayout() );
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service Name" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fName, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service URL" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fURL, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "Service Type" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fType, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( new JLabel( "WSDL URL" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = GridBagConstraints.REMAINDER ;
pane.add( fWsdl, c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( addButton = new JButton( "Add" ), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( Box.createHorizontalStrut(3), c );
c.anchor = GridBagConstraints.WEST ;
c.gridwidth = 1 ;
pane.add( cancelButton = new JButton( "Cancel" ), c );
fType.setText( "Bid" );
addButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Add".equals(event.getActionCommand()) ) {
Service s = new Service();
s.setServiceName( fName.getText() );
s.setServiceUrl( fURL.getText() );
s.setServiceType( fType.getText() );
s.setServiceWsdl( fWsdl.getText() );
addServer( s );
j.dispose();
}
};
});
cancelButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
if ( "Cancel".equals(event.getActionCommand()) ) {
j.dispose();
}
};
});
j.pack();
Point p = new Point( parent.getLocation() );
Dimension d = parent.getSize();
p.setLocation( (int)(p.getX() + d.getWidth()/2),
(int)(p.getY() + d.getHeight()/2) );
d = j.getSize();
j.setLocation( (int)(p.getX() - d.getWidth()/2),
(int)(p.getY() - d.getHeight()/2) );
j.show();
}
public void addServer(Service s) {
Object[] objs = new Object[NUM_COLUMNS] ;
objs[0] = new Boolean(false);
objs[1] = s.getServiceName();
objs[2] = s.getServiceUrl();
objs[3] = s.getServiceType();
objs[4] = s.getServiceWsdl();
objs[5] = null ;
objs[6] = null ;
tableModel.addRow( objs );
}
public void register(Service s) {
try {
vv.register( (String) regServerList.getSelectedItem(), s );
refreshList();
}
catch( Exception e ) {
JOptionPane.showMessageDialog(this, e.toString(), "Error",
JOptionPane.INFORMATION_MESSAGE );
}
}
public void loadRegList() {
try {
FileReader fr = new FileReader( "reg.lst" );
LineNumberReader lnr = new LineNumberReader( fr );
String line = null ;
while ( (line = lnr.readLine()) != null )
addRegistrationServer( line );
fr.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
public void saveRegList() {
try {
FileOutputStream fos = new FileOutputStream( "reg.lst" );
PrintWriter pw = new PrintWriter( fos );
int count = regServerList.getItemCount();
int i ;
for ( i = 0 ; i < count ; i++ )
pw.println( (String) regServerList.getItemAt(i) );
pw.close();
fos.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame window = new JFrame("Request For Quote Client") {
protected void processWindowEvent(WindowEvent event) {
switch( event.getID() ) {
case WindowEvent.WINDOW_CLOSING: exit();
break ;
default: super.processWindowEvent(event);
break ;
}
}
private void exit() {
System.exit(0);
}
};
window.getContentPane().add( new rfq() );
window.pack();
window.setSize( new Dimension(800, 500) );
window.setVisible( true );
}
catch( Throwable exp ) {
exp.printStackTrace();
}
}
}
| 6,993 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/Service.java | package samples.bidbuy ;
public class Service implements java.io.Serializable {
private String ServiceName;
private String ServiceUrl;
private String ServiceType;
private String ServiceWsdl;
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String value) {
ServiceName = value;
}
public String getServiceUrl() {
return ServiceUrl;
}
public void setServiceUrl(String value) {
ServiceUrl = value;
}
public String getServiceType() {
return ServiceType;
}
public void setServiceType(String value) {
ServiceType = value;
}
public String getServiceWsdl() {
return ServiceWsdl;
}
public void setServiceWsdl(String value) {
ServiceWsdl = value;
}
}
| 6,994 |
0 | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/bidbuy-sample/src/main/java/samples/bidbuy/BidService.java | package samples.bidbuy;
/**
* Big/PurchaseOrder Service
*/
public class BidService {
static int nextReceiptNumber = 9000;
/**
* Request a quote for a given quantity of a specified product
* @param productName name of product
* @param quantity number desired
* @return Total amount in US$ for complete purchase
*/
public double RequestForQuote(String productName, int quantity) {
if (quantity < 100) {
return 1.0 * quantity;
} if (quantity < 1000) {
return 0.8 * quantity;
} else {
return 0.7 * quantity;
}
}
/**
* Purchase a given quantity of a specified product
* @param productName name of product
* @param quantity number desired
* @param price desired price (!!!)
* @param customerId who you are
* @param shipTo where you want the goods to go
* @param date where you want the goods to go
* @return Receipt
*/
public String SimpleBuy(String productName, String address, int quantity) {
return Integer.toString(nextReceiptNumber++) + "\n" +
quantity + " " + productName;
}
/**
* Process a purchase order.
* @return Receipt
*/
public String Buy(PurchaseOrder PO) {
String receipt = Integer.toString(nextReceiptNumber++);
for (int i=0; i<PO.getItems().length; i++) {
LineItem item = PO.getItems()[i];
receipt += "\n " + item.getQuantity() + " " + item.getName();
}
return receipt;
}
/**
* Let the world know that we are still alive...
*/
public void Ping() {
}
}
| 6,995 |
0 | Create_ds/axis-axis1-java/samples/echo-sample/src/test/java/test | Create_ds/axis-axis1-java/samples/echo-sample/src/test/java/test/functional/TestEchoSample.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.functional;
import junit.framework.TestCase;
import org.apache.axis.client.AdminClient;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import samples.echo.TestClient;
/** Test the stock sample code.
*/
public class TestEchoSample extends TestCase {
static Log log =
LogFactory.getLog(TestEchoSample.class.getName());
public TestEchoSample(String name) {
super(name);
}
public static void main(String args[]) throws Exception {
TestEchoSample tester = new TestEchoSample("tester");
tester.testEchoService();
}
public void testEchoService () throws Exception {
log.info("Testing echo interop sample.");
// deploy the echo service
String[] args = {"-l",
"local:///AdminService",
"src/main/wsdd/deploy.wsdd"};
AdminClient.main(args);
// define the tests using JUnit assert facilities, and tell client to
// throw any exceptions it catches.
TestClient client = new TestClient(true) {
public void verify(String method, Object sent, Object gotBack) {
assertTrue("What was sent was not received--" + method + ": " + gotBack, equals(sent, gotBack));
}
};
// run the tests using a local (in process) server
client.setURL("local:");
client.executeAll();
log.info("Test complete.");
}
}
| 6,996 |
0 | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples/echo/echoHeaderStructHandler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.echo;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
/** This handler processes the SOAP header "echoMeStruct" defined in the
* SOAPBuilder Round2C interop tests.
*
* <p>Essentially, you install it on both the request and response chains of
* your service, on the server side.</p>
*
* @author Simon Fell (simon@zaks.demon.co.uk)
*/
public class echoHeaderStructHandler extends BasicHandler
{
static Log log =
LogFactory.getLog(echoHeaderStringHandler.class.getName());
public static final String ECHOHEADER_STRUCT_ID = "echoHeaderStructHandler.id";
public static final String HEADER_NS = "http://soapinterop.org/echoheader/";
public static final String HEADER_REQNAME = "echoMeStructRequest";
public static final String HEADER_RESNAME = "echoMeStructResponse";
public static final String ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next";
public static final String STRUCT_NS = "http://soapinterop.org/xsd" ;
public static final String STRUCT_NAME = "SOAPStruct";
public static final QName SOAPStructType = new QName(STRUCT_NS, STRUCT_NAME);
public boolean canHandleBlock(QName qname) {
if (HEADER_NS.equals(qname.getNamespaceURI()) &&
HEADER_REQNAME.equals(qname.getLocalPart())) {
return true;
}
return false;
}
/**
* Process a MessageContext.
*/
public void invoke(MessageContext context) throws AxisFault
{
if (context.getPastPivot()) {
// This is a response. Add the response header, if we saw
// the requestHeader
SOAPStruct hdrVal= (SOAPStruct)context.getProperty(ECHOHEADER_STRUCT_ID);
if (hdrVal == null)
return;
Message msg = context.getResponseMessage();
if (msg == null)
return;
SOAPEnvelope env = msg.getSOAPEnvelope();
SOAPHeaderElement header = new SOAPHeaderElement(HEADER_NS,
HEADER_RESNAME,
hdrVal);
env.addHeader(header);
} else {
// Request. look for the header
Message msg = context.getRequestMessage();
if (msg == null)
throw new AxisFault(Messages.getMessage("noRequest00"));
SOAPEnvelope env = msg.getSOAPEnvelope();
SOAPHeaderElement header = env.getHeaderByName(HEADER_NS,
HEADER_REQNAME);
if (header != null) {
// seems Axis has already ignored any headers not tageted
// at us
SOAPStruct hdrVal ;
// header.getValue() doesn't seem to be connected to anything
// we always get null.
try {
hdrVal = (SOAPStruct)header.getValueAsType(SOAPStructType);
} catch (Exception e) {
throw AxisFault.makeFault(e);
}
context.setProperty(ECHOHEADER_STRUCT_ID, hdrVal) ;
header.setProcessed(true);
}
}
}
}
| 6,997 |
0 | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples/echo/echoHeaderStringHandler.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.echo;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.utils.Messages;
import org.apache.commons.logging.Log;
import javax.xml.namespace.QName;
/** This handler processes the SOAP header "echoMeString" defined in the
* SOAPBuilder Round2C interop tests.
*
* <p>Essentially, you install it on both the request and response chains of
* your service, on the server side.</p>
*
* @author Simon Fell (simon@zaks.demon.co.uk)
*/
public class echoHeaderStringHandler extends BasicHandler
{
static Log log =
LogFactory.getLog(echoHeaderStringHandler.class.getName());
public static final String ECHOHEADER_STRING_ID = "echoHeaderStringHandler.id";
public static final String HEADER_NS = "http://soapinterop.org/echoheader/";
public static final String HEADER_REQNAME = "echoMeStringRequest";
public static final String HEADER_RESNAME = "echoMeStringResponse";
public static final String ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next";
public boolean canHandleBlock(QName qname) {
if (HEADER_NS.equals(qname.getNamespaceURI()) &&
HEADER_REQNAME.equals(qname.getLocalPart())) {
return true;
}
return false;
}
/**
* Process a MessageContext.
*/
public void invoke(MessageContext context) throws AxisFault
{
if (context.getPastPivot()) {
// This is a response. Add the response header, if we saw
// the requestHeader
String strVal = (String)context.getProperty(ECHOHEADER_STRING_ID);
if (strVal == null)
return;
Message msg = context.getResponseMessage();
if (msg == null)
return;
SOAPEnvelope env = msg.getSOAPEnvelope();
SOAPHeaderElement header = new SOAPHeaderElement(HEADER_NS,
HEADER_RESNAME,
strVal);
env.addHeader(header);
} else {
// Request. look for the header
Message msg = context.getRequestMessage();
if (msg == null)
throw new AxisFault(Messages.getMessage("noRequest00"));
SOAPEnvelope env = msg.getSOAPEnvelope();
SOAPHeaderElement header = env.getHeaderByName(HEADER_NS,
HEADER_REQNAME);
if (header != null) {
// seems Axis has already ignored any headers not tageted
// at us
String strVal ;
// header.getValue() doesn't seem to be connected to anything
// we always get null.
try {
strVal = (String)header.getValueAsType(Constants.XSD_STRING);
} catch (Exception e) {
throw AxisFault.makeFault(e);
}
context.setProperty(ECHOHEADER_STRING_ID, strVal) ;
header.setProcessed(true);
}
}
}
}
| 6,998 |
0 | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples | Create_ds/axis-axis1-java/samples/echo-sample/src/main/java/samples/echo/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.echo ;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Stub;
import org.apache.axis.types.HexBinary;
import org.apache.axis.types.NegativeInteger;
import org.apache.axis.types.NonNegativeInteger;
import org.apache.axis.types.NonPositiveInteger;
import org.apache.axis.types.NormalizedString;
import org.apache.axis.types.PositiveInteger;
import org.apache.axis.types.Token;
import org.apache.axis.types.UnsignedByte;
import org.apache.axis.types.UnsignedInt;
import org.apache.axis.types.UnsignedLong;
import org.apache.axis.types.UnsignedShort;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Options;
import javax.xml.rpc.holders.FloatHolder;
import javax.xml.rpc.holders.IntHolder;
import javax.xml.rpc.holders.StringHolder;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
/**
* Test Client for the echo interop service. See the main entrypoint
* for more details on usage.
*
* @author Sam Ruby <rubys@us.ibm.com>
* Modified to use WSDL2Java generated stubs and artifacts by
* @author Rich Scheuerle <scheu@us.ibm.com>
*/
public abstract class TestClient {
private static InteropTestPortType binding = null;
/**
* When testMode is true, we throw exceptions up to the caller
* instead of recording them and continuing.
*/
private boolean testMode = false;
public TestClient() {
}
/**
* Constructor which sets testMode
*/
public TestClient(boolean testMode) {
this.testMode = testMode;
}
/**
* Determine if two objects are equal. Handles nulls and recursively
* verifies arrays are equal. Accepts dates within a tolerance of
* 999 milliseconds.
*/
protected boolean equals(Object obj1, Object obj2) {
if (obj1 == null || obj2 == null) return (obj1 == obj2);
if (obj1.equals(obj2)) return true;
// For comparison purposes, get the array of bytes representing
// the HexBinary object.
if (obj1 instanceof HexBinary) {
obj1 = ((HexBinary) obj1).getBytes();
}
if (obj2 instanceof HexBinary) {
obj2 = ((HexBinary) obj2).getBytes();
}
if (obj1 instanceof Calendar && obj2 instanceof Calendar) {
if (Math.abs(((Calendar)obj1).getTime().getTime() - ((Calendar)obj2).getTime().getTime()) < 1000) {
return true;
}
}
if ((obj1 instanceof Map) && (obj2 instanceof Map)) {
Map map1 = (Map)obj1;
Map map2 = (Map)obj2;
Set keys1 = map1.keySet();
Set keys2 = map2.keySet();
if (!(keys1.equals(keys2))) return false;
// Check map1 is a subset of map2.
Iterator i = keys1.iterator();
while (i.hasNext()) {
Object key = i.next();
if (!equals(map1.get(key), map2.get(key)))
return false;
}
// Check map2 is a subset of map1.
Iterator j = keys2.iterator();
while (j.hasNext()) {
Object key = j.next();
if (!equals(map1.get(key), map2.get(key)))
return false;
}
return true;
}
if (obj1 instanceof List)
obj1 = JavaUtils.convert(obj1, Object[].class);
if (obj2 instanceof List)
obj2 = JavaUtils.convert(obj2, Object[].class);
if (!obj2.getClass().isArray()) return false;
if (!obj1.getClass().isArray()) return false;
if (Array.getLength(obj1) != Array.getLength(obj2)) return false;
for (int i=0; i<Array.getLength(obj1); i++)
if (!equals(Array.get(obj1,i),Array.get(obj2,i))) return false;
return true;
}
/**
* Set up the call object.
*/
public void setURL(String url)
throws AxisFault
{
try {
binding = new InteropTestServiceLocator().
getecho(new java.net.URL(url));
// safety first
((InteropTestSoapBindingStub)binding).setTimeout(60000);
((InteropTestSoapBindingStub)binding).setMaintainSession(true);
} catch (Exception exp) {
throw AxisFault.makeFault(exp);
}
}
void setUser(String user) {
((Stub)binding).setUsername(user);
}
void setPassword(String password) {
((Stub)binding).setPassword(password);
}
/**
* Execute all tests.
*/
public void executeAll() throws Exception {
execute2A();
execute2B();
executeAxisXSD();
}
/**
* Test custom mapping of xsd types not standardized: xsd:token and
* xsd:normalizedString.
*/
public void executeAxisXSD() throws Exception {
Object output = null;
// Test xsd:token
Token tInput = new Token("abccdefg");
try {
output = binding.echoToken(tInput);
verify("echoToken", tInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoToken", tInput, e);
} else {
throw e;
}
}
// Test xsd:normalizedString
NormalizedString nsInput = new NormalizedString("abccdefg");
try {
output = binding.echoNormalizedString(nsInput);
verify("echoNormalizedString", nsInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNormalizedString", nsInput, e);
} else {
throw e;
}
}
// Test xsd:unsignedLong
UnsignedLong ulInput = new UnsignedLong(100);
try {
output = binding.echoUnsignedLong(ulInput);
verify("echoUnsignedLong", ulInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoUnsignedLong", ulInput, e);
} else {
throw e;
}
}
// Test xsd:unsignedInt
UnsignedInt uiInput = new UnsignedInt(101);
try {
output = binding.echoUnsignedInt(uiInput);
verify("echoUnsignedInt", uiInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoUnsignedInt", uiInput, e);
} else {
throw e;
}
}
// Test xsd:unsignedShort
UnsignedShort usInput = new UnsignedShort(102);
try {
output = binding.echoUnsignedShort(usInput);
verify("echoUnsignedShort", usInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoUnsignedShort", usInput, e);
} else {
throw e;
}
}
// Test xsd:unsignedByte
UnsignedByte ubInput = new UnsignedByte(103);
try {
output = binding.echoUnsignedByte(ubInput);
verify("echoUnsignedByte", ubInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoUnsignedByte", ubInput, e);
} else {
throw e;
}
}
// Test xsd:nonNegativeInteger
NonNegativeInteger nniInput = new NonNegativeInteger("12345678901234567890");
try {
output = binding.echoNonNegativeInteger(nniInput);
verify("echoNonNegativeInteger", nniInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNonNegativeInteger", nniInput, e);
} else {
throw e;
}
}
// Test xsd:positiveInteger
PositiveInteger piInput = new PositiveInteger("12345678901234567890");
try {
output = binding.echoPositiveInteger(piInput);
verify("echoPositiveInteger", piInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoPositiveInteger", piInput, e);
} else {
throw e;
}
}
// Test xsd:nonPositiveInteger
NonPositiveInteger npiInput = new NonPositiveInteger("-12345678901234567890");
try {
output = binding.echoNonPositiveInteger(npiInput);
verify("echoNonPositiveInteger", npiInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNonPositiveInteger", npiInput, e);
} else {
throw e;
}
}
// Test xsd:negativeInteger
NegativeInteger niInput = new NegativeInteger("-12345678901234567890");
try {
output = binding.echoNegativeInteger(niInput);
verify("echoNegativeInteger", niInput, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNegativeInteger", niInput, e);
} else {
throw e;
}
}
}
/**
* Execute the 2A tests
*/
public void execute2A() throws Exception {
// execute the tests
Object output = null;
{
String input = "abccdefg";
try {
output = binding.echoString(input);
verify("echoString", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoString", input, e);
} else {
throw e;
}
}
}
{
String[] input = new String[] {"abc", "def"};
try {
output = binding.echoStringArray(input);
verify("echoStringArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoStringArray", input, e);
} else {
throw e;
}
}
}
{
Integer input = new Integer(42);
try {
output = new Integer( binding.echoInteger(input.intValue()));
verify("echoInteger", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoInteger", input, e);
} else {
throw e;
}
}
}
{
int[] input = new int[] {42};
try {
output = binding.echoIntegerArray(input);
verify("echoIntegerArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoIntegerArray", input, e);
} else {
throw e;
}
}
}
{
Float input = new Float(3.7F);
try {
output = new Float(binding.echoFloat(input.floatValue()));
verify("echoFloat", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoFloat", input, e);
} else {
throw e;
}
}
}
{
float[] input = new float[] {3.7F, 7F};
try {
output = binding.echoFloatArray(input);
verify("echoFloatArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoFloatArray", input, e);
} else {
throw e;
}
}
}
{
SOAPStruct input = new SOAPStruct();
input.setVarInt(5);
input.setVarString("Hello");
input.setVarFloat(103F);
try {
output = binding.echoStruct(input);
verify("echoStruct", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoStruct", input, e);
} else {
throw e;
}
}
}
{
SOAPStruct[] input = new SOAPStruct[] {
new SOAPStruct(),
new SOAPStruct(),
new SOAPStruct()};
input[0].setVarInt(1);
input[0].setVarString("one");
input[0].setVarFloat(1.1F);
input[1].setVarInt(2);
input[1].setVarString("two");
input[1].setVarFloat(2.2F);
input[2].setVarInt(3);
input[2].setVarString("three");
input[2].setVarFloat(3.3F);
try {
output = binding.echoStructArray(input);
verify("echoStructArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoStructArray", input, e);
} else {
throw e;
}
}
}
{
try {
binding.echoVoid();
verify("echoVoid", null, null);
} catch (Exception e) {
if (!testMode) {
verify("echoVoid", null, e);
} else {
throw e;
}
}
}
{
byte[] input = "Base64".getBytes();
try {
output = binding.echoBase64(input);
verify("echoBase64", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoBase64", input, e);
} else {
throw e;
}
}
}
{
HexBinary input = new HexBinary("3344");
try {
output = binding.echoHexBinary(input.getBytes());
verify("echoHexBinary", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoHexBinary", input, e);
} else {
throw e;
}
}
}
Calendar inputDate = Calendar.getInstance();
inputDate.setTimeZone(TimeZone.getTimeZone("GMT"));
inputDate.setTime(new Date());
{
try {
output = binding.echoDate(inputDate);
verify("echoDate", inputDate, output);
} catch (Exception e) {
if (!testMode) {
verify("echoDate", inputDate, e);
} else {
throw e;
}
}
}
{
BigDecimal input = new BigDecimal("3.14159");
try {
output = binding.echoDecimal(input);
verify("echoDecimal", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoDecimal", input, e);
} else {
throw e;
}
}
}
{
Boolean input = Boolean.TRUE;
try {
output = new Boolean( binding.echoBoolean(input.booleanValue()));
verify("echoBoolean", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoBoolean", input, e);
} else {
throw e;
}
}
}
HashMap map = new HashMap();
map.put(new Integer(5), "String Value");
map.put("String Key", inputDate);
{
HashMap input = map;
try {
output = binding.echoMap(input);
verify("echoMap", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoMap", input, e);
} else {
throw e;
}
}
}
HashMap map2 = new HashMap();
map2.put("this is the second map", new Boolean(true));
map2.put("test", new Float(411));
{
HashMap[] input = new HashMap [] {map, map2 };
try {
output = binding.echoMapArray(input);
verify("echoMapArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoMapArray", input, e);
} else {
throw e;
}
}
}
}
/**
* Execute the 2B tests
*/
public void execute2B() throws Exception {
// execute the tests
Object output = null;
{
SOAPStruct input = new SOAPStruct();
input.setVarInt(5);
input.setVarString("Hello");
input.setVarFloat(103F);
try {
StringHolder outputString = new StringHolder();
IntHolder outputInteger = new IntHolder();
FloatHolder outputFloat = new FloatHolder();
binding.echoStructAsSimpleTypes(input, outputString,
outputInteger, outputFloat);
output = new SOAPStruct();
((SOAPStruct)output).setVarInt(outputInteger.value);
((SOAPStruct)output).setVarString(outputString.value);
((SOAPStruct)output).setVarFloat(outputFloat.value);
verify("echoStructAsSimpleTypes",
input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoStructAsSimpleTypes", input, e);
} else {
throw e;
}
}
}
{
SOAPStruct input = new SOAPStruct();
input.setVarInt(5);
input.setVarString("Hello");
input.setVarFloat(103F);
try {
output = binding.echoSimpleTypesAsStruct(
input.getVarString(), input.getVarInt(), input.getVarFloat());
verify("echoSimpleTypesAsStruct",
input,
output);
} catch (Exception e) {
if (!testMode) {
verify("echoSimpleTypesAsStruct", input, e);
} else {
throw e;
}
}
}
{
String[][] input = new String[2][2];
input[0][0] = "00";
input[0][1] = "01";
input[1][0] = "10";
input[1][1] = "11";
try {
output = binding.echo2DStringArray(input);
verify("echo2DStringArray",
input,
output);
} catch (Exception e) {
if (!testMode) {
verify("echo2DStringArray", input, e);
} else {
throw e;
}
}
}
{
SOAPStruct inputS =new SOAPStruct();
inputS.setVarInt(5);
inputS.setVarString("Hello");
inputS.setVarFloat(103F);
SOAPStructStruct input = new SOAPStructStruct();
input.setVarString("AXIS");
input.setVarInt(1);
input.setVarFloat(3F);
input.setVarStruct(inputS);
try {
output = binding.echoNestedStruct(input);
verify("echoNestedStruct", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNestedStruct", input, e);
} else {
throw e;
}
}
}
{
SOAPArrayStruct input = new SOAPArrayStruct();
input.setVarString("AXIS");
input.setVarInt(1);
input.setVarFloat(3F);
input.setVarArray(new String[] {"one", "two", "three"});
try {
output = binding.echoNestedArray(input);
verify("echoNestedArray", input, output);
} catch (Exception e) {
if (!testMode) {
verify("echoNestedArray", input, e);
} else {
throw e;
}
}
}
}
/**
* Verify that the object sent was, indeed, the one you got back.
* Subclasses are sent to override this with their own output.
*/
protected abstract void verify(String method, Object sent, Object gotBack);
/**
* Main entry point. Tests a variety of echo methods and reports
* on their results.
*
* Arguments are of the form:
* -h localhost -p 8080 -s /soap/servlet/rpcrouter
* -h indicats the host
*/
public static void main(String args[]) throws Exception {
Options opts = new Options(args);
boolean testPerformance = opts.isFlagSet('k') > 0;
boolean allTests = opts.isFlagSet('A') > 0;
boolean onlyB = opts.isFlagSet('b') > 0;
boolean testMode = opts.isFlagSet('t') > 0;
// set up tests so that the results are sent to System.out
TestClient client;
if (testPerformance) {
client = new TestClient(testMode) {
public void verify(String method, Object sent, Object gotBack) {
}
};
} else {
client = new TestClient(testMode) {
public void verify(String method, Object sent, Object gotBack) {
String message;
if (this.equals(sent, gotBack)) {
message = "OK";
} else {
if (gotBack instanceof Exception) {
if (gotBack instanceof AxisFault) {
message = "Fault: " +
((AxisFault)gotBack).getFaultString();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
message = "Exception: ";
((Exception)gotBack).printStackTrace(pw);
message += sw.getBuffer().toString();
}
} else {
message = "Fail:" + gotBack + " expected " + sent;
}
}
// Line up the output
String tab = "";
int l = method.length();
while (l < 25) {
tab += " ";
l++;
}
System.out.println(method + tab + " " + message);
}
};
}
// set up the call object
client.setURL(opts.getURL());
client.setUser(opts.getUser());
client.setPassword(opts.getPassword());
if (testPerformance) {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
if (allTests) {
client.executeAll();
} else if (onlyB) {
client.execute2B();
} else {
client.execute2A();
}
}
long stopTime = System.currentTimeMillis();
System.out.println("That took " + (stopTime - startTime) + " milliseconds");
} else {
if (allTests) {
client.executeAll();
} else if (onlyB) {
client.execute2B();
} else {
client.execute2A();
}
}
}
}
| 6,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.