use of org.jgroups.Message in project camel by apache.
the class JGroupsComponentWithChannelPropertiesTest method shouldConsumeMulticastedMessage.
@Test
public void shouldConsumeMulticastedMessage() throws Exception {
// Given
MockEndpoint mockEndpoint = getMockEndpoint("mock:default");
mockEndpoint.setExpectedMessageCount(1);
mockEndpoint.expectedBodiesReceived(MESSAGE);
// When
Message message = new Message(null, MESSAGE);
message.setSrc(null);
clientChannel.send(message);
// Then
mockEndpoint.assertIsSatisfied();
}
use of org.jgroups.Message in project camel by apache.
the class JGroupsProducerTest method doPreSetup.
// Fixture setup
@Override
protected void doPreSetup() throws Exception {
super.doPreSetup();
channel = new JChannel();
channel.setReceiver(new ReceiverAdapter() {
@Override
public void receive(Message msg) {
messageReceived = msg.getObject();
}
});
channel.connect(CLUSTER_NAME);
}
use of org.jgroups.Message in project wildfly by wildfly.
the class JChannelFactory method createChannel.
@Override
public Channel createChannel(String id) throws Exception {
JChannel channel = new JChannel(false);
ProtocolStack stack = new ProtocolStack();
channel.setProtocolStack(stack);
stack.addProtocol(this.configuration.getTransport().createProtocol());
stack.addProtocols(this.configuration.getProtocols().stream().map(ProtocolConfiguration::createProtocol).collect(Collectors.toList()));
RelayConfiguration relay = this.configuration.getRelay();
if (relay != null) {
stack.addProtocol(relay.createProtocol());
}
// Add implicit FORK to the top of the stack
FORK fork = new FORK();
fork.setUnknownForkHandler(new UnknownForkHandler() {
private final short id = ClassConfigurator.getProtocolId(RequestCorrelator.class);
@Override
public Object handleUnknownForkStack(Message message, String forkStackId) {
return this.handle(message);
}
@Override
public Object handleUnknownForkChannel(Message message, String forkChannelId) {
return this.handle(message);
}
private Object handle(Message message) {
Header header = (Header) message.getHeader(this.id);
// If this is a request expecting a response, don't leave the requester hanging - send an identifiable response on which it can filter
if ((header != null) && (header.type == Header.REQ) && header.rspExpected()) {
Message response = message.makeReply().setFlag(message.getFlags()).clearFlag(Message.Flag.RSVP, Message.Flag.SCOPED);
response.putHeader(FORK.ID, message.getHeader(FORK.ID));
response.putHeader(this.id, new Header(Header.RSP, header.req_id, header.corrId));
response.setBuffer(UNKNOWN_FORK_RESPONSE.array());
channel.down(new Event(Event.MSG, response));
}
return null;
}
});
stack.addProtocol(fork);
stack.init();
channel.setName(this.configuration.getNodeName());
TransportConfiguration.Topology topology = this.configuration.getTransport().getTopology();
if (topology != null) {
channel.addAddressGenerator(new TopologyAddressGenerator(topology));
}
return channel;
}
use of org.jgroups.Message in project wildfly by wildfly.
the class ChannelCommandDispatcher method submitOnCluster.
@Override
public <R> Map<Node, Future<R>> submitOnCluster(Command<R, ? super C> command, Node... excludedNodes) throws CommandDispatcherException {
Map<Node, Future<R>> results = new ConcurrentHashMap<>();
FutureListener<RspList<R>> listener = future -> {
try {
future.get().keySet().stream().map(address -> this.factory.createNode(address)).forEach(node -> results.remove(node));
} catch (CancellationException e) {
} catch (ExecutionException e) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Message message = this.createMessage(command);
RequestOptions options = this.createRequestOptions(excludedNodes);
try {
Future<? extends Map<Address, Rsp<R>>> futureResponses = this.dispatcher.castMessageWithFuture(null, message, options, listener);
Set<Node> excluded = (excludedNodes != null) ? new HashSet<>(Arrays.asList(excludedNodes)) : Collections.<Node>emptySet();
for (Address address : this.dispatcher.getChannel().getView().getMembers()) {
Node node = this.factory.createNode(address);
if (!excluded.contains(node)) {
Future<R> future = new Future<R>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return futureResponses.cancel(mayInterruptIfRunning);
}
@Override
public R get() throws InterruptedException, ExecutionException {
Map<Address, Rsp<R>> responses = futureResponses.get();
Rsp<R> response = responses.get(address);
if (response == null) {
throw new CancellationException();
}
return createCommandResponse(response).get();
}
@Override
public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
Map<Address, Rsp<R>> responses = futureResponses.get(timeout, unit);
Rsp<R> response = responses.get(address);
if (response == null) {
throw new CancellationException();
}
return createCommandResponse(response).get();
}
@Override
public boolean isCancelled() {
return futureResponses.isCancelled();
}
@Override
public boolean isDone() {
return futureResponses.isDone();
}
};
results.put(node, future);
}
}
return results;
} catch (Exception e) {
throw new CommandDispatcherException(e);
}
}
use of org.jgroups.Message in project geode by apache.
the class JGroupsMessenger method send.
private Set<InternalDistributedMember> send(DistributionMessage msg, boolean reliably) {
// perform the same jgroups messaging as in 8.2's GMSMembershipManager.send() method
// BUT: when marshalling messages we need to include the version of the product and
// localAddress at the beginning of the message. These should be used in the receiver
// code to create a versioned input stream, read the sender address, then read the message
// and set its sender address
DMStats theStats = services.getStatistics();
NetView oldView = this.view;
if (!myChannel.isConnected()) {
logger.info("JGroupsMessenger channel is closed - messaging is not possible");
throw new DistributedSystemDisconnectedException("Distributed System is shutting down");
}
filterOutgoingMessage(msg);
// the message's processor if necessary
if ((msg instanceof DirectReplyMessage) && msg.isDirectAck() && msg.getProcessorId() <= 0) {
((DirectReplyMessage) msg).registerProcessor();
}
InternalDistributedMember[] destinations = msg.getRecipients();
boolean allDestinations = msg.forAll();
boolean useMcast = false;
if (services.getConfig().getTransport().isMcastEnabled()) {
if (msg.getMulticast() || allDestinations) {
useMcast = services.getManager().isMulticastAllowed();
}
}
if (logger.isDebugEnabled() && reliably) {
String recips = useMcast ? "multicast" : Arrays.toString(msg.getRecipients());
logger.debug("sending via JGroups: [{}] recipients: {}", msg, recips);
}
JGAddress local = this.jgAddress;
if (useMcast) {
long startSer = theStats.startMsgSerialization();
Message jmsg = createJGMessage(msg, local, Version.CURRENT_ORDINAL);
theStats.endMsgSerialization(startSer);
Exception problem;
try {
jmsg.setTransientFlag(TransientFlag.DONT_LOOPBACK);
if (!reliably) {
jmsg.setFlag(Message.Flag.NO_RELIABILITY);
}
theStats.incSentBytes(jmsg.getLength());
logger.trace("Sending JGroups message: {}", jmsg);
myChannel.send(jmsg);
} catch (Exception e) {
logger.debug("caught unexpected exception", e);
Throwable cause = e.getCause();
if (cause instanceof ForcedDisconnectException) {
problem = (Exception) cause;
} else {
problem = e;
}
if (services.getShutdownCause() != null) {
Throwable shutdownCause = services.getShutdownCause();
// problem.
if (shutdownCause instanceof ForcedDisconnectException) {
problem = (Exception) shutdownCause;
} else {
Throwable ne = problem;
while (ne.getCause() != null) {
ne = ne.getCause();
}
ne.initCause(services.getShutdownCause());
}
}
final String channelClosed = LocalizedStrings.GroupMembershipService_CHANNEL_CLOSED.toLocalizedString();
// services.getManager().membershipFailure(channelClosed, problem);
throw new DistributedSystemDisconnectedException(channelClosed, problem);
}
} else // useMcast
{
// ! useMcast
int len = destinations.length;
// explicit list of members
List<GMSMember> calculatedMembers;
// == calculatedMembers.len
int calculatedLen;
if (len == 1 && destinations[0] == DistributionMessage.ALL_RECIPIENTS) {
// send to all
// Grab a copy of the current membership
NetView v = services.getJoinLeave().getView();
// Construct the list
calculatedLen = v.size();
calculatedMembers = new LinkedList<GMSMember>();
for (int i = 0; i < calculatedLen; i++) {
InternalDistributedMember m = (InternalDistributedMember) v.get(i);
calculatedMembers.add((GMSMember) m.getNetMember());
}
} else // send to all
{
// send to explicit list
calculatedLen = len;
calculatedMembers = new LinkedList<GMSMember>();
for (int i = 0; i < calculatedLen; i++) {
calculatedMembers.add((GMSMember) destinations[i].getNetMember());
}
}
// send to explicit list
Int2ObjectOpenHashMap<Message> messages = new Int2ObjectOpenHashMap<>();
long startSer = theStats.startMsgSerialization();
boolean firstMessage = true;
for (GMSMember mbr : calculatedMembers) {
short version = mbr.getVersionOrdinal();
if (!messages.containsKey(version)) {
Message jmsg = createJGMessage(msg, local, version);
messages.put(version, jmsg);
if (firstMessage) {
theStats.incSentBytes(jmsg.getLength());
firstMessage = false;
}
}
}
theStats.endMsgSerialization(startSer);
Collections.shuffle(calculatedMembers);
int i = 0;
for (GMSMember mbr : calculatedMembers) {
JGAddress to = new JGAddress(mbr);
short version = mbr.getVersionOrdinal();
Message jmsg = messages.get(version);
Exception problem = null;
try {
Message tmp = (i < (calculatedLen - 1)) ? jmsg.copy(true) : jmsg;
if (!reliably) {
jmsg.setFlag(Message.Flag.NO_RELIABILITY);
}
tmp.setDest(to);
tmp.setSrc(this.jgAddress);
logger.trace("Unicasting to {}", to);
myChannel.send(tmp);
} catch (Exception e) {
problem = e;
}
if (problem != null) {
Throwable cause = services.getShutdownCause();
if (cause != null) {
// problem.
if (cause instanceof ForcedDisconnectException) {
problem = (Exception) cause;
} else {
Throwable ne = problem;
while (ne.getCause() != null) {
ne = ne.getCause();
}
ne.initCause(cause);
}
}
final String channelClosed = LocalizedStrings.GroupMembershipService_CHANNEL_CLOSED.toLocalizedString();
// services.getManager().membershipFailure(channelClosed, problem);
throw new DistributedSystemDisconnectedException(channelClosed, problem);
}
}
// send individually
}
// (i.e., left the view), we signal it here.
if (msg.forAll()) {
return Collections.emptySet();
}
Set<InternalDistributedMember> result = new HashSet<>();
NetView newView = this.view;
if (newView != null && newView != oldView) {
for (InternalDistributedMember d : destinations) {
if (!newView.contains(d)) {
logger.debug("messenger: member has left the view: {} view is now {}", d, newView);
result.add(d);
}
}
}
return result;
}
Aggregations