1 18 package org.apache.activemq.console.command; 19 20 import org.apache.activemq.ActiveMQConnectionFactory; 21 import org.apache.activemq.console.formatter.GlobalWriter; 22 23 import javax.jms.ConnectionFactory ; 24 import javax.jms.Connection ; 25 import javax.jms.JMSException ; 26 import java.net.URI ; 27 import java.net.URISyntaxException ; 28 import java.util.List ; 29 import java.util.ArrayList ; 30 import java.util.Iterator ; 31 32 public abstract class AbstractAmqCommand extends AbstractCommand { 33 private URI brokerUrl; 34 private ConnectionFactory factory; 35 private final List connections = new ArrayList (); 36 37 42 protected Connection createConnection() throws JMSException { 43 if (getBrokerUrl() == null) { 44 GlobalWriter.printException(new IllegalStateException ("You must specify a broker URL to connect to using the --amqurl option.")); 45 return null; 46 } 47 48 if (factory == null) { 49 factory = new ActiveMQConnectionFactory(getBrokerUrl()); 50 } 51 52 Connection conn = factory.createConnection(); 53 connections.add(conn); 54 55 return conn; 56 } 57 58 65 protected Connection createConnection(String username, String password) throws JMSException { 66 if (getBrokerUrl() == null) { 67 GlobalWriter.printException(new IllegalStateException ("You must specify a broker URL to connect to using the --amqurl option.")); 68 return null; 69 } 70 71 if (factory == null) { 72 factory = new ActiveMQConnectionFactory(getBrokerUrl()); 73 } 74 75 Connection conn = factory.createConnection(username, password); 76 connections.add(conn); 77 conn.start(); 78 79 return conn; 80 } 81 82 85 protected void closeAllConnections() { 86 for (Iterator i=connections.iterator(); i.hasNext();) { 87 try { 88 ((Connection )i.next()).close(); 89 } catch (Exception e) { } 90 } 91 92 connections.clear(); 93 } 94 95 101 protected void handleOption(String token, List tokens) throws Exception { 102 if (token.equals("--amqurl")) { 104 if (tokens.isEmpty() || ((String )tokens.get(0)).startsWith("-")) { 106 GlobalWriter.printException(new IllegalArgumentException ("Broker URL not specified.")); 107 tokens.clear(); 108 return; 109 } 110 111 if (getBrokerUrl() != null) { 113 GlobalWriter.printException(new IllegalArgumentException ("Multiple broker URL cannot be specified.")); 114 tokens.clear(); 115 return; 116 } 117 118 String strBrokerUrl = (String )tokens.remove(0); 119 120 try { 121 setBrokerUrl(new URI (strBrokerUrl)); 122 } catch (URISyntaxException e) { 123 GlobalWriter.printException(e); 124 tokens.clear(); 125 return; 126 } 127 } else { 128 super.handleOption(token, tokens); 130 } 131 } 132 133 137 protected void setBrokerUrl(URI brokerUrl) { 138 this.brokerUrl = brokerUrl; 139 } 140 141 146 protected void setBrokerUrl(String address) throws URISyntaxException { 147 this.brokerUrl = new URI (address); 148 } 149 150 154 protected URI getBrokerUrl() { 155 return brokerUrl; 156 } 157 } 158 | Popular Tags |