@Test public void pingPong() throws Exception { connect(); Utils.rollMockClock(0); // No ping pong happened yet. assertEquals(Long.MAX_VALUE, peer.getLastPingTime()); assertEquals(Long.MAX_VALUE, peer.getPingTime()); ListenableFuture<Long> future = peer.ping(); assertEquals(Long.MAX_VALUE, peer.getLastPingTime()); assertEquals(Long.MAX_VALUE, peer.getPingTime()); assertFalse(future.isDone()); Ping pingMsg = (Ping) outbound(writeTarget); Utils.rollMockClock(5); // The pong is returned. inbound(writeTarget, new Pong(pingMsg.getNonce())); pingAndWait(writeTarget); assertTrue(future.isDone()); long elapsed = future.get(); assertTrue("" + elapsed, elapsed > 1000); assertEquals(elapsed, peer.getLastPingTime()); assertEquals(elapsed, peer.getPingTime()); // Do it again and make sure it affects the average. future = peer.ping(); pingMsg = (Ping) outbound(writeTarget); Utils.rollMockClock(50); inbound(writeTarget, new Pong(pingMsg.getNonce())); elapsed = future.get(); assertEquals(elapsed, peer.getLastPingTime()); assertEquals(7250, peer.getPingTime()); }
/** * Check the server connection, reconnect if needed. * * <p>This function will try to ping the server if we are connected, and try to reestablish a * connection otherwise. */ public void sendServerPing() { if (mXMPPConnection == null || !mXMPPConnection.isAuthenticated()) { debugLog("Ping: requested, but not connected to server."); requestConnectionState(ConnectionState.ONLINE, false); return; } if (mPingID != null) { debugLog("Ping: requested, but still waiting for " + mPingID); return; // a ping is still on its way } if (mStreamHandler.isSmEnabled()) { debugLog("Ping: sending SM request"); mPingID = "" + mStreamHandler.requestAck(); } else { Ping ping = new Ping(); ping.setType(Type.GET); ping.setTo(mConfig.server); mPingID = ping.getPacketID(); debugLog("Ping: sending ping " + mPingID); mXMPPConnection.sendPacket(ping); } // register ping timeout handler: PACKET_TIMEOUT(30s) + 3s registerPongTimeout(PACKET_TIMEOUT + 3000, mPingID); }
@Test public void serviceRegsistrySupportsMultipleProvidersOfSameService() throws Exception { InMemoryServiceRegistry serviceRegistry = new InMemoryServiceRegistry(); astrixConfigurer.setSubsystem("default"); astrixConfigurer.set(AstrixSettings.SERVICE_REGISTRY_URI, serviceRegistry.getServiceUri()); astrixConfigurer.registerApiProvider(PingApiProvider.class); clientContext = astrixConfigurer.configure(); ServiceRegistryExporterClient server1serviceRegistryClient = new ServiceRegistryExporterClient(serviceRegistry, "default", "server-1"); server1serviceRegistryClient.register( Ping.class, DirectComponent.registerAndGetProperties(Ping.class, new PingImpl("1")), Integer.MAX_VALUE); ServiceRegistryExporterClient server2serviceRegistryClient = new ServiceRegistryExporterClient(serviceRegistry, "default", "server-2"); server2serviceRegistryClient.register( Ping.class, DirectComponent.registerAndGetProperties(Ping.class, new PingImpl("2")), Integer.MAX_VALUE); Ping ping1 = clientContext.getBean(Ping.class); ServiceRegistryClient serviceRegistryClient = clientContext.getBean(ServiceRegistryClient.class); List<ServiceProperties> providers = serviceRegistryClient.list(AstrixBeanKey.create(Ping.class)); assertEquals(2, providers.size()); assertNotNull(ping1.ping()); }
@Test public void executeWithPool() throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); PoolFiberFactory fact = new PoolFiberFactory(exec); PingPongChannels channels = new PingPongChannels(); final CountDownLatch onstop = new CountDownLatch(2); Disposable dispose = new Disposable() { public void dispose() { onstop.countDown(); } }; Fiber pingThread = fact.create(); pingThread.add(dispose); Ping ping = new Ping(channels, pingThread, 100000); Fiber pongThread = fact.create(); pongThread.add(dispose); Pong pong = new Pong(channels, pongThread); pong.start(); ping.start(); // wait for fibers to be disposed. Assert.assertTrue(onstop.await(60, TimeUnit.SECONDS)); // destroy thread pool exec.shutdown(); }
@Test public void doesNotBindToNonPublishedProvidersInOtherZones() throws Exception { InMemoryServiceRegistry serviceRegistry = new InMemoryServiceRegistry(); astrixConfigurer.setSubsystem("default"); astrixConfigurer.set(AstrixSettings.SERVICE_REGISTRY_URI, serviceRegistry.getServiceUri()); astrixConfigurer.registerApiProvider(PingApiProvider.class); clientContext = astrixConfigurer.configure(); ServiceRegistryExporterClient server1serviceRegistryClient = new ServiceRegistryExporterClient(serviceRegistry, "my-subsystem", "server-1"); ServiceProperties service1Properties = DirectComponent.registerAndGetProperties(Ping.class, new PingImpl("1")); service1Properties.setProperty(ServiceProperties.PUBLISHED, "false"); service1Properties.setProperty(ServiceProperties.SERVICE_ZONE, "foo-zone"); server1serviceRegistryClient.register(Ping.class, service1Properties, Integer.MAX_VALUE); ServiceRegistryClient serviceRegistryClient = clientContext.getBean(ServiceRegistryClient.class); List<ServiceProperties> providers = serviceRegistryClient.list(AstrixBeanKey.create(Ping.class)); assertEquals(1, providers.size()); Ping ping = clientContext.getBean(Ping.class); try { ping.ping(); fail("Expected service to not be available when server is INACTIVE"); } catch (ServiceUnavailableException e) { // expected } }
@Test public void bindsToNonPublishedProvidersInSameZone() throws Exception { InMemoryServiceRegistry serviceRegistry = new InMemoryServiceRegistry(); astrixConfigurer.setSubsystem("my-subsystem"); astrixConfigurer.set(AstrixSettings.SERVICE_REGISTRY_URI, serviceRegistry.getServiceUri()); astrixConfigurer.registerApiProvider(PingApiProvider.class); clientContext = astrixConfigurer.configure(); ServiceRegistryExporterClient server1serviceRegistryClient = new ServiceRegistryExporterClient(serviceRegistry, "my-subsystem", "server-1"); ServiceProperties service1Properties = DirectComponent.registerAndGetProperties(Ping.class, new PingImpl("1")); service1Properties.setProperty(ServiceProperties.PUBLISHED, "false"); server1serviceRegistryClient.register(Ping.class, service1Properties, Integer.MAX_VALUE); ServiceRegistryClient serviceRegistryClient = clientContext.getBean(ServiceRegistryClient.class); List<ServiceProperties> providers = serviceRegistryClient.list(AstrixBeanKey.create(Ping.class)); assertEquals(1, providers.size()); Ping ping = clientContext.getBean(Ping.class); assertNotNull(ping.ping()); }
public static void main(String[] args) { RMID rmid = null; System.out.println("\nRegression test for bug 4510355\n"); try { TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); /* * Install group class file in codebase. */ System.err.println("install class file in codebase"); URL groupURL = TestLibrary.installClassInCodebase("MyActivationGroupImpl", "group"); System.err.println("class file installed"); /* * Start rmid. */ RMID.removeLog(); rmid = RMID.createRMID(); String execPolicyOption = "-Dsun.rmi.activation.execPolicy=none"; rmid.addOptions(new String[] {execPolicyOption}); rmid.start(); /* * Create and register descriptors for custom group and an * activatable object in that group. */ System.err.println("register group"); Properties p = new Properties(); p.put("java.security.policy", TestParams.defaultGroupPolicy); ActivationGroupDesc groupDesc = new ActivationGroupDesc( "MyActivationGroupImpl", groupURL.toExternalForm(), null, p, null); ActivationGroupID groupID = ActivationGroup.getSystem().registerGroup(groupDesc); System.err.println("register activatable object"); ActivationDesc desc = new ActivationDesc(groupID, "DownloadActivationGroup", null, null); Ping obj = (Ping) Activatable.register(desc); /* * Start group (by calling ping). */ System.err.println("ping object (forces download of group's class)"); obj.ping(); System.err.println("TEST PASSED: group's class downloaded successfully"); System.err.println("shutdown object"); obj.shutdown(); System.err.println("TEST PASSED"); } catch (Exception e) { TestLibrary.bomb(e); } finally { rmid.cleanup(); } }
@Test public void pingDeveRetornarProfileEHorario() throws Exception { UserProfile profile = new UserProfile().withEmail("*****@*****.**"); given(userProfiles.get()).willReturn(profile); Ping ping = controller.ping(); assertThat(ping.getProfile(), is(profile)); assertThat(System.currentTimeMillis() - ping.getHorario(), is(lessThan(1000L))); }
private void close(ErrorCode connectionCode, ErrorCode streamCode) throws IOException { assert (!Thread.holdsLock(this)); IOException thrown = null; try { shutdown(connectionCode); } catch (IOException e) { thrown = e; } FramedStream[] streamsToClose = null; Ping[] pingsToCancel = null; synchronized (this) { if (!streams.isEmpty()) { streamsToClose = streams.values().toArray(new FramedStream[streams.size()]); streams.clear(); setIdle(false); } if (pings != null) { pingsToCancel = pings.values().toArray(new Ping[pings.size()]); pings = null; } } if (streamsToClose != null) { for (FramedStream stream : streamsToClose) { try { stream.close(streamCode); } catch (IOException e) { if (thrown != null) thrown = e; } } } if (pingsToCancel != null) { for (Ping ping : pingsToCancel) { ping.cancel(); } } // Close the writer to release its resources (such as deflaters). try { frameWriter.close(); } catch (IOException e) { if (thrown == null) thrown = e; } // Close the socket to break out the reader thread, which will clean up after itself. try { socket.close(); } catch (IOException e) { thrown = e; } if (thrown != null) throw thrown; }
/** * Method that is called when a Ping is received from the other Network. * * @param player The Ping that was received from the other Network. */ public void onReceivedPing(Ping ping) { if (ping.wasReceived()) { ping.calculatePing(); System.out.println("Ping: " + ping.getPing()); } else { ping.receive(); ping(ping); } }
public ArrayList<Row> getDisplayData(Context context) { ArrayList<Row> data = new ArrayList<Row>(); try { data.add(new Row("ROUND TRIP")); int pingMax = 1; for (Ping p : pings) pingMax = Math.max((int) p.measure.getAverage(), pingMax); pingMax *= 1.2; for (Ping p : pings) { ArrayList<String> str = new ArrayList<String>(); if (p != null) { if (p.measure != null) { if (p.getDst().getTagname().equals("localhost")) continue; try { data.add(new Row(new PingGraph(p, pingMax))); } catch (Exception e) { e.printStackTrace(); } } } } } catch (Exception e) { ClientLog.log(context, e, "Measurement Display"); } /*data.add(new Row("FIRST HOP")); for(LastMile p: lastMiles){ ArrayList<String> str = new ArrayList<String>(); if (p != null) { if (p.measure != null) { try { if(p.getDst().getTagname().equals("localhost")) continue; data.add(new Row(p.getDst().getTagname(),(int)p.measure.getAverage()*100/pingMax,((int)p.measure.getAverage()) +" ms")); } catch (Exception e) { e.printStackTrace(); } } } } if(isComplete) { data.add(new Row("GRAPHS")); LatencyDataSource dataSource = new LatencyDataSource(context); String connection = DeviceUtil.getNetworkInfo(context); HashMap<String,ArrayList<GraphPoint>> graphPoints = dataSource.getGraphData(); GraphData graphdata = new GraphData(graphPoints.get("ping")); graphdata.setxAxisTitle("Historical trend of Roundtrip tests for " + connection); data.add(new Row(graphdata)); //GraphData graphdata2 = new GraphData(graphPoints.get("firsthop")); //graphdata2.setxAxisTitle("Historical trend of FirstHop tests for " + connection); //data.add(new Row(graphdata2)); }*/ return data; }
@Override public void ping(boolean reply, int payload1, int payload2) { if (reply) { Ping ping = removePing(payload1); if (ping != null) { ping.receive(); } } else { // Send a reply to a client ping if this is a server and vice versa. writePingLater(true, payload1, payload2, null); } }
private void close(ErrorCode connectionCode, ErrorCode streamCode) throws IOException { assert (!Thread.holdsLock(this)); IOException thrown = null; try { shutdown(connectionCode); } catch (IOException e) { thrown = e; } SpdyStream[] streamsToClose = null; Ping[] pingsToCancel = null; synchronized (this) { if (!streams.isEmpty()) { streamsToClose = streams.values().toArray(new SpdyStream[streams.size()]); streams.clear(); setIdle(false); } if (pings != null) { pingsToCancel = pings.values().toArray(new Ping[pings.size()]); pings = null; } } if (streamsToClose != null) { for (SpdyStream stream : streamsToClose) { try { stream.close(streamCode); } catch (IOException e) { if (thrown != null) thrown = e; } } } if (pingsToCancel != null) { for (Ping ping : pingsToCancel) { ping.cancel(); } } try { frameReader.close(); } catch (IOException e) { thrown = e; } try { frameWriter.close(); } catch (IOException e) { if (thrown == null) thrown = e; } if (thrown != null) throw thrown; }
@Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeShort(eventType); out.writeInt(streamId); out.writeInt(bufferLength); }
private void writePing(boolean reply, int payload1, int payload2, Ping ping) throws IOException { synchronized (frameWriter) { // Observe the sent time immediately before performing I/O. if (ping != null) ping.send(); frameWriter.ping(reply, payload1, payload2); } }
/** The loop method that runs forever while the Socket is connected. */ public final void start() { new Thread() { public void run() { while (connection.isConnected()) { Packet packet = null; try { packet = (Packet) in.readObject(); } catch (SocketException e) { // e.printStackTrace(); break; } catch (EOFException e) { // e.printStackTrace(); break; } catch (ClassNotFoundException e) { e.printStackTrace(); break; } catch (IOException e) { e.printStackTrace(); break; } if (packet instanceof Ping) { onReceivedPing((Ping) packet); } else { onReceivedPacket(packet); } } } }.start(); }
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); eventType = in.readShort(); streamId = in.readInt(); bufferLength = in.readInt(); }
public JSONObject toJSON() { JSONObject obj = new JSONObject(); try { putSafe(obj, "time", time); putSafe(obj, "localtime", localTime); putSafe(obj, "deviceid", SHA1Util.SHA1(deviceId)); JSONArray array = new JSONArray(); try { for (Ping p : pings) { array.put(p.toJSON()); } } catch (Exception e) { } putSafe(obj, "pings", array); JSONArray tmparray = new JSONArray(); try { for (LastMile p : lastMiles) { tmparray.put(p.toJSON()); } } catch (Exception e) { } putSafe(obj, "lastmiles", tmparray); JSONArray array2 = new JSONArray(); for (Screen s : screens) { array2.put(s.toJSON()); } if (screens != null) putSafe(obj, "screens", array2); if (device != null) putSafe(obj, "device", device.toJSON()); if (throughput != null) putSafe(obj, "throughput", throughput.toJSON()); if (gps != null) putSafe(obj, "gps", gps.toJSON()); if (battery != null) putSafe(obj, "battery", battery.toJSON()); if (usage != null) putSafe(obj, "usage", usage.toJSON()); if (network != null) putSafe(obj, "network", network.toJSON()); if (warmupExperiment != null) putSafe(obj, "warmup_experiment", warmupExperiment.toJSON()); if (sim != null) putSafe(obj, "sim", sim.toJSON()); if (wifi != null) putSafe(obj, "wifi", wifi.toJSON()); if (state != null) putSafe(obj, "state", state.toJSON()); if (isManual) putSafe(obj, "isManual", 1); else putSafe(obj, "isManual", 0); if (loss != null) putSafe(obj, "loss", loss.toJSON()); if (ipdv != null) putSafe(obj, "delay_variation", ipdv.toJSON()); } catch (Exception e) { e.printStackTrace(); } printJSON(obj.toString()); return obj; }
@Test public void executWithDedicatedThreads() throws Exception { PingPongChannels channels = new PingPongChannels(); ThreadFiber pingThread = new ThreadFiber(); Ping ping = new Ping(channels, pingThread, 100000); ThreadFiber pongThread = new ThreadFiber(); Pong pong = new Pong(channels, pongThread); pong.start(); ping.start(); // wait for threads to cleanly exit pingThread.join(); pongThread.join(); }
public PingResponseBody ping(Ping ping) { PingResponseBody resp = new PingResponseBody(); String scenario = ping.getScenario(); System.out.println("scenario = " + scenario); resp.setScenario(scenario); String origin = ping.getOrigin(); System.out.println("origin = " + origin); resp.setOrigin(origin); String text = ping.getText(); System.out.println("text = " + text); resp.setText(text); return resp; }
@Test public void clientPingsServerHttp2() throws Exception { peer.setVariantAndClient(HTTP_2, false); // write the mocking script peer.acceptFrame(); // PING peer.sendFrame().ping(true, 1, 5); peer.play(); // play it back FramedConnection connection = connection(peer, HTTP_2); Ping ping = connection.ping(); assertTrue(ping.roundTripTime() > 0); assertTrue(ping.roundTripTime() < TimeUnit.SECONDS.toNanos(1)); // verify the peer received what was expected MockSpdyPeer.InFrame pingFrame = peer.takeFrame(); assertEquals(0, pingFrame.streamId); assertEquals(1, pingFrame.payload1); assertEquals(0x4f4b6f6b, pingFrame.payload2); // connection.ping() sets this. assertFalse(pingFrame.ack); }
public void setPing(Ping ping) { if (ping != null) { if (!ping.equals(this.ping)) { this.ping = ping; setupPingTask(); } if (this.ping.getLoadBalancer() != this) { this.ping.setLoadBalancer(this); } } else { this.ping = null; pingTimer.cancel(); } }
public static void main(String[] args) { XmlManager xmlManager = new XmlManager(); xmlManager.modifyNode("", "Eastsoft_54328"); String cmd = "netsh wlan add profile filename=" + xmlManager.getNowPath() + "\"\\Eastsoft_wifi.xml\""; Ping.executeCmd(cmd); /*String original = xmlManager.getNowPath()+ "\\wifiConfTemplate.xml"; String target = xmlManager.getNowPath()+"\\Eastsoft_wifi.xml"; try { ToolUtil.copyFile(original, target); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ System.out.println(xmlManager.stringToHexString("Eastsoft_54328").toUpperCase()); }
private static void __FOO__(Ping stub) throws PingException, RemoteException { stub.ping(); }
private void bouncePing() throws Exception { Ping ping = (Ping) outbound(writeTarget); inbound(writeTarget, new Pong(ping.getNonce())); }
public void receiveAndPing(Ping p) throws RemoteException { p.ping(); }
public static void main(String[] args) { Ping obj = null; Registry registry = null; try { /* * create registry */ TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); System.err.println("creating Registry..."); registry = TestLibrary.createRegistryOnUnusedPort(); int port = TestLibrary.getRegistryPort(registry); /* * create object with custom ref and bind in registry */ System.err.println("creating UseCustomRef..."); UseCustomRef cr = new UseCustomRef(); RemoteRef ref = cr.getRef(); if (!(ref instanceof CustomServerRef)) { TestLibrary.bomb("test failed: reference not " + "instanceof CustomServerRef"); } String name = "//:" + port + "/UseCustomRef"; // String name = "UseCustomRef"; System.err.println("binding object in registry..."); Naming.rebind(name, cr); /* * look up object and invoke its ping method */ System.err.println("ping object..."); obj = (Ping) Naming.lookup(name); obj.ping(); /* * pass object with custom ref in remote call */ System.err.println("pass object in remote call..."); obj.receiveAndPing(cr); /* * write remote object with custom ref to output stream */ System.err.println("writing remote object to stream..."); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(cr); out.flush(); out.close(); /* * read back remote object from output stream */ System.err.println("reading remote object from stream..."); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray())); cr = (UseCustomRef) in.readObject(); /* * re-export object and ping */ System.err.println("re-export object read..."); cr.exportObject(); System.err.println("look up object again..."); Naming.rebind(name, cr); System.err.println("ping object read..."); obj = (Ping) Naming.lookup(name); obj.ping(); System.err.println("TEST PASSED"); Naming.unbind(name); cr = null; } catch (Exception e) { TestLibrary.bomb("test failed with exception: ", e); } finally { TestLibrary.unexport(obj); TestLibrary.unexport(registry); registry = null; obj = null; } }