use of org.apache.ignite.lang.IgnitePredicate in project ignite by apache.
the class GridCachePartitionedUnloadEventsSelfTest method checkPartitionUnloadEvents.
/**
* @param evts Events.
* @param g Grid.
* @param parts Parts.
*/
private void checkPartitionUnloadEvents(Collection<Event> evts, Ignite g, Collection<GridDhtLocalPartition> parts) {
assertEquals(parts.size(), evts.size());
for (Event evt : evts) {
CacheRebalancingEvent unloadEvt = (CacheRebalancingEvent) evt;
final int part = unloadEvt.partition();
assertNotNull("Unexpected partition: " + part, F.find(parts, null, new IgnitePredicate<GridDhtLocalPartition>() {
@Override
public boolean apply(GridDhtLocalPartition e) {
return e.id() == part;
}
}));
assertEquals(g.cache(DEFAULT_CACHE_NAME).getName(), unloadEvt.cacheName());
assertEquals(g.cluster().localNode().id(), unloadEvt.node().id());
}
}
use of org.apache.ignite.lang.IgnitePredicate in project ignite by apache.
the class TcpCommunicationSpi method resetNioServer.
/**
* Recreates tpcSrvr socket instance.
*
* @return Server instance.
* @throws IgniteCheckedException Thrown if it's not possible to create server.
*/
private GridNioServer<Message> resetNioServer() throws IgniteCheckedException {
if (boundTcpPort >= 0)
throw new IgniteCheckedException("Tcp NIO server was already created on port " + boundTcpPort);
IgniteCheckedException lastEx = null;
// If configured TCP port is busy, find first available in range.
int lastPort = locPortRange == 0 ? locPort : locPort + locPortRange - 1;
for (int port = locPort; port <= lastPort; port++) {
try {
MessageFactory msgFactory = new MessageFactory() {
private MessageFactory impl;
@Nullable
@Override
public Message create(short type) {
if (impl == null)
impl = getSpiContext().messageFactory();
assert impl != null;
return impl.create(type);
}
};
GridNioMessageReaderFactory readerFactory = new GridNioMessageReaderFactory() {
private MessageFormatter formatter;
@Override
public MessageReader reader(GridNioSession ses, MessageFactory msgFactory) throws IgniteCheckedException {
if (formatter == null)
formatter = getSpiContext().messageFormatter();
assert formatter != null;
ConnectionKey key = ses.meta(CONN_IDX_META);
return key != null ? formatter.reader(key.nodeId(), msgFactory) : null;
}
};
GridNioMessageWriterFactory writerFactory = new GridNioMessageWriterFactory() {
private MessageFormatter formatter;
@Override
public MessageWriter writer(GridNioSession ses) throws IgniteCheckedException {
if (formatter == null)
formatter = getSpiContext().messageFormatter();
assert formatter != null;
ConnectionKey key = ses.meta(CONN_IDX_META);
return key != null ? formatter.writer(key.nodeId()) : null;
}
};
GridDirectParser parser = new GridDirectParser(log.getLogger(GridDirectParser.class), msgFactory, readerFactory);
IgnitePredicate<Message> skipRecoveryPred = new IgnitePredicate<Message>() {
@Override
public boolean apply(Message msg) {
return msg instanceof RecoveryLastReceivedMessage;
}
};
boolean clientMode = Boolean.TRUE.equals(ignite.configuration().isClientMode());
IgniteBiInClosure<GridNioSession, Integer> queueSizeMonitor = !clientMode && slowClientQueueLimit > 0 ? new CI2<GridNioSession, Integer>() {
@Override
public void apply(GridNioSession ses, Integer qSize) {
checkClientQueueSize(ses, qSize);
}
} : null;
GridNioFilter[] filters;
if (isSslEnabled()) {
GridNioSslFilter sslFilter = new GridNioSslFilter(ignite.configuration().getSslContextFactory().create(), true, ByteOrder.nativeOrder(), log);
sslFilter.directMode(true);
sslFilter.wantClientAuth(true);
sslFilter.needClientAuth(true);
filters = new GridNioFilter[] { new GridNioCodecFilter(parser, log, true), new GridConnectionBytesVerifyFilter(log), sslFilter };
} else
filters = new GridNioFilter[] { new GridNioCodecFilter(parser, log, true), new GridConnectionBytesVerifyFilter(log) };
GridNioServer<Message> srvr = GridNioServer.<Message>builder().address(locHost).port(port).listener(srvLsnr).logger(log).selectorCount(selectorsCnt).igniteInstanceName(igniteInstanceName).serverName("tcp-comm").tcpNoDelay(tcpNoDelay).directBuffer(directBuf).byteOrder(ByteOrder.nativeOrder()).socketSendBufferSize(sockSndBuf).socketReceiveBufferSize(sockRcvBuf).sendQueueLimit(msgQueueLimit).directMode(true).metricsListener(metricsLsnr).writeTimeout(sockWriteTimeout).selectorSpins(selectorSpins).filters(filters).writerFactory(writerFactory).skipRecoveryPredicate(skipRecoveryPred).messageQueueSizeListener(queueSizeMonitor).readWriteSelectorsAssign(usePairedConnections).build();
boundTcpPort = port;
// Ack Port the TCP server was bound to.
if (log.isInfoEnabled()) {
log.info("Successfully bound communication NIO server to TCP port " + "[port=" + boundTcpPort + ", locHost=" + locHost + ", selectorsCnt=" + selectorsCnt + ", selectorSpins=" + srvr.selectorSpins() + ", pairedConn=" + usePairedConnections + ']');
}
srvr.idleTimeout(idleConnTimeout);
return srvr;
} catch (IgniteCheckedException e) {
if (X.hasCause(e, SSLException.class))
throw new IgniteSpiException("Failed to create SSL context. SSL factory: " + ignite.configuration().getSslContextFactory() + '.', e);
lastEx = e;
if (log.isDebugEnabled())
log.debug("Failed to bind to local port (will try next port within range) [port=" + port + ", locHost=" + locHost + ']');
onException("Failed to bind to local port (will try next port within range) [port=" + port + ", locHost=" + locHost + ']', e);
}
}
// If free port wasn't found.
throw new IgniteCheckedException("Failed to bind to any port within range [startPort=" + locPort + ", portRange=" + locPortRange + ", locHost=" + locHost + ']', lastEx);
}
use of org.apache.ignite.lang.IgnitePredicate in project ignite by apache.
the class GridEventConsumeSelfTest method testNodeJoinWithP2P.
/**
* TODO: IGNITE-585.
*
* @throws Exception If failed.
*/
public void testNodeJoinWithP2P() throws Exception {
fail("https://issues.apache.org/jira/browse/IGNITE-585");
final Collection<UUID> nodeIds = new HashSet<>();
final AtomicInteger cnt = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(GRID_CNT + 1);
ClassLoader ldr = getExternalClassLoader();
IgnitePredicate<ClusterNode> prjPred = (IgnitePredicate<ClusterNode>) ldr.loadClass(PRJ_PRED_CLS_NAME).newInstance();
IgnitePredicate<Event> filter = (IgnitePredicate<Event>) ldr.loadClass(FILTER_CLS_NAME).newInstance();
UUID consumeId = events(grid(0).cluster().forPredicate(prjPred)).remoteListen(new P2<UUID, Event>() {
@Override
public boolean apply(UUID nodeId, Event evt) {
info("Event from " + nodeId + " [" + evt.shortDisplay() + ']');
assertEquals(EVT_JOB_STARTED, evt.type());
nodeIds.add(nodeId);
cnt.incrementAndGet();
latch.countDown();
return true;
}
}, filter, EVT_JOB_STARTED);
try {
assertNotNull(consumeId);
startGrid("anotherGrid");
grid(0).compute().broadcast(F.noop());
assert latch.await(2, SECONDS);
assertEquals(GRID_CNT + 1, nodeIds.size());
assertEquals(GRID_CNT + 1, cnt.get());
} finally {
stopGrid("anotherGrid");
grid(0).events().stopRemoteListen(consumeId);
}
}
use of org.apache.ignite.lang.IgnitePredicate in project ignite by apache.
the class IgniteClientReconnectApiExceptionTest method igniteOperationsTest.
/**
* @throws Exception If failed.
*/
@SuppressWarnings("unchecked")
public void igniteOperationsTest() throws Exception {
clientMode = true;
final Ignite client = startGrid(serverCount());
final IgniteCache<Object, Object> dfltCache = client.cache(DEFAULT_CACHE_NAME);
final CountDownLatch recvLatch = new CountDownLatch(1);
assertNotNull(dfltCache);
doTestIgniteOperationOnDisconnect(client, Arrays.asList(// Check compute.
new T2<Callable, C1<Object, Boolean>>(new Callable() {
@Override
public Object call() throws Exception {
boolean failed = false;
try {
client.compute();
} catch (IgniteClientDisconnectedException e) {
failed = true;
checkAndWait(e);
}
assertTrue(failed);
return client.compute();
}
}, new C1<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
IgniteCompute comp = (IgniteCompute) o;
Collection<UUID> uuids = comp.broadcast(new IgniteCallable<UUID>() {
@IgniteInstanceResource
private Ignite ignite;
@Override
public UUID call() throws Exception {
return ignite.cluster().localNode().id();
}
});
assertFalse(uuids.isEmpty());
for (UUID uuid : uuids) assertNotNull(uuid);
return true;
}
}), // Check ping node.
new T2<Callable, C1<Object, Boolean>>(new Callable() {
@Override
public Object call() throws Exception {
boolean failed = false;
try {
client.cluster().pingNode(new UUID(0, 0));
} catch (IgniteClientDisconnectedException e) {
failed = true;
checkAndWait(e);
}
assertTrue(failed);
return client.cluster().pingNode(new UUID(0, 0));
}
}, new C1<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
Boolean pingNode = (Boolean) o;
assertFalse(pingNode);
return true;
}
}), // Check register remote listener.
new T2<Callable, C1<Object, Boolean>>(new Callable() {
@Override
public Object call() throws Exception {
boolean failed = false;
try {
client.events().remoteListen(null, new IgnitePredicate<Event>() {
@Override
public boolean apply(Event event) {
return true;
}
});
} catch (IgniteClientDisconnectedException e) {
failed = true;
checkAndWait(e);
}
assertTrue(failed);
return client.events().remoteListen(null, new IgnitePredicate<Event>() {
@Override
public boolean apply(Event event) {
return true;
}
});
}
}, new C1<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
UUID remoteId = (UUID) o;
assertNotNull(remoteId);
client.events().stopRemoteListen(remoteId);
return true;
}
}), // Check message operation.
new T2<Callable, C1<Object, Boolean>>(new Callable() {
@Override
public Object call() throws Exception {
boolean failed = false;
try {
client.message().remoteListen(null, new IgniteBiPredicate<UUID, Object>() {
@Override
public boolean apply(UUID uuid, Object o) {
if (o.equals("Test message."))
recvLatch.countDown();
return true;
}
});
} catch (IgniteClientDisconnectedException e) {
failed = true;
checkAndWait(e);
}
assertTrue(failed);
return client.message().remoteListen(null, new IgniteBiPredicate<UUID, Object>() {
@Override
public boolean apply(UUID uuid, Object o) {
if (o.equals("Test message."))
recvLatch.countDown();
return true;
}
});
}
}, new C1<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
assertNotNull(o);
IgniteMessaging msg = client.message();
msg.send(null, "Test message.");
try {
assertTrue(recvLatch.await(2, SECONDS));
} catch (InterruptedException ignored) {
fail("Message wasn't received.");
}
return true;
}
}), // Check executor.
new T2<Callable, C1<Object, Boolean>>(new Callable() {
@Override
public Object call() throws Exception {
boolean failed = false;
try {
client.executorService().submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 42;
}
});
} catch (IgniteClientDisconnectedException e) {
failed = true;
checkAndWait(e);
}
assertTrue(failed);
return client.executorService().submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 42;
}
});
}
}, new C1<Object, Boolean>() {
@Override
public Boolean apply(Object o) {
assertNotNull(o);
Future<Integer> fut = (Future<Integer>) o;
try {
assertEquals(42, (int) fut.get());
} catch (Exception ignored) {
fail("Failed submit task.");
}
return true;
}
})));
clientMode = false;
}
use of org.apache.ignite.lang.IgnitePredicate in project ignite by apache.
the class WebSessionSelfTest method testInvalidatedSession.
/**
* Tests invalidated sessions.
*
* @throws Exception Exception If failed.
*/
public void testInvalidatedSession() throws Exception {
String invalidatedSesId;
Server srv = null;
try {
srv = startServer(TEST_JETTY_PORT, "/modules/core/src/test/config/websession/example-cache.xml", null, new InvalidatedSessionServlet());
Ignite ignite = G.ignite();
URLConnection conn = new URL("http://localhost:" + TEST_JETTY_PORT + "/ignitetest/invalidated").openConnection();
conn.connect();
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
// checks if the old session object is invalidated.
invalidatedSesId = rdr.readLine();
assertNotNull(invalidatedSesId);
if (!keepBinary()) {
IgniteCache<String, HttpSession> cache = ignite.cache(getCacheName());
assertNotNull(cache);
HttpSession invalidatedSes = cache.get(invalidatedSesId);
assertNull(invalidatedSes);
// requests to subsequent getSession() returns null.
String ses = rdr.readLine();
assertEquals("null", ses);
} else {
IgniteCache<String, WebSessionEntity> cache = ignite.cache(getCacheName());
assertNotNull(cache);
WebSessionEntity invalidatedSes = cache.get(invalidatedSesId);
assertNull(invalidatedSes);
// requests to subsequent getSession() returns null.
String ses = rdr.readLine();
assertEquals("null", ses);
}
}
// put and update.
final CountDownLatch latch = new CountDownLatch(2);
final IgnitePredicate<Event> putLsnr = new IgnitePredicate<Event>() {
@Override
public boolean apply(Event evt) {
assert evt != null;
latch.countDown();
return true;
}
};
ignite.events().localListen(putLsnr, EVT_CACHE_OBJECT_PUT);
// new request that creates a new session.
conn = new URL("http://localhost:" + TEST_JETTY_PORT + "/ignitetest/valid").openConnection();
conn.addRequestProperty("Cookie", "JSESSIONID=" + invalidatedSesId);
conn.connect();
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String sesId = rdr.readLine();
assertFalse(sesId.equals("null"));
assertTrue(latch.await(10, TimeUnit.SECONDS));
if (!keepBinary()) {
IgniteCache<String, HttpSession> cache = ignite.cache(getCacheName());
assertNotNull(cache);
HttpSession ses = cache.get(sesId);
assertNotNull(ses);
assertEquals("val10", ses.getAttribute("key10"));
} else {
IgniteCache<String, WebSessionEntity> cache = ignite.cache(getCacheName());
assertNotNull(cache);
WebSessionEntity entity = cache.get(sesId);
assertNotNull(entity);
final Marshaller marshaller = ignite.configuration().getMarshaller();
assertEquals("val10", marshaller.unmarshal(entity.attributes().get("key10"), getClass().getClassLoader()));
}
}
} finally {
stopServer(srv);
}
}
Aggregations