/** * Creates and configures a new instance. * * @param dataDirectory root directory where persistent messages are stored * @param useLibAio true to use libaio, false if not installed. See <a * href="http://docs.jboss.org/hornetq/2.2.5.Final/user-manual/en/html/libaio.html">Libaio * Native Libraries</a> * @param injector Google Guice injector. Used to inject dependency members into commands if * needed. * @param queueConfigs vararg of QueueConfig> instances. */ public HornetNest( String dataDirectory, boolean useLibAio, Injector injector, QueueConfig... queueConfigs) { jmsServer = new EmbeddedJMS(); config = new ConfigurationImpl(); jmsConfig = new JMSConfigurationImpl(); try { configureLocations(dataDirectory); configureAcceptor(); configureConnectionFactory(); configurePaging(); config.setJournalType(useLibAio ? JournalType.ASYNCIO : JournalType.NIO); configureQueues(queueConfigs); config.setThreadPoolMaxSize(-1); config.setScheduledThreadPoolMaxSize(10); jmsServer.setConfiguration(config); jmsServer.setJmsConfiguration(jmsConfig); jmsServer.start(); ConnectionFactory connectionFactory = (ConnectionFactory) jmsServer.lookup("/cf"); if (connectionFactory == null) { throw new HornetNestException( "Failed to start EmbeddedJMS due to previous errors. Please, see earlier output from HornetQ."); } consumerConnection = connectionFactory.createConnection(); producerConnection = connectionFactory.createConnection(); configureListeners(injector, queueConfigs); } catch (HornetNestException e) { throw e; } catch (Exception e) { throw new HornetNestException("Failed to start EmbeddedJMS", e); } }
public static void main(String[] args) { try { // Gets the JgetTopicName()NDI context Context jndiContext = new InitialContext(); // Looks up the administered objects ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory"); Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue"); // Creates the needed artifacts to connect to the queue Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); connection.start(); // Loops to receive the messages System.out.println("\nInfinite loop. Waiting for a message..."); while (true) { TextMessage message = (TextMessage) consumer.receive(); System.out.println("Message received: " + message.getText()); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { try { Context ctx = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); Queue queue = (Queue) ctx.lookup("inbound"); Connection con = factory.createConnection(); final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { final String type; try { type = message.getStringProperty("type"); if (type != null && type.equals("xml")) { System.out.println(((TextMessage) message).getText()); } } catch (JMSException e) { e.printStackTrace(); } } }); con.start(); } catch (Exception e) { e.printStackTrace(); } }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
public List<Publicacao> getLista() throws Exception { String sql = "SELECT * FROM publicacao pu"; Connection conn = ConnectionFactory.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); List<Publicacao> publicacao = new ArrayList<Publicacao>(); while (rs.next()) { Publicacao pu = new Publicacao(); pu.setId(rs.getInt("pu.id_publicacao")); pu.setNome(rs.getString("pu.nome_publicacao")); pu.setTipo(rs.getString("pu.tipo_publicacao")); pu.setTema(rs.getString("pu.tema_publicacao")); pu.setArea(rs.getString("pu.area_publicacao")); pu.setResumo(rs.getString("pu.resumo_publicacao")); pu.setLink(rs.getString("pu.link_publicacao")); Date data; data = (rs.getDate("pu.data_hora_cadastro")); SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy"); String date = formato.format(data); pu.setDataHoraCadastro(date); publicacao.add(pu); } rs.close(); ps.close(); ConnectionFactory.closeConnection(conn); return publicacao; }
/** * Establishes a connection to a registry. * * @param queryUrl the URL of the query registry * @param publishUrl the URL of the publish registry */ public void makeConnection(String queryUrl, String publishUrl) { Context context = null; ConnectionFactory factory = null; /* * Define connection configuration properties. * To publish, you need both the query URL and the * publish URL. */ Properties props = new Properties(); props.setProperty("javax.xml.registry.queryManagerURL", queryUrl); props.setProperty("javax.xml.registry.lifeCycleManagerURL", publishUrl); try { // Create the connection, passing it the // configuration properties context = new InitialContext(); factory = (ConnectionFactory) context.lookup("java:comp/env/eis/JAXR"); factory.setProperties(props); connection = factory.createConnection(); System.out.println("Created connection to registry"); } catch (Exception e) { e.printStackTrace(); if (connection != null) { try { connection.close(); } catch (JAXRException je) { } } } }
public static void main(String[] args) throws JMSException { AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(asyncConsumer); connection.setExceptionListener(asyncConsumer); try { while (true) { if (AsyncSimpleConsumer.catchExit) { break; } Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Sleep interrupted"); } connection.close(); }
/* * Initiate the snapshot by sending a Marker message to one of the Players (Player0) * Any Player could have been used to initiate the snapshot. */ private void sendInitSnapshot() { try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Queue q = (Queue) ctx.lookup("jms/PITplayer0"); Connection con = cf.createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer writer = session.createProducer(q); /* * As part of the snapshot algorithm, players need to record * what other Players they receive markers from. * "-1" indicates to the PITplayer0 that this marker is coming from * the monitor, not another Player. */ Marker m = new Marker(-1); ObjectMessage msg = session.createObjectMessage(m); System.out.println("Initiating Snapshot"); writer.send(msg); con.close(); } catch (JMSException e) { System.out.println("JMS Exception thrown" + e); } catch (Throwable e) { System.out.println("Throwable thrown" + e); } }
public static void main(String[] args) throws JMSException { // Getting JMS connection from the server ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); // Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Getting the queue 'JMSBEGINQUEUE' Destination destination = session.createQueue(subject); // MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination); // Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive(); // There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println("Received message '" + textMessage.getText() + "'"); } connection.close(); }
@Override /* LISTAGEM */ public List<Fabricante> listAll() { Connection conn; List<Fabricante> fabricante = new ArrayList<>(); try { conn = ConnectionFactory.getConnection(); PreparedStatement pstm = conn.prepareStatement(LIST); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Fabricante f = new Fabricante(); f.setCod(rs.getInt("cod_fabricante")); f.setNmFantasia(rs.getString("nmfantasia")); f.setCnpj(rs.getString("cnpj")); f.setTelefone(rs.getString("telefone")); f.setEmail(rs.getString("email")); f.setEndereco(rs.getString("endereco")); fabricante.add(f); } ConnectionFactory.closeConnection(conn, pstm); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Não foi possível efetuar a transação"); } return fabricante; }
/** * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the * cow-server.properties file. */ public void init() { String connectionFactorylocation = "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'"; String destinationType = "topic"; String jndiName = "cow"; String destinationName = "myTopic"; try { properties = new Properties(); properties.setProperty( Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); properties.setProperty("connectionfactory.amqpConnectionFactory", connectionFactorylocation); properties.setProperty(destinationType + "." + jndiName, destinationName); context = new InitialContext(properties); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("amqpConnectionFactory"); Connection connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = (Destination) context.lookup(jndiName); messageProducer = session.createProducer(destination); initialized = true; } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
public static StreamConnection getConnectionForRequest(String url) { final ConnectionFactory connectionFactory = new ConnectionFactory(); // Remove any transports that are not currently available. if (isTransportManaged == false) { for (int i = 0; i < availableTransportTypes.length; i++) { int transport = availableTransportTypes[i]; if (!TransportInfo.isTransportTypeAvailable(transport) || !TransportInfo.hasSufficientCoverage(transport)) { Arrays.removeAt(availableTransportTypes, i); } } isTransportManaged = true; } connectionFactory.setPreferredTransportTypes(availableTransportTypes); final ConnectionDescriptor connectionDescriptor = connectionFactory.getConnection(url); StreamConnection connection = null; if (connectionDescriptor != null) { // connection suceeded int transportUsed = connectionDescriptor.getTransportDescriptor().getTransportType(); System.out.println("Transport type used: " + Integer.toString(transportUsed)); connection = (StreamConnection) connectionDescriptor.getConnection(); } return connection; }
private void createAndStartConnection(String userName, String password, String url) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url); connection = (ActiveMQConnection) connectionFactory.createConnection(); connection.start(); LOG.info("Connected successfully to {}", url); }
@Override /* LISTAGEM POR ID */ public Fabricante listById(int codFabricante) { Connection conn; try { conn = ConnectionFactory.getConnection(); PreparedStatement pstm = conn.prepareStatement(LISTBYID); pstm.setInt(1, codFabricante); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Fabricante f = new Fabricante(); f.setCod(rs.getInt("cod_fabricante")); f.setNmFantasia(rs.getString("nmfantasia")); f.setCnpj(rs.getString("cnpj")); f.setTelefone(rs.getString("telefone")); f.setEmail(rs.getString("email")); f.setEndereco(rs.getString("endereco")); return f; } ConnectionFactory.closeConnection(conn, pstm); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Não foi possível efetuar a transação"); } return null; }
public UserMessageService(String brokerURL, String queueName) throws JMSException { this.queueName = queueName; ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); this.con = factory.createConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); this.producer = session.createProducer(null); }
/** * Construct a memcached connection. * * @param bufSize the size of the buffer used for reading from the server * @param f the factory that will provide an operation queue * @param a the addresses of the servers to connect to * @throws IOException if a connection attempt fails early */ public MemcachedConnection(int bufSize, ConnectionFactory f, List<InetSocketAddress> a) throws IOException { reconnectQueue = new TreeMap<Long, MemcachedNode>(); addedQueue = new ConcurrentLinkedQueue<MemcachedNode>(); selector = Selector.open(); List<MemcachedNode> connections = new ArrayList<MemcachedNode>(a.size()); for (SocketAddress sa : a) { SocketChannel ch = SocketChannel.open(); ch.configureBlocking(false); MemcachedNode qa = f.createMemcachedNode(sa, ch, bufSize); int ops = 0; if (ch.connect(sa)) { getLogger().info("Connected to %s immediately", qa); qa.connected(); assert ch.isConnected(); } else { getLogger().info("Added %s to connect queue", qa); ops = SelectionKey.OP_CONNECT; } qa.setSk(ch.register(selector, ops, qa)); assert ch.isConnected() || qa.getSk().interestOps() == SelectionKey.OP_CONNECT : "Not connected, and not wanting to connect"; connections.add(qa); } locator = f.createLocator(connections); }
private int inserir(Endereco e) { int status = -1; Connection con = null; PreparedStatement pstm = null; try { con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, e.getRua()); pstm.execute(); try (ResultSet rs = pstm.getGeneratedKeys()) { rs.next(); status = rs.getInt(1); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao inserir um endereço: " + ex.getMessage()); } finally { } try { ConnectionFactory.closeConnection(con, pstm); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao fechar conexão: " + ex.getMessage()); } return status; }
public void setConnectionFactories(Collection<ConnectionFactory> factories) { synchronized (_factories) { List<ConnectionFactory> existing = new ArrayList<>(_factories.values()); for (ConnectionFactory factory : existing) removeConnectionFactory(factory.getProtocol()); for (ConnectionFactory factory : factories) if (factory != null) addConnectionFactory(factory); } }
@Override public <T> T getConnectionFactory(Class<T> factoryType) { synchronized (_factories) { for (ConnectionFactory f : _factories.values()) if (factoryType.isAssignableFrom(f.getClass())) return (T) f; return null; } }
public void addConnectionFactory(ConnectionFactory factory) { synchronized (_factories) { ConnectionFactory old = _factories.remove(factory.getProtocol()); if (old != null) removeBean(old); _factories.put(factory.getProtocol().toLowerCase(Locale.ENGLISH), factory); addBean(factory); if (_defaultProtocol == null) _defaultProtocol = factory.getProtocol(); } }
static { // determine good/bad nodes: final ConnectionFactory cf = ConnectionFactory.getInstance(); cf.testAllNodes(); // set not to automatically try reconnects (auto-retries prevent ConnectionException tests from // working): final DefaultConnectionPolicy cp = ((DefaultConnectionPolicy) cf.getConnectionPolicy()); cp.setMaxRetries(0); scalarisNode = cp.selectNode().toString(); }
public static void main(String args[]) { Connection connection = null; try { // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); LOG.info( "Start consuming messages from " + destination.toString() + " with " + MESSAGE_TIMEOUT_MILLISECONDS + "ms timeout"); // Synchronous message consumer int i = 1; while (true) { Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); LOG.info("Got " + (i++) + ". message: " + text); } } else { break; } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error("Error receiving message", t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error("Error closing connection", e); } } } }
/* (non-Javadoc) * @see org.ikasan.spec.management.ManagedResource#startManagedResource() */ public void startManagedResource() { ConnectionFactory _connectionFactory = null; try { if (this.configuration.isRemoteJNDILookup()) { Context context = getInitialContext(); if (this.configuration.getConnectionFactoryName() == null) { throw new RuntimeException( "ConnectionFactory name cannot be 'null' when using remoteJNDILookup"); } _connectionFactory = (ConnectionFactory) context.lookup(this.configuration.getConnectionFactoryName()); if (this.configuration.getDestinationName() == null) { throw new RuntimeException( "DestinationName name cannot be 'null' when using remoteJNDILookup"); } this.destination = (Destination) context.lookup(this.configuration.getDestinationName()); } else { if (this.connectionFactory == null) { throw new RuntimeException( "You must specify the remoteJNDILookup as true or provide a ConnectionFactory instance for this class."); } _connectionFactory = this.connectionFactory; } if (this.configuration.getUsername() != null && this.configuration.getUsername().trim().length() > 0) { connection = _connectionFactory.createConnection( this.configuration.getUsername(), this.configuration.getPassword()); } else { connection = _connectionFactory.createConnection(); } this.session = connection.createSession( this.configuration.isTransacted(), this.configuration.getAcknowledgement()); if (this.destination == null) { if (destinationResolver == null) { throw new RuntimeException( "destination and destinationResolver are both 'null'. No means of resolving a destination."); } this.destination = this.destinationResolver.getDestination(); } } catch (JMSException e) { throw new EndpointException(e); } catch (NamingException e) { throw new RuntimeException(e); } }
@Test public void testGetConnection() throws SQLException { System.out.println("ConnectionFactory"); System.out.println("Testando a criação de Intâcia: 'ConnectionFactory'"); ConnectionFactory instance = new ConnectionFactory(); assertNotNull( ">>> A instância da Classe 'ConnectionFactory' não pode ser criada! <<<", instance); Connection conn = instance.getConnection(); assertNotNull(conn); }
public HTTPConnManager( final int type, final String http, BigVector _postData, final int handler, final HTTPAnswerListener _listener) { listener = _listener; postData = _postData; // Create a preference-ordered list of transports. int[] _intTransports = { TransportInfo.TRANSPORT_TCP_WIFI, TransportInfo.TRANSPORT_BIS_B, TransportInfo.TRANSPORT_MDS, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_TCP_CELLULAR }; // Remove any transports that are not currently available. for (int i = 0; i < _intTransports.length; i++) { int transport = _intTransports[i]; if (!TransportInfo.isTransportTypeAvailable(transport) || !TransportInfo.hasSufficientCoverage(transport)) { Arrays.removeAt(_intTransports, i); } } // Set ConnectionFactory options. if (_intTransports.length > 0) { _factory.setPreferredTransportTypes(_intTransports); } _factory.setAttemptsLimit(5); // Open a connection on a new thread. Thread t = new Thread( new Runnable() { public void run() { DebugStorage.getInstance().Log(0, "HTTPConnManager: open connection to " + http); ConnectionDescriptor cd = _factory.getConnection(http); if (cd != null) { DebugStorage.getInstance().Log(0, "HTTPConnManager: connection created."); Connection c = cd.getConnection(); new HTTPOut(type, postData, c, handler, listener); } else { DebugStorage.getInstance() .Log(0, "HTTPConnManager: UNABLE TO CREATE CONNECTION!"); } } }); t.start(); }
public static void main(String[] args) throws JMSException { String uri = "failover://tcp://103.224.81.184:61616"; ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Topic topic = session.createTopic("topic1"); MessageProducer producer = session.createProducer(topic); TextMessage textMessage = session.createTextMessage("HelloWorld4"); producer.send(textMessage); connection.start(); producer.close(); session.close(); connection.close(); }
public synchronized F getConnectionFactory(String scheme) throws IOException { if (scheme == null) { throw new IllegalArgumentException("no connection scheme given"); } ConnectionFactory factory; ServiceLoader<ConnectionFactory> loader = ServiceLoader.load(ConnectionFactory.class); Iterator<ConnectionFactory> it = loader.iterator(); while (it.hasNext()) { factory = it.next(); if (scheme != null && factory.providesScheme(scheme)) { return (F) factory; } } throw new ServiceConfigurationError("no connection factory found for scheme " + scheme); }
@SuppressWarnings({"unchecked", "static-access"}) public static synchronized void initConnectionPool() throws SQLException, ClassNotFoundException { ConnectionPool.getConnectionPool().destoryConnectionPool(); @SuppressWarnings("rawtypes") Vector temp = ConnectionPool.getConnectionPool().getConnectionPoolBuffer(); ConnectionFactory connectionFactory = ConnectionFactory.getDefaultFactory(); for (int i = 0; i < MAX_CONNECTION; i++) { Connection connection = connectionFactory.createConnection("mysql"); temp.addElement(new ConnectionInfo(connection, System.currentTimeMillis())); System.out.println("New Connection Created.." + connection); } }
public int insertDriver(String driverId, int vehicleId, String driver_type) throws SQLException { String location = getlocation(); String driveravailability = "free"; String query = "INSERT INTO driver(driver_emailid,driver_vehicleid,driverlocation,driverstatus,driver_type) VALUES " + "( '" + driverId + "','" + vehicleId + "','" + location + "','" + driveravailability + "','" + driver_type + "'" + ")"; int status = 0; try { SignUpconnection = ConnectionFactory.getConnection(); Signstatement = SignUpconnection.createStatement(); status = Signstatement.executeUpdate(query); } finally { DbUtil.close(Signstatement); DbUtil.close(SignUpconnection); } return status; }
public int AddVehicle(String vehicleType, String vehicle_model, int requestNoOfSeats) throws SQLException { String query = "INSERT INTO vehicle(vehiclemodel,vehicletype,noofseats) VALUES " + "( " + "\"" + vehicle_model + "\"" + "," + "\"" + vehicleType + "\"" + "," + requestNoOfSeats + ")"; int status = 0; try { SignUpconnection = ConnectionFactory.getConnection(); Signstatement = SignUpconnection.createStatement(); status = Signstatement.executeUpdate(query); } finally { DbUtil.close(Signstatement); DbUtil.close(SignUpconnection); } return status; }