org.jgroups.Message Java Examples

The following examples show how to use org.jgroups.Message. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LateralJGSender.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * Sends commands to the lateral cache listener.
 *
 * @param led
 * @throws IOException
 */
public void send( LateralElementDescriptor led )
    throws IOException
{
    log.debug( "sending LateralElementDescriptor" );

    if ( led == null )
    {
        return;
    }

    try
    {

        Message send_msg = new Message( null, null, led );

        javagroups.send( send_msg );

    }
    catch ( Exception e )
    {
        log.error( "Detected problem with connection: " + e );
        throw new IOException( e.getMessage() );
    }

}
 
Example #2
Source File: JChannelWrapper.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public JChannelWrapper(JChannelManager manager, final String channelName, JChannel channel) throws Exception {
   this.refCount = 1;
   this.channelName = channelName;
   this.channel = channel;
   this.manager = manager;

   if (logger.isTraceEnabled() && channel.getReceiver() != null) {
      logger.trace(this + "The channel already had a receiver previously!!!! == " + channel.getReceiver(), new Exception("trace"));
   }

   //we always add this for the first ref count
   channel.setReceiver(new ReceiverAdapter() {

      @Override
      public String toString() {
         return "ReceiverAdapter::" + JChannelWrapper.this;
      }

      @Override
      public void receive(org.jgroups.Message msg) {
         if (logger.isTraceEnabled()) {
            logger.trace(this + ":: Wrapper received " + msg + " on channel " + channelName);
         }
         synchronized (receivers) {
            for (JGroupsReceiver r : receivers) {
               r.receive(msg);
            }
         }
      }
   });
}
 
Example #3
Source File: ClusterClientTest.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
public void receive(Message msg) {

  try {
    MasterTest mt = (MasterTest)msg.getObject();
    testsRun++;
    System.out.println("Received test: " + mt.testname);
    ClientTest ct = (ClientTest)tests.get(mt.testname);
    if (ct == null) throw new OntopiaRuntimeException("Could not find test: " + mt.testname);
    ct.run(mt);
    topicmap.getStore().commit();
    
  } catch (Exception e) {
    testsFailed++;
    e.printStackTrace();
  }
}
 
Example #4
Source File: PCServiceEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * JGroups message listener.
 */
public void receive(Message msg) {

    Object o = msg.getObject();
    if (o instanceof UserMessage) {
        UserMessage message = (UserMessage) o;
        if (message.to == null) {
        	if (message.clear) {
                String userId = message.from;
                synchronized (messageMap) {
                    messageMap.remove(userId);
				}
        	} else {
        		log.debug("Received heartbeat from cluster ...");
        		heartbeatMap.put(message.from, message);
        	}
        } else  {
log.debug("Received {} message from cluster ...",  message.video ? "video" : "");
            addMessageToMap(message);
        } 
    }
}
 
Example #5
Source File: OpenshiftPing.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendMcastDiscoveryRequest(Message msg) {
    final List<InetSocketAddress> hosts = readAll();
    final PhysicalAddress physical_addr = (PhysicalAddress) down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
    if (!(physical_addr instanceof IpAddress)) {
        log.error("Unable to send PING requests: physical_addr is not an IpAddress.");
        return;
    }
    // XXX: is it better to force this to be defined?
    // assume symmetry
    final int port = ((IpAddress) physical_addr).getPort();
    for (InetSocketAddress host: hosts) {
        // JGroups messages cannot be reused - https://github.com/belaban/workshop/blob/master/slides/admin.adoc#problem-9-reusing-a-message-the-sebastian-problem
        Message msgToHost = msg.copy();
        msgToHost.dest(new IpAddress(host.getAddress(), port));
        sendDown(down_prot, msgToHost);
    }
}
 
Example #6
Source File: ELECTION.java    From jgroups-raft with Apache License 2.0 6 votes vote down vote up
protected void handleEvent(Message msg, RaftHeader hdr) {
    // drop the message if hdr.term < raft.current_term, else accept
    // if hdr.term > raft.current_term -> change to follower
    int rc=raft.currentTerm(hdr.term);
    if(rc < 0)
        return;
    if(rc > 0) { // a new term was set
        changeRole(Role.Follower);
        voteFor(null); // so we can vote again in this term
    }

    if(hdr instanceof HeartbeatRequest) {
        HeartbeatRequest hb=(HeartbeatRequest)hdr;
        handleHeartbeat(hb.term(), hb.leader);
    }
    else if(hdr instanceof VoteRequest) {
        VoteRequest header=(VoteRequest)hdr;
        handleVoteRequest(msg.src(), header.term(), header.lastLogTerm(), header.lastLogIndex());
    }
    else if(hdr instanceof VoteResponse) {
        VoteResponse rsp=(VoteResponse)hdr;
        if(rsp.result()) {
        	handleVoteResponse(rsp.term());
        }
    }
}
 
Example #7
Source File: ServerTestBase.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
@Test @Ignore
public void testResponse() throws Exception {
    Address local_addr = pinger.getLocalAddress();
    PhysicalAddress physical_addr = (PhysicalAddress) pinger
            .down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr));
    PingData data = createPingData(local_addr, physical_addr);
    final PingHeader hdr = getPingHeader(data);
    Message msg = new Message(null).setFlag(Message.Flag.DONT_BUNDLE)
            .putHeader(pinger.getId(), hdr).setBuffer(streamableToBuffer(data));
    URL url = new URL("http://localhost:8888");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
    conn.addRequestProperty(Server.CLUSTER_NAME, TestBase.CLUSTER_NAME);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    msg.writeTo(out);
    out.flush();

    Assert.assertEquals(200, conn.getResponseCode());
}
 
Example #8
Source File: JvmStateReceiverAdapterTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReceiveNullId() {
    final Identifier<Jvm> jvmId = new Identifier<>("1");
    Jvm jvm = new Jvm(jvmId, "jvm-name");

    final Map<Object, Object> serverInfoMap = new HashMap();
    serverInfoMap.put(JvmStateReceiverAdapter.NAME_KEY, jvm.getJvmName());
    serverInfoMap.put(JvmStateReceiverAdapter.STATE_KEY, LifecycleState.STOPPING);

    msg = new Message();
    msg.setObject(serverInfoMap);

    when (mockJvmPersistenceService.findJvmByExactName(jvm.getJvmName())).thenReturn(null);

    jvmStateReceiverAdapter.receive(msg);
    verify(mockJvmStateService, never()).updateState(eq(jvm), eq(JvmState.JVM_STOPPING), eq(StringUtils.EMPTY));
}
 
Example #9
Source File: JvmStateReceiverAdapterTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReceive() throws Exception {
    final Identifier<Jvm> jvmId = new Identifier<>("1");
    Jvm jvm = new Jvm(jvmId, "jvm-name");

    final Map<Object, Object> serverInfoMap = new HashMap();
    serverInfoMap.put(JvmStateReceiverAdapter.NAME_KEY, jvm.getJvmName());
    serverInfoMap.put(JvmStateReceiverAdapter.STATE_KEY, LifecycleState.STOPPING);

    msg = new Message();
    msg.setObject(serverInfoMap);

    when (mockJvmPersistenceService.findJvmByExactName(jvm.getJvmName())).thenReturn(jvm);
    jvmStateReceiverAdapter.receive(msg);
    verify(mockJvmStateService).updateState(eq(jvm), eq(JvmState.JVM_STOPPING), eq(StringUtils.EMPTY));
}
 
Example #10
Source File: PCServiceEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * JGroups message listener.
 */
public void receive(Message msg) {

    Object o = msg.getObject();
    if (o instanceof UserMessage) {
        UserMessage message = (UserMessage) o;
        if (message.to == null) {
        	if (message.clear) {
                String userId = message.from;
                synchronized (messageMap) {
                    messageMap.remove(userId);
				}
        	} else {
        		log.debug("Received heartbeat from cluster ...");
        		heartbeatMap.put(message.from, message);
        	}
        } else  {
log.debug("Received {} message from cluster ...",  message.video ? "video" : "");
            addMessageToMap(message);
        } 
    }
}
 
Example #11
Source File: JvmStateReceiverAdapterTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReceiveReportingJmsMessageKey() throws Exception {
    final Identifier<Jvm> jvmId = new Identifier<>("1");
    Jvm jvm = new Jvm(jvmId, "jvm-name");

    final Map<Object, Object> serverInfoMap = new HashMap();
    serverInfoMap.put(ReportingJmsMessageTestKey.ID, "1");
    serverInfoMap.put(ReportingJmsMessageTestKey.STATE, "JVM_STOPPING");

    msg = new Message();
    msg.setObject(serverInfoMap);

    when (mockJvmPersistenceService.getJvm(jvmId)).thenReturn(jvm);
    jvmStateReceiverAdapter.receive(msg);
    verify(mockJvmStateService).updateState(eq(jvm), eq(JvmState.JVM_STOPPING), eq(StringUtils.EMPTY));
}
 
Example #12
Source File: ELECTION.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
public Object up(Message msg) {
    RaftHeader hdr=msg.getHeader(id);
    if(hdr != null) {
        handleEvent(msg, hdr);
        return null;
    }
    return up_prot.up(msg);
}
 
Example #13
Source File: JGroupsServerInfoMessageBuilder.java    From jwala with Apache License 2.0 5 votes vote down vote up
public Message build() {
    final Map<String, Object> serverInfoMap = new HashMap<>();
    serverInfoMap.put(ServerInfoFields.ID.name(), serverId);
    serverInfoMap.put(ServerInfoFields.NAME.name(), serverName);
    serverInfoMap.put(ServerInfoFields.AS_OF.name(), DateTime.now());
    serverInfoMap.put(ServerInfoFields.STATE.name(), state);
    return new Message(destAddress, srcAddress, serverInfoMap);
}
 
Example #14
Source File: JGroupsCluster.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private void sendEvent(java.io.Serializable e) {
  log.debug("Sending: " + e);
  try {
    Message msg = new Message(null, null, e);
    dchannel.send(msg);
  } catch (Exception ex) {
    log.error(ex.getMessage(), ex);
  }
}
 
Example #15
Source File: JavaGroupsCache.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/**
 * If 'getFromPeers' is true, this will attempt to get the requested element
 * from ant other members of the group.
 *
 * @param key
 * @return
 * @throws IOException
 *             Never thrown by this implementation
 */
public ICacheElement<K, V> get( K key )
    throws IOException
{
    if ( getFromPeers )
    {
        CacheElement element = new CacheElement( cacheName, key, null );

        Request request = new Request( element, Request.GET );

        // Cast message and wait for all responses.

        // FIXME: we can stop waiting after the first not null response,
        //        that is more difficult to implement however.

        RspList responses = dispatcher.castMessage( null, new Message( null, null, request ), GroupRequest.GET_ALL,
                                                    0 );

        // Get results only gives the responses which were not null

        Vector results = responses.getResults();

        // If there were any non null results, return the first

        if ( results.size() > 0 )
        {
            return (ICacheElement) results.get( 0 );
        }
    }

    return null;
}
 
Example #16
Source File: ClusterMasterTest.java    From ontopia with Apache License 2.0 5 votes vote down vote up
protected void sendTest(MasterTest mt) {
  System.out.println("Sending: " + mt.testname);
  try {
    Message msg = new Message(null, null, mt);
    channel.send(msg);
  } catch (Exception ex1) {
    ex1.printStackTrace();
  }
}
 
Example #17
Source File: NO_DUPES.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
public void up(MessageBatch batch) {
    for(Message msg: batch) {
        GMS.GmsHeader hdr=msg.getHeader(gms_id);
        if(hdr != null && !handleGmsHeader(hdr, msg.src()))
            batch.remove(msg);
    }
    if(!batch.isEmpty())
        up_prot.up(batch);
}
 
Example #18
Source File: JavaGroupsCache.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
public void send( ICacheElement<K, V> element, int command )
{
    Request request = new Request( element, command );

    try
    {
        dispatcher.castMessage( null, new Message( null, null, request ), GroupRequest.GET_NONE, 0 );

    }
    catch ( Exception e )
    {
        log.error( "Failed to send JavaGroups message", e );
    }
}
 
Example #19
Source File: NO_DUPES.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected void sendJoinRejectedMessageTo(Address joiner, String reject_message) {
    try {
        Buffer buffer=Util.streamableToBuffer(new JoinRsp(reject_message));
        Message msg=new Message(joiner, buffer).putHeader(gms_id, new GMS.GmsHeader(GMS.GmsHeader.JOIN_RSP));
        down_prot.down(msg);
    }
    catch(Exception ex) {
        log.error("failed sending JoinRsp to %s: %s", joiner, ex);
    }
}
 
