org.jgroups.JChannel Java Examples

The following examples show how to use org.jgroups.JChannel. 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: JBossServer.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException {
    try {
        try {
            String clusterName = exchange.getRequestHeaders().getFirst(CLUSTER_NAME);
            JChannel channel = server.getChannel(clusterName);
            try (InputStream stream = exchange.getRequestBody()) {
                handlePingRequest(channel, stream);
            }
            exchange.sendResponseHeaders(200, RESPONSE_BYTES.length);
            exchange.getResponseBody().write(RESPONSE_BYTES);
        } catch (Exception e) {
            throw new IOException(e);
        }
    } finally {
        exchange.close();
    }
}
 
Example #2
Source File: ActiveMQRaUtils.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Within AS7 the RA is loaded by JCA. properties can only be passed in String form. However if
 * RA is configured using jgroups stack, we need to pass a Channel object. As is impossible with
 * JCA, we use this method to allow a JChannel object to be located.
 */
public static JChannel locateJGroupsChannel(final String locatorClass, final String name) {
   return AccessController.doPrivileged(new PrivilegedAction<JChannel>() {
      @Override
      public JChannel run() {
         try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> aClass = loader.loadClass(locatorClass);
            Object o = aClass.newInstance();
            Method m = aClass.getMethod("locateChannel", new Class[]{String.class});
            return (JChannel) m.invoke(o, name);
         } catch (Throwable e) {
            ActiveMQRALogger.LOGGER.debug(e.getMessage(), e);
            return null;
         }
      }
   });
}
 
Example #3
Source File: JGroupsChannelBroadcastGroupControlTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();

   TransportConfiguration connectorConfiguration = new TransportConfiguration(NETTY_CONNECTOR_FACTORY);
   List<String> connectorInfos = new ArrayList<>();
   connectorInfos.add(connectorConfiguration.getName());
   PlainConfigurator configurator = new PlainConfigurator(jgroupsConfigString);
   JChannel channel = new JChannel(configurator);

   String channelName1 = "channel1";
   ChannelBroadcastEndpointFactory endpointFactory = new ChannelBroadcastEndpointFactory(channel, channelName1);
   broadcastGroupConfig = new BroadcastGroupConfiguration().setName(RandomUtil.randomString()).setBroadcastPeriod(RandomUtil.randomPositiveInt()).setConnectorInfos(connectorInfos).setEndpointFactory(endpointFactory);

   Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true).addConnectorConfiguration(connectorConfiguration.getName(), connectorConfiguration).addBroadcastGroupConfiguration(broadcastGroupConfig);
   server = addServer(ActiveMQServers.newActiveMQServer(config, mbeanServer, false));
   server.start();

   broadcastGroupControl = createManagementControl(broadcastGroupConfig.getName());
}
 
Example #4
Source File: SolverServerImplementation.java    From unitime with Apache License 2.0 6 votes vote down vote up
public SolverServerImplementation(boolean local, JChannel channel) {
	super();
	
	iLocal = local;
	iChannel = channel;
	// iChannel.setReceiver(this);
	iChannel.setUpHandler(new MuxUpHandler());
	iDispatcher = new MuxRpcDispatcher(SCOPE_SERVER, channel, this, this, this);
	
	iCourseSolverContainer = new CourseSolverContainerRemote(channel, SCOPE_COURSE, local);
	iExamSolverContainer = new ExaminationSolverContainerRemote(channel, SCOPE_EXAM);
	iStudentSolverContainer = new StudentSolverContainerRemote(channel, SCOPE_STUDENT);
	iInstructorSchedulingContainer = new InstructorSchedulingContainerRemote(channel, SCOPE_INSTRUCTOR);
	iOnlineStudentSchedulingContainer = new OnlineStudentSchedulingContainerRemote(channel, SCOPE_ONLINE);
	iRemoteRoomAvailability = new RemoteRoomAvailability(channel, SCOPE_AVAILABILITY);
	iUpdater = new OnlineStudentSchedulingGenericUpdater(iDispatcher, iOnlineStudentSchedulingContainer);
	iRemoteQueueProcessor = new RemoteQueueProcessor(channel, SCOPE_QUEUE_PROCESSOR);
}
 
