下面列出了怎么用javax.jms.InvalidClientIDException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void setClientID(String clientID) throws JMSException {
checkClosedOrFailed();
if (explicitClientID) {
throw new IllegalStateException("The clientID has already been set");
}
if (clientID == null || clientID.isEmpty()) {
throw new InvalidClientIDException("Cannot have a null or empty clientID");
}
if (connected.get()) {
throw new IllegalStateException("Cannot set the client id once connected.");
}
setClientID(clientID, true);
// We weren't connected if we got this far, we should now connect to ensure the
// configured clientID is valid.
initialize();
}
@Test
public void testSetSameIdToDifferentConnections() throws Exception {
String id = "somethingElse" + name.getMethodName();
conn = cf.createConnection();
conn2 = cf.createConnection();
conn.getClientID();
conn.setClientID(id);
try {
conn2.setClientID(id);
Assert.fail("should not happen.");
} catch (InvalidClientIDException expected) {
// expected
}
Session session1 = conn.createSession();
Session session2 = conn.createSession();
session1.close();
session2.close();
}
@Test
public void testTwoConnectionsSameIDThroughCF() throws Exception {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?clientID=myid");
conn = connectionFactory.createConnection();
try {
conn2 = connectionFactory.createConnection();
Assert.fail("Exception expected");
} catch (InvalidClientIDException expected) {
// expected
}
Session session1 = conn.createSession();
Session session2 = conn.createSession();
session1.close();
session2.close();
}
@Test
public void testTwoConnectionsSameIDThroughCFWithShareClientIDEnabeld() throws Exception {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?clientID=myid;enableSharedClientID=true");
conn = connectionFactory.createConnection();
try {
conn2 = connectionFactory.createConnection();
} catch (InvalidClientIDException expected) {
Assert.fail("Should allow sharing of client IDs among the same CF");
}
Session session1 = conn.createSession();
Session session2 = conn.createSession();
Session session3 = conn2.createSession();
Session session4 = conn2.createSession();
session1.close();
session2.close();
session3.close();
session4.close();
}
@Override
public void fail(ActiveMQException me, String message) {
if (me != null) {
//filter it like the other protocols
if (!(me instanceof ActiveMQRemoteDisconnectException)) {
ActiveMQClientLogger.LOGGER.connectionFailureDetected(this.transportConnection.getRemoteAddress(), me.getMessage(), me.getType());
}
}
try {
if (this.getConnectionInfo() != null) {
protocolManager.removeConnection(this.getConnectionInfo(), me);
}
} catch (InvalidClientIDException e) {
ActiveMQServerLogger.LOGGER.warn("Couldn't close connection because invalid clientID", e);
}
shutdown(true);
}
public void removeConnection(ConnectionInfo info, Throwable error) throws InvalidClientIDException {
synchronized (clientIdSet) {
String clientId = info.getClientId();
if (clientId != null) {
AMQConnectionContext context = this.clientIdSet.get(clientId);
if (context != null && context.decRefCount() == 0) {
//connection is still there and need to close
context.getConnection().disconnect(error != null);
this.connections.remove(context.getConnection());
this.clientIdSet.remove(clientId);
}
} else {
throw new InvalidClientIDException("No clientID specified for connection disconnect request");
}
}
}
@Override
public synchronized void setClientID(String clientID) throws JMSException {
checkClosedOrFailed();
if (connectionInfo.isExplicitClientID()) {
throw new IllegalStateException("The clientID has already been set");
}
if (clientID == null || clientID.isEmpty()) {
throw new InvalidClientIDException("Cannot have a null or empty clientID");
}
if (connected.get()) {
throw new IllegalStateException("Cannot set the client id once connected.");
}
this.connectionInfo.setClientId(clientID, true);
// We weren't connected if we got this far, we should now connect to ensure the
// configured clientID is valid.
createJmsConnection();
}
@Test(timeout=30000)
public void testCreateWithDuplicateClientIdFails() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
JmsConnection connection1 = (JmsConnection) factory.createConnection();
connection1.setClientID("Test");
assertNotNull(connection1);
connection1.start();
JmsConnection connection2 = (JmsConnection) factory.createConnection();
try {
connection2.setClientID("Test");
fail("should have thrown a JMSException");
} catch (InvalidClientIDException ex) {
LOG.info("Remote threw ex: {}", ex);
} catch (Exception unexpected) {
fail("Wrong exception type thrown: " + unexpected);
}
connection1.close();
connection2.close();
}
/**
* Initialize jmsTemplate and jmsListener from jms configuration data in jmsConfig {@inheritDoc}
*/
public void activate() {
getLogger().log(Level.FINE, "JMSDestination activate().... ");
jmsConfig.ensureProperlyConfigured();
try {
this.jmsListener = createTargetDestinationListener();
} catch (Exception e) {
if (e.getCause() != null && InvalidClientIDException.class.isInstance(e.getCause())) {
throw e;
}
if (!jmsConfig.isOneSessionPerConnection()) {
// If first connect fails we will try to establish the connection in the background
new Thread(new Runnable() {
@Override
public void run() {
restartConnection();
}
}).start();
}
}
}
@Test(expected = InvalidClientIDException.class)
public void testDurableInvalidClientId() throws Throwable {
Connection con = cf1.createConnection();
JMSDestination destination = null;
try {
con.setClientID("testClient");
con.start();
EndpointInfo ei = setupServiceInfo("HelloWorldPubSubService", "HelloWorldPubSubPort");
JMSConfiguration jmsConfig = JMSConfigFactory.createFromEndpointInfo(bus, ei, null);
jmsConfig.setDurableSubscriptionClientId("testClient");
jmsConfig.setDurableSubscriptionName("testsub");
jmsConfig.setConnectionFactory(cf);
destination = new JMSDestination(bus, ei, jmsConfig);
destination.setMessageObserver(createMessageObserver());
} catch (RuntimeException e) {
throw e.getCause();
} finally {
ResourceCloser.close(con);
destination.shutdown();
}
}
@Test(timeout = 5000)
public void testDuplicateClientIdSet() throws Exception {
ActiveMQConnectionFactory activeMQConnectionFactory = (ActiveMQConnectionFactory) cf;
Connection con = cf.createConnection();
Connection con2 = cf.createConnection();
try {
con.setClientID("valid");
con2.setClientID("valid");
fail("Should have failed for duplicate clientId");
} catch (InvalidClientIDException e) {
assertEquals(1, duplicateCount.get());
} finally {
activeMQConnectionFactory.close();
}
}
/**
* Converts instances of sub-classes of {@link JMSException} into the corresponding sub-class of
* {@link JMSRuntimeException}.
*
* @param e
* @return
*/
public static JMSRuntimeException convertToRuntimeException(JMSException e) {
if (e instanceof javax.jms.IllegalStateException) {
return new IllegalStateRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidClientIDException) {
return new InvalidClientIDRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidDestinationException) {
return new InvalidDestinationRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidSelectorException) {
return new InvalidSelectorRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof JMSSecurityException) {
return new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof MessageFormatException) {
return new MessageFormatRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof MessageNotWriteableException) {
return new MessageNotWriteableRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof ResourceAllocationException) {
return new ResourceAllocationRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof TransactionInProgressException) {
return new TransactionInProgressRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof TransactionRolledBackException) {
return new TransactionRolledBackRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
return new JMSRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
private void validateClientID(ClientSession validateSession, String clientID)
throws InvalidClientIDException, ActiveMQException {
try {
validateSession.addUniqueMetaData(JMS_SESSION_CLIENT_ID_PROPERTY, clientID);
} catch (ActiveMQException e) {
if (e.getType() == ActiveMQExceptionType.DUPLICATE_METADATA) {
throw new InvalidClientIDException("clientID=" + clientID + " was already set into another connection");
} else {
throw e;
}
}
}
@Override
public InvalidClientIDException toJMSException() {
final InvalidClientIDException jmsEx = new InvalidClientIDException(getMessage());
jmsEx.initCause(this);
jmsEx.setLinkedException(this);
return jmsEx;
}
@Test(timeout = 20000)
public void testConnectWithInvalidClientIdThrowsICIDEWhenInvalidContainerHintPresent() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
final String remoteURI = "amqp://localhost:" + testPeer.getServerPort();
Map<Symbol, Object> errorInfo = new HashMap<Symbol, Object>();
errorInfo.put(AmqpSupport.INVALID_FIELD, AmqpSupport.CONTAINER_ID);
testPeer.rejectConnect(AmqpError.INVALID_FIELD, "Client ID already in use", errorInfo);
Connection connection = null;
try {
ConnectionFactory factory = new JmsConnectionFactory(remoteURI);
connection = factory.createConnection();
connection.setClientID("in-use-client-id");
fail("Should have thrown InvalidClientIDException");
} catch (InvalidClientIDException e) {
// Expected
} finally {
if (connection != null) {
connection.close();
}
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testConnectionFactoryCreateConnectionWithInvalidClientIdThrowsICIDEWhenInvalidContainerHintPresent() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
final String remoteURI = "amqp://localhost:" + testPeer.getServerPort();
Map<Symbol, Object> errorInfo = new HashMap<Symbol, Object>();
errorInfo.put(AmqpSupport.INVALID_FIELD, AmqpSupport.CONTAINER_ID);
testPeer.rejectConnect(AmqpError.INVALID_FIELD, "Client ID already in use", errorInfo);
Connection connection = null;
try {
JmsConnectionFactory factory = new JmsConnectionFactory(remoteURI);
// Setting on factory prompts the open to fire on create as opposed to waiting
// for the setClientID method or the start method on Connection to be called.
factory.setClientID("in-use-client-id");
connection = factory.createConnection();
fail("Should have thrown InvalidClientIDException");
} catch (InvalidClientIDException e) {
// Expected
} finally {
if (connection != null) {
connection.close();
}
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
public static JMSRuntimeException toRuntimeException(final JMSException e) {
if (e instanceof javax.jms.IllegalStateException) {
return new IllegalStateRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidClientIDException) {
return new InvalidClientIDRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidDestinationException) {
return new InvalidDestinationRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof InvalidSelectorException) {
return new InvalidSelectorRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof JMSSecurityException) {
return new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof MessageFormatException) {
return new MessageFormatRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof MessageNotWriteableException) {
return new MessageNotWriteableRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof ResourceAllocationException) {
return new ResourceAllocationRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof TransactionInProgressException) {
return new TransactionInProgressRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
if (e instanceof TransactionRolledBackException) {
return new TransactionRolledBackRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
return new JMSRuntimeException(e.getMessage(), e.getErrorCode(), e);
}
@Test(expected = InvalidClientIDRuntimeException.class)
public void testConvertsInvalidClientIDExceptionToInvalidClientIDRuntimeException() {
throw JMSExceptionSupport.createRuntimeException(new InvalidClientIDException("error"));
}
public void testReconnectMultipleTimesWithSameClientID() throws Exception {
org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.jmx.ManagedTransportConnection.class);
final AtomicBoolean failed = new AtomicBoolean(false);
Appender appender = new DefaultTestAppender() {
@Override
public void doAppend(LoggingEvent event) {
if (event.getMessage().toString().startsWith("Failed to register MBean")) {
LOG.info("received unexpected log message: " + event.getMessage());
failed.set(true);
}
}
};
log4jLogger.addAppender(appender);
try {
connection = connectionFactory.createConnection();
useConnection(connection);
// now lets create another which should fail
for (int i = 1; i < 11; i++) {
Connection connection2 = connectionFactory.createConnection();
try {
useConnection(connection2);
fail("Should have thrown InvalidClientIDException on attempt" + i);
} catch (InvalidClientIDException e) {
LOG.info("Caught expected: " + e);
} finally {
connection2.close();
}
}
// now lets try closing the original connection and creating a new
// connection with the same ID
connection.close();
connection = connectionFactory.createConnection();
useConnection(connection);
} finally {
log4jLogger.removeAppender(appender);
}
assertFalse("failed on unexpected log event", failed.get());
}
public void addConnection(OpenWireConnection connection, ConnectionInfo info) throws Exception {
String username = info.getUserName();
String password = info.getPassword();
try {
validateUser(username, password, connection);
} catch (ActiveMQSecurityException e) {
// We need to send an exception used by the openwire
SecurityException ex = new SecurityException("User name [" + username + "] or password is invalid.");
ex.initCause(e);
throw ex;
}
String clientId = info.getClientId();
if (clientId == null) {
throw new InvalidClientIDException("No clientID specified for connection request");
}
synchronized (clientIdSet) {
AMQConnectionContext context;
context = clientIdSet.get(clientId);
if (context != null) {
if (info.isFailoverReconnect()) {
OpenWireConnection oldConnection = context.getConnection();
oldConnection.disconnect(true);
connections.remove(oldConnection);
connection.reconnect(context, info);
} else {
throw new InvalidClientIDException("Broker: " + getBrokerName() + " - Client: " + clientId + " already connected from " + context.getConnection().getRemoteAddress());
}
} else {
//new connection
context = connection.initContext(info);
clientIdSet.put(clientId, context);
}
connections.add(connection);
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
// do not distribute passwords in advisory messages. usernames okay
ConnectionInfo copy = info.copy();
copy.setPassword("");
fireAdvisory(context, topic, copy);
// init the conn
context.getConnection().addSessions(context.getConnectionState().getSessionIds());
}
}
@Test(expected = InvalidClientIDRuntimeException.class)
public void testConvertsInvalidClientIDExceptionToInvalidClientIDRuntimeException() {
throw JmsExceptionSupport.createRuntimeException(new InvalidClientIDException("error"));
}
@Test(timeout=30000, expected=InvalidClientIDException.class)
public void testSetClientIDFromNull() throws JMSException, IOException {
connection = new JmsConnection(connectionInfo, provider);
assertFalse(connection.isConnected());
connection.setClientID("");
}
@Test(timeout=30000, expected=InvalidClientIDException.class)
public void testSetClientIDFromEmptyString() throws JMSException, IOException {
connection = new JmsConnection(connectionInfo, provider);
assertFalse(connection.isConnected());
connection.setClientID(null);
}
/**
* Sets the client identifier for this connection.
* <P>
* Does not verify uniqueness of client ID, so does not detect if another
* connection is already using the same client ID
*
* @param clientID
* The client identifier
* @throws JMSException
* If the connection is being closed
* @throws InvalidClientIDException
* If empty or null client ID is used
* @throws IllegalStateException
* If the client ID is already set or attempted to set after an
* action on the connection already took place
*/
@Override
public void setClientID(String clientID) throws JMSException {
checkClosing();
if (clientID == null || clientID.isEmpty()) {
throw new InvalidClientIDException("ClientID is empty");
}
if (this.clientID != null) {
throw new IllegalStateException("ClientID is already set");
}
if (actionOnConnectionTaken) {
throw new IllegalStateException(
"Client ID cannot be set after any action on the connection is taken");
}
this.clientID = clientID;
}