/** * Sends a response packet from the server to the client. * * <p>Synchronized so that only one thread can send a client a message at a time. * * @param packet the response packet */ public synchronized void sendResponse(Packet packet) { try { session.getRemote().sendString(packet.getJson().toString()); } catch (IOException ioe) { System.out.println( "Sending response failed, session id = " + session.getRemoteAddress().toString()); } }
@OnWebSocketMessage public void onText(Session session, String message) { if (session.isOpen()) { System.out.printf("Echoing back message [%s]%n", message); // echo the message back session.getRemote().sendString(message, null); } }
/* Socket message envoyé */ public void sendMessage(String str) { try { session.getRemote().sendString(str); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onWebSocketConnect(Session sess) { connected = true; final String spath = getFirstValue(sess, "path"); final String sset = getFirstValue(sess, "dataset"); final boolean writing = Boolean.parseBoolean(getFirstValue(sess, "writingExpected")); final Path path = Paths.get(spath); try { WatchService myWatcher = path.getFileSystem().newWatchService(); QueueReader fileWatcher = new QueueReader(myWatcher, sess, spath, sset, writing); // We may only monitor a directory if (Files.isDirectory(path)) { path.register(myWatcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); } else { path.getParent().register(myWatcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); } Thread th = new Thread(fileWatcher, path.getFileName() + " Watcher"); th.setDaemon(true); th.setPriority(Thread.MAX_PRIORITY - 2); th.start(); if (diagInfo != null) diagInfo.record("Start Thread", th.getName()); } catch (Exception ne) { logger.error("Cannot watch " + path, ne); try { sess.getRemote().sendString(ne.getMessage()); } catch (IOException e) { logger.warn("Cannot write to remote " + sess, e); } } }
public void send(final WebSocketMessage message, final boolean clearSessionId) { // return session status to client message.setSessionValid(isAuthenticated()); // whether to clear the token (all command except LOGIN (for now) should absolutely do this!) if (clearSessionId) { message.setSessionId(null); } // set callback message.setCallback(callback); if (isAuthenticated() || "STATUS".equals(message.getCommand())) { String msg = gson.toJson(message, WebSocketMessage.class); logger.log( Level.FINE, "############################################################ SENDING \n{0}", msg); try { session.getRemote().sendString(msg); } catch (Throwable t) { logger.log(Level.WARNING, "Unable to send websocket message to remote client"); } } else { logger.log(Level.WARNING, "NOT sending message to unauthenticated client."); } }
@Override public void onWebSocketText(String message) { LOG.debug("onWebSocketText({})", message); calls.incrementAndGet(); if (message.equalsIgnoreCase("openSessions")) { Collection<WebSocketSession> sessions = container.getOpenSessions(); StringBuilder ret = new StringBuilder(); ret.append("openSessions.size=").append(sessions.size()).append('\n'); int idx = 0; for (WebSocketSession sess : sessions) { ret.append('[').append(idx++).append("] ").append(sess.toString()).append('\n'); } session.getRemote().sendStringByFuture(ret.toString()); session.close(StatusCode.NORMAL, "ContainerSocket"); } else if (message.equalsIgnoreCase("calls")) { session.getRemote().sendStringByFuture(String.format("calls=%,d", calls.get())); } }
@Override public void close() { logger.trace( "WebSocket.close() for AtmosphereResource {}", resource() != null ? resource().uuid() : "null"); try { webSocketConnection.close(); } catch (IOException e) { logger.trace("Close error", e); } }
@Override public void onWebSocketConnect(final Session session) { logger.log(Level.INFO, "New connection with protocol {0}", session.getProtocolVersion()); this.session = session; syncController.registerClient(this); pagePath = request.getQueryString(); }
@Test public void testBatchModeAuto() throws Exception { URI uri = URI.create("ws://localhost:" + connector.getLocalPort()); final CountDownLatch latch = new CountDownLatch(1); WebSocketAdapter adapter = new WebSocketAdapter() { @Override public void onWebSocketText(String message) { latch.countDown(); } }; try (Session session = client.connect(adapter, uri).get()) { RemoteEndpoint remote = session.getRemote(); Future<Void> future = remote.sendStringByFuture("batch_mode_on"); // The write is aggregated and therefore completes immediately. future.get(1, TimeUnit.MICROSECONDS); // Wait for the echo. Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } }
@Override public void initializeNativeSession(Session session) { super.initializeNativeSession(session); this.id = ObjectUtils.getIdentityHexString(getNativeSession()); this.uri = session.getUpgradeRequest().getRequestURI(); this.headers = new HttpHeaders(); this.headers.putAll(getNativeSession().getUpgradeRequest().getHeaders()); this.headers = HttpHeaders.readOnlyHttpHeaders(headers); this.acceptedProtocol = session.getUpgradeResponse().getAcceptedSubProtocol(); List<ExtensionConfig> source = getNativeSession().getUpgradeResponse().getExtensions(); this.extensions = new ArrayList<WebSocketExtension>(source.size()); for (ExtensionConfig ec : source) { this.extensions.add(new WebSocketExtension(ec.getName(), ec.getParameters())); } if (this.user == null) { this.user = session.getUpgradeRequest().getUserPrincipal(); } }
@Override @OnWebSocketConnect public void onConnect(Session session) { super.onConnect(session); this.session.setIdleTimeout(TimeUnit.MINUTES.toMillis(1)); Connector con = null; try { ConnectorFactory cf = ConnectorFactory.getDefault(); con = cf.createConnector(); } catch (AgentProxyException e) { System.out.println(e); } IdentityRepository irepo = null; if (con != null) { RemoteIdentityRepository rrepo = new RemoteIdentityRepository(con); if (rrepo.getIdentities() != null && rrepo.getIdentities().size() > 0) { irepo = rrepo; jsch.setIdentityRepository(irepo); } } if (irepo == null) { String home = System.getProperty("user.home"); String sshDir = home + File.separator + ".ssh" + File.separator; String[] defaultKeys = new String[] { sshDir + "id_ecdsa", sshDir + "id_id_ed25519", sshDir + "id_rsa", sshDir + "id_dsa", sshDir + "identity" }; for (String nextKey : defaultKeys) { try { jsch.addIdentity(nextKey); log.fine("Key '" + nextKey + "' added"); } catch (JSchException e) { log.log(Level.FINE, "Key '" + nextKey + "' not valid", e); } } } Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap(); String host = getStringParameter(parameterMap, "host", null); String connectHost = hostLookupService.getResolvableHostname(host); String user = getStringParameter(parameterMap, "user", null); if ("@admin".equals(user)) { user = hostLookupService.getAdminUserFor(host); } Resize resize = new Resize(); resize.cols = getIntParameter(parameterMap, "cols", 80); resize.rows = getIntParameter(parameterMap, "rows", 24); try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); jschSession = jsch.getSession(user, connectHost, hostLookupService.getSshPort(host)); jschSession.setConfig(config); jschSession.connect(60000); shell = (ChannelShell) jschSession.openChannel("shell"); shell.setAgentForwarding(true); shell.setPtyType("vt102"); shell.connect(); shell.setPtySize(resize.cols, resize.rows, resize.getPixelWidth(), resize.getPixelHeight()); } catch (JSchException e) { close(1, "Failed to create ssh session", e); } Runnable run; try { run = new RawSentOutputTask( session, new BufferedInputStream(shell.getInputStream(), BUFFER_LEN)); Thread thread = new Thread(run); thread.start(); } catch (IOException e) { close(2, "IOException while getting data from ssh", e); } try { inputToShell = new PrintStream(shell.getOutputStream(), true, "UTF-8"); } catch (IOException e) { close(3, "IOException while creating write stream to ssh", e); } }
/** * Disconnects this client's session. @TODO send notification first before suddenly closing * connection */ public void disconnectSession() { session.close(); }
/** * Gets the session id that this client is connected to the server with. (ie. the remote address, * to string'd) * * @return the session object */ public String getSessionId() { return session.getRemoteAddress().toString(); }
public synchronized void keepAlive() throws Exception { checkConnected(); connection.getRemote().sendString("\n"); }
public synchronized void sendFrame(StompFrame frame) throws Exception { checkConnected(); connection.getRemote().sendString(frame.format()); }
public synchronized void sendRawFrame(String rawFrame) throws Exception { checkConnected(); connection.getRemote().sendString(rawFrame); }
public void close() { if (connection != null) { connection.close(); } }
@Override public boolean isConnected() { return connection != null ? connection.isOpen() : false; }
/** * In order to implement a file watcher, we loop forever ensuring requesting to take the next * item from the file watchers queue. */ @Override public void run() { final Path path = Paths.get(spath); try { // We wait until the file we are told to monitor exists. while (!Files.exists(path)) { Thread.sleep(200); } // get the first event before looping WatchKey key = null; while (session.isOpen() && connected && (key = watcher.take()) != null) { try { if (!Files.exists(path)) continue; for (WatchEvent<?> event : key.pollEvents()) { if (!Files.exists(path)) continue; Path epath = (Path) event.context(); if (!Files.isDirectory(path) && !path.endsWith(epath)) continue; try { // Data has changed, read its shape and publish the event using a web socket. final IDataHolder holder = ServiceHolder.getLoaderService().getData(spath, new IMonitor.Stub()); if (holder == null) continue; // We do not stop if the loader got nothing. final ILazyDataset lz = sdataset != null && !"".equals(sdataset) ? holder.getLazyDataset(sdataset) : holder.getLazyDataset(0); if (lz == null) continue; // We do not stop if the loader got nothing. if (lz instanceof IDynamicDataset) { ((IDynamicDataset) lz).refreshShape(); } if (writing) { ServiceHolder.getLoaderService().clearSoftReferenceCache(spath); } final DataEvent evt = new DataEvent(lz.getName(), lz.getShape()); evt.setFilePath(spath); // We manually JSON the object because we // do not want a dependency and object simple String json = evt.encode(); session.getRemote().sendString(json); if (diagInfo != null) diagInfo.record("JSON Send", json); } catch (HDF5FunctionArgumentException h5error) { // This happens sometimes when the file is not ready to read. logger.trace("Path might not be ready to read " + path); continue; } catch (Exception ne) { logger.error("Exception getting data from " + path); continue; } break; } } finally { key.reset(); } } } catch (Exception e) { logger.error("Exception monitoring " + path, e); if (session.isOpen()) session.close(403, e.getMessage()); } finally { if (diagInfo != null) diagInfo.record("Close Thread", Thread.currentThread().getName()); try { watcher.close(); } catch (IOException e) { logger.error("Error closing watcher", e); } } }
@Override public boolean isOpen() { return webSocketConnection.isOpen(); }
private String getFirstValue(Session sess, String name) { final List<String> vals = sess.getUpgradeRequest().getParameterMap().get(name); return vals != null ? vals.get(0) : null; }
@Override public void onWebSocketConnect(Session sess) { LOG.debug("onWebSocketConnect({})", sess); calls.incrementAndGet(); sess.close(StatusCode.NORMAL, "FastCloseServer"); }