Example #5
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 #6
Source File: TestCacheResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/jgroups-stats")
@Produces(MediaType.APPLICATION_JSON)
public JGroupsStats getJgroupsStats() {
    Transport transport = cache.getCacheManager().getTransport();
    if (transport == null) {
        return new JGroupsStats(0, 0, 0, 0);
    } else {
        try {
            // Need to use reflection due some incompatibilities between ispn 8.2.6 and 9.0.1
            JChannel channel = (JChannel) transport.getClass().getMethod("getChannel").invoke(transport);

            return new JGroupsStats(channel.getSentBytes(), channel.getSentMessages(), channel.getReceivedBytes(), channel.getReceivedMessages());
        } catch (Exception nsme) {
            throw new RuntimeException(nsme);
        }
    }
}
 
Example #7
Source File: JBossServer.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
public synchronized boolean start(JChannel channel) throws Exception {
    boolean started = false;
    if (server == null) {
        try {
            InetSocketAddress address = new InetSocketAddress("0.0.0.0", port);
            server = HttpServer.create(address, 0);
            server.setExecutor(Executors.newCachedThreadPool());
            server.createContext("/", new Handler(this));
            server.start();
            started = true;
        } catch (Exception e) {
            server = null;
            throw e;
        }
    }
    addChannel(channel);
    return started;
}
 
Example #8
Source File: JDKServer.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
public synchronized boolean start(JChannel channel) throws Exception {
    boolean started = false;
    if (server == null) {
        try {
            InetSocketAddress address = new InetSocketAddress("0.0.0.0", port);
            server = HttpServer.create(address, 0);
            server.setExecutor(Executors.newCachedThreadPool());
            server.createContext("/", new Handler(this));
            server.start();
            started = true;
        } catch (Exception e) {
            server = null;
            throw e;
        }
    }
    addChannel(channel);
    return started;
}
 
Example #9
Source File: ElectionsTest.java    From jgroups-raft with Apache License 2.0 6 votes vote down vote up
/** If expected is null, then any member can be a leader */
protected static Address assertLeader(int times, long sleep, Address expected, JChannel... channels) {
    // wait until there is 1 leader
    for(int i=0; i < times; i++) {
        List<Address> leaders=leaders(channels);
        if(!leaders.isEmpty()) {
            int size=leaders.size();
            assert size <= 1;
            Address leader=leaders.get(0);
            System.out.println("leader: " + leader);
            assert expected == null || expected.equals(leader);
            break;
        }

        Util.sleep(sleep);
    }
    List<Address> leaders=leaders(channels);
    assert leaders.size() == 1 : "leaders=" + leaders;
    Address leader=leaders.get(0);
    System.out.println("leader = " + leader);
    return leader;
}
 
Example #10
Source File: ActiveMQResourceAdapter.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected BroadcastEndpointFactory createBroadcastEndpointFactory(final ConnectionFactoryProperties overrideProperties) {

      String discoveryAddress = overrideProperties.getDiscoveryAddress() != null ? overrideProperties.getDiscoveryAddress() : getDiscoveryAddress();
      if (discoveryAddress != null) {
         Integer discoveryPort = overrideProperties.getDiscoveryPort() != null ? overrideProperties.getDiscoveryPort() : getDiscoveryPort();
         if (discoveryPort == null) {
            discoveryPort = ActiveMQClient.DEFAULT_DISCOVERY_PORT;
         }

         String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress() : raProperties.getDiscoveryLocalBindAddress();
         return new UDPBroadcastEndpointFactory().setGroupAddress(discoveryAddress).setGroupPort(discoveryPort).setLocalBindAddress(localBindAddress).setLocalBindPort(-1);
      }

      String jgroupsChannel = overrideProperties.getJgroupsChannelName() != null ? overrideProperties.getJgroupsChannelName() : getJgroupsChannelName();

      String jgroupsLocatorClassName = raProperties.getJgroupsChannelLocatorClass();
      if (jgroupsLocatorClassName != null) {
         String jchannelRefName = raProperties.getJgroupsChannelRefName();
         JChannel jchannel = ActiveMQRaUtils.locateJGroupsChannel(jgroupsLocatorClassName, jchannelRefName);
         return new ChannelBroadcastEndpointFactory(jchannel, jgroupsChannel);
      }

      String jgroupsFileName = overrideProperties.getJgroupsFile() != null ? overrideProperties.getJgroupsFile() : getJgroupsFile();
      if (jgroupsFileName != null) {
         return new JGroupsFileBroadcastEndpointFactory().setChannelName(jgroupsChannel).setFile(jgroupsFileName);
      }

      return null;
   }
 