Example #20
Source File: Follower.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleInstallSnapshotRequest(Message msg, int term, Address leader,
                                            int last_included_index, int last_included_term) {
    // 1. read the state (in the message's buffer) and apply it to the state machine (clear the SM before?)

    // 2. Delete the log (if it exists) and create a new log. Append a dummy entry at last_included_index with an
    //    empty buffer and term=last_included_term
    //    - first_appended=last_appended=commit_index=last_included_index

    StateMachine sm;
    if((sm=raft.state_machine) == null) {
        raft.getLog().error("%s: no state machine set, cannot install snapshot", raft.local_addr);
        return;
    }
    Address sender=msg.src();
    try {
        ByteArrayDataInputStream in=new ByteArrayDataInputStream(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
        sm.readContentFrom(in);

        raft.doSnapshot();

        // insert a dummy entry
        Log log=raft.log();
        log.append(last_included_index, true, new LogEntry(last_included_term, null));
        raft.last_appended=last_included_index;
        log.commitIndex(last_included_index);
        raft.commit_index=last_included_index;
        log.truncate(last_included_index);

        raft.getLog().debug("%s: applied snapshot (%s) from %s; last_appended=%d, commit_index=%d",
                            raft.local_addr, Util.printBytes(msg.getLength()), msg.src(), raft.lastAppended(), raft.commitIndex());

        AppendResult result=new AppendResult(true, last_included_index).commitIndex(raft.commitIndex());
        Message ack=new Message(leader).putHeader(raft.getId(), new AppendEntriesResponse(raft.currentTerm(), result));
        raft.getDownProtocol().down(ack);
    }
    catch(Exception ex) {
        raft.getLog().error("%s: failed applying snapshot from %s: %s", raft.local_addr, sender, ex);
    }
}
 
Example #21
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void sendToCluster(TransferableChatMessage message){
    if (clustered) {
        try {
            log.debug("Sending message ({}) id:{}, channelId:{} to cluster ...", message.getType(), message.getId(), message.getChannelId());
            Message msg = new Message(null, message);
            clusterChannel.send(msg);
        } catch (Exception e) {
            log.error("Error sending JGroups message", e);
        }
    }
}
 
Example #22
Source File: ELECTION.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
public void up(MessageBatch batch) {
    for(Message msg: batch) {
        RaftHeader hdr=msg.getHeader(id);
        if(hdr != null) {
            batch.remove(msg);
            handleEvent(msg, hdr);
        }
    }
    if(!batch.isEmpty())
        up_prot.up(batch);
}
 
Example #23
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * JGroups message listener.
 */
public void receive(Message msg) {
    Object o = msg.getObject();
    if (o instanceof TransferableChatMessage) {
        TransferableChatMessage message = (TransferableChatMessage) o;

        String id = message.getId();
        String channelId = message.getChannelId();

        switch(message.getType()){
        case CHAT : 
            log.debug("Received message {} from cluster ...", id);
            addMessageToMap(message);
            break;
        case HEARTBEAT :
            log.debug("Received heartbeat {} - {} from cluster ...", id, channelId);
            addHeartBeat(channelId, id);
            break;
        case CLEAR :
            log.debug("Received clear message {} from cluster ...", id);
            //as guava cache is synchronized, maybe this is not necessary
            synchronized (messageMap){
                messageMap.invalidate(id);
            }
            break;
        case REMOVE :
            log.debug("Received remove message {} from cluster ...", id);
            addMessageToMap(message); 
            break;
        }
    }
}
 
Example #24
Source File: ELECTION.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected void sendVoteRequest(int term) {
    int last_log_index=raft.log().lastAppended();
    LogEntry entry=raft.log().get(last_log_index);
    int last_log_term=entry != null? entry.term() : 0;
    VoteRequest req=new VoteRequest(term, last_log_term, last_log_index);
    log.trace("%s: sending %s", local_addr, req);
    Message vote_req=new Message(null).putHeader(id, req)
      .setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY, Message.Flag.NO_FC);
    down_prot.down(vote_req);
}
 
Example #25
Source File: ELECTION.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected void sendVoteResponse(Address dest, int term) {
    VoteResponse rsp=new VoteResponse(term, true);
    log.trace("%s: sending %s",local_addr,rsp);
    Message vote_rsp=new Message(dest).putHeader(id, rsp)
      .setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY, Message.Flag.NO_FC);
    down_prot.down(vote_rsp);
}
 
Example #26
Source File: NodeReceiverAdapter.java    From java-course-ee with MIT License 5 votes vote down vote up
@Override
public void receive(Message msg) {
    log.info("Message received: {}", (Object) msg.getObject());
    try {
        log.trace("Message received: {}", mapper.writeValueAsString(msg));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: PCServiceEntityProvider.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void sendClearMessage(String userId) {

        if (clustered) {
            try {
				log.debug("Sending messagMap clear message for {} ...", userId);
            	UserMessage userMessage = new UserMessage(userId, true);
                Message msg = new Message(null, null, userMessage);
                clusterChannel.send(msg);
            } catch (Exception e) {
                log.error("Error sending JGroups clear message", e);
            }
        }
    }
 
Example #28
Source File: JChannelWrapper.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void send(org.jgroups.Message msg) throws Exception {
   if (logger.isTraceEnabled())
      logger.trace(this + "::Sending JGroups Message: Open=" + channel.isOpen() + " on channel " + channelName + " msg=" + msg);
   if (!manager.isLoopbackMessages()) {
      msg.setTransientFlag(Message.TransientFlag.DONT_LOOPBACK);
   }
   channel.send(msg);
}
 
Example #29
Source File: JGroupsMessagingServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final Message msg) {
    try {
        connect(clusterName);
        LOGGER.info("Sending msg {}", msg);
        LOGGER.info("Msg content = {}", msg.getObject());
        channel.send(msg);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new MessagingServiceException("Failed to deliver message!", e);
    }
}
 
Example #30
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void sendToCluster(TransferableChatMessage message){
    if (clustered) {
        try {
            log.debug("Sending message ({}) id:{}, channelId:{} to cluster ...", message.getType(), message.getId(), message.getChannelId());
            Message msg = new Message(null, message);
            clusterChannel.send(msg);
        } catch (Exception e) {
            log.error("Error sending JGroups message", e);
        }
    }
}