Example #11
Source File: DummySolverServer.java    From unitime with Apache License 2.0 5 votes vote down vote up
public DummySolverServer(JChannel channel) {
	iChannel = channel;
	iDispatcher = new MuxRpcDispatcher(SCOPE_SERVER, channel, null, null, this);
	iCourseSolverContainer = new DummyContainer<SolverProxy>(channel, SCOPE_COURSE, SolverProxy.class);
	iExamSolverContainer = new DummyContainer<ExamSolverProxy>(channel, SCOPE_EXAM, ExamSolverProxy.class);
	iStudentSolverContainer = new DummyContainer<StudentSolverProxy>(channel, SCOPE_STUDENT, StudentSolverProxy.class);
	iInstructorSchedulingContainer = new DummyContainer<InstructorSchedulingProxy>(channel, SCOPE_INSTRUCTOR, InstructorSchedulingProxy.class);
	iOnlineStudentSchedulingContainer = new ReplicatedDummyContainer<OnlineSectioningServer>(channel, SCOPE_ONLINE, OnlineSectioningServer.class);
	iRoomAvailabilityDispatcher = new MuxRpcDispatcher(SCOPE_AVAILABILITY, channel, null, null, this);
	
	iCourseSolverContainerWrapper = new SolverContainerWrapper<SolverProxy>(iDispatcher, iCourseSolverContainer, false);
	iExamSolverContainerWrapper = new SolverContainerWrapper<ExamSolverProxy>(iDispatcher, iExamSolverContainer, false);
	iStudentSolverContainerWrapper = new SolverContainerWrapper<StudentSolverProxy>(iDispatcher, iStudentSolverContainer, false);
	iOnlineStudentSchedulingContainerWrapper = new SolverContainerWrapper<OnlineSectioningServer>(iDispatcher, iOnlineStudentSchedulingContainer, false);
}
 
Example #12
Source File: DynamicMembershipTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected void close(boolean remove_log, boolean remove_snapshot, JChannel ... channels) {
    for(JChannel ch: channels) {
        if(ch == null)
            continue;
        RAFT raft=ch.getProtocolStack().findProtocol(RAFT.class);
        if(remove_log)
            raft.log().delete(); // remove log files after the run
        if(remove_snapshot)
            raft.deleteSnapshot();
        Util.close(ch);
    }
}
 
Example #13
Source File: ElectionsTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static void setLog(JChannel ch, int... terms) {
    RAFT raft=ch.getProtocolStack().findProtocol(RAFT.class);
    Log log=raft.log();
    int index=log.lastAppended();
    for(int term: terms)
        log.append(++index, true, new LogEntry(term, BUF));
}
 
Example #14
Source File: HibernateChannelLookup.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public Channel getJGroupsChannel(Properties p) {
	try {
		return new JChannel(JGroupsUtils.getConfigurator(ApplicationProperty.HibernateClusterConfiguration.value()));
	} catch (Exception e) {
		Debug.error(e.getMessage(), e);
		return null;
	}
}
 
Example #15
Source File: SectioningChannelLookup.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public Channel getJGroupsChannel(Properties p) {
	try {
		if (ApplicationProperty.OnlineSchedulingClusterForkChannel.isTrue()) {
			return new ForkChannel(super.getJGroupsChannel(p), "forked-stack", "sectioning-channel",
					true, ProtocolStack.ABOVE, FRAG2.class,
					new RSVP().setValue("timeout", 60000).setValue("resend_interval", 500).setValue("ack_on_delivery", false));
		} else {
			return new JChannel(JGroupsUtils.getConfigurator(ApplicationProperty.OnlineSchedulingClusterConfiguration.value()));
		}
	} catch (Exception e) {
		Debug.error(e.getMessage(), e);
		return null;
	}
}
 
Example #16
Source File: AbstractServer.java    From openshift-ping with Apache License 2.0 5 votes vote down vote up
private String getClusterName(final JChannel channel) {
    if (channel != null) {
        String clusterName = channel.getClusterName();
        // clusterName will be null if the Channel is not yet connected, but we still need it!
        if (clusterName == null) {
            try {
                Field field = JChannel.class.getDeclaredField("cluster_name");
                field.setAccessible(true);
                return (String)field.get(channel);
            } catch (Throwable t) {}
        }
    }
    return null;
}
 
Example #17
Source File: AbstractServer.java    From openshift-ping with Apache License 2.0 5 votes vote down vote up
public final JChannel getChannel(String clusterName) {
    if (clusterName != null) {
        synchronized (CHANNELS) {
            return CHANNELS.get(clusterName);
        }
    }
    return null;
}
 
Example #18
Source File: ConnectionFactoryWithJGroupsSerializationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   try {
      super.setUp();

      PlainConfigurator configurator = new PlainConfigurator(jgroupsConfigString);
      channel = new JChannel(configurator);

      String channelName1 = "channel1";
      String channelName2 = "channel2";

      BroadcastEndpointFactory jgroupsBroadcastCfg1 = new ChannelBroadcastEndpointFactory(channel, channelName1);
      BroadcastEndpointFactory jgroupsBroadcastCfg2 = new JGroupsFileBroadcastEndpointFactory().setChannelName(channelName2).setFile(jgroupsConfigString);

      DiscoveryGroupConfiguration dcConfig1 = new DiscoveryGroupConfiguration().setName("dg1").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(jgroupsBroadcastCfg1);

      DiscoveryGroupConfiguration dcConfig2 = new DiscoveryGroupConfiguration().setName("dg2").setRefreshTimeout(5000).setDiscoveryInitialWaitTimeout(5000).setBroadcastEndpointFactory(jgroupsBroadcastCfg2);

      jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig1.getName(), dcConfig1);
      jmsServer.getActiveMQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig2.getName(), dcConfig2);

      jmsServer.createConnectionFactory("ConnectionFactory1", false, JMSFactoryType.CF, dcConfig1.getName(), "/ConnectionFactory1");

      jmsServer.createConnectionFactory("ConnectionFactory2", false, JMSFactoryType.CF, dcConfig2.getName(), "/ConnectionFactory2");

      testQueue = createQueue("testQueueFor1389");
   } catch (Exception e) {
      e.printStackTrace();
      throw e;
   }
}
 
Example #19
Source File: VoteTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static Address leader(long timeout, long interval, JChannel ... channels) {
    long target_time=System.currentTimeMillis() + timeout;
    while(System.currentTimeMillis() <= target_time) {
        for(JChannel ch : channels) {
            if(ch.isConnected() && raft(ch).leader() != null)
                return raft(ch).leader();
        }
        Util.sleep(interval);
    }
    return null;
}
 
Example #20
Source File: DynamicMembershipTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected void assertSameLeader(Address leader, JChannel ... channels) {
    for(JChannel ch: channels) {
        final Address raftLeader = raft(ch).leader();
        assert leader.equals(raftLeader)
            : String.format("expected leader to be '%s' but was '%s'", leader, raftLeader);
    }
}
 
Example #21
Source File: DynamicMembershipTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected JChannel create(String name) throws Exception {
    RAFT raft=new RAFT().members(mbrs).raftId(name).stateMachine(new DummyStateMachine())
      .logClass("org.jgroups.protocols.raft.InMemoryLog").logName(name + "-" + CLUSTER);
    JChannel ch=new JChannel(Util.getTestStack(new ELECTION(), raft, new REDIRECT())).name(name);
    ch.connect(CLUSTER);
    return ch;
}
 
Example #22
Source File: JGroupsFileBroadcastEndpoint.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JChannel createChannel() throws Exception {
   URL configURL = Thread.currentThread().getContextClassLoader().getResource(file);

   if (configURL == null) {
      throw new RuntimeException("couldn't find JGroups configuration " + file);
   }

   return new JChannel(configURL);
}
 
Example #23
Source File: VoteTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static int nonLeader(JChannel ... channels) {
    for(int i=channels.length-1; i >= 0; i--) {
        JChannel ch=channels[i];
        if(!ch.isConnected())
            continue;
        if(!raft(ch).leader().equals(ch.getAddress()))
            return i;
    }
    return -1;
}
 
Example #24
Source File: RaftHandle.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a RaftHandle instance.
 * @param ch The channel over which to create the RaftHandle. Must be non-null, but doesn't yet need to be connected
 * @param sm An implementation of {@link StateMachine}.
 *           Can be null, ie. if it is set later via {@link #stateMachine(StateMachine)}.
 */
public RaftHandle(JChannel ch, StateMachine sm) {
    if((this.ch=ch) == null)
        throw new IllegalStateException("channel must not be null");
    if((raft=RAFT.findProtocol(RAFT.class, ch.getProtocolStack().getTopProtocol(),true)) == null)
        throw new IllegalStateException("RAFT protocol was not found");
    if((settable=RAFT.findProtocol(Settable.class, ch.getProtocolStack().getTopProtocol(),true)) == null)
        throw new IllegalStateException("did not find a protocol implementing Settable (e.g. REDIRECT or RAFT)");
    stateMachine(sm);
}
 
Example #25
Source File: AppendEntriesTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static void close(boolean remove_log, boolean remove_snapshot, JChannel... channels) {
    for(JChannel ch: channels) {
        if(ch == null)
            continue;
        RAFT raft=ch.getProtocolStack().findProtocol(RAFT.class);
        if(remove_log)
            raft.log().delete(); // remove log files after the run
        if(remove_snapshot)
            raft.deleteSnapshot();
        Util.close(ch);
    }
}
 
Example #26
Source File: DistributedCacheConcurrentWritesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void printStats(BasicCache cache) {
    if (cache instanceof Cache) {
        Cache cache1 = (Cache) cache;

        JChannel channel = ((JGroupsTransport)cache1.getAdvancedCache().getRpcManager().getTransport()).getChannel();

        System.out.println("Sent MB: " + channel.getSentBytes() / 1000000 + ", sent messages: " + channel.getSentMessages() + ", received MB: " + channel.getReceivedBytes() / 1000000 +
                ", received messages: " + channel.getReceivedMessages());
    } else {
        Map<String, String> stats = ((RemoteCache) cache).stats().getStatsMap();
        System.out.println("Stats: " + stats);
    }
}
 
Example #27
Source File: AppendEntriesTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static void assertLeader(JChannel ch, long timeout, long interval) {
    RAFT raft=raft(ch);
    long stop_time=System.currentTimeMillis() + timeout;
    while(System.currentTimeMillis() < stop_time) {
        if(raft.isLeader())
            break;
        Util.sleep(interval);
    }
    assert raft.isLeader();
}
 
Example #28
Source File: DynamicMembershipTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected JChannel channel(Address addr) {
    for(JChannel ch: Arrays.asList(channels)) {
        if(ch.getAddress() != null && ch.getAddress().equals(addr))
            return ch;
    }
    return null;
}
 
Example #29
Source File: ElectionsTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static void close(boolean remove_log, boolean remove_snapshot, JChannel... channels) {
    for(JChannel ch: channels) {
        if(ch == null)
            continue;
        close(remove_log, remove_snapshot, ch);
    }
}
 
Example #30
Source File: VoteTest.java    From jgroups-raft with Apache License 2.0 5 votes vote down vote up
protected static JChannel create(String name, List<String> mbrs) throws Exception {
    RAFT raft=new RAFT().members(mbrs).raftId(name).stateMachine(new DummyStateMachine())
      .logClass("org.jgroups.protocols.raft.InMemoryLog").logName(name + "-" + CLUSTER);
    JChannel ch=new JChannel(Util.getTestStack(new ELECTION(), raft, new REDIRECT())).name(name);
    ch.connect(CLUSTER);
    return ch;
}