Example usage for javax.websocket Session getBasicRemote

List of usage examples for javax.websocket Session getBasicRemote

Introduction

In this page you can find the example usage for javax.websocket Session getBasicRemote.

Prototype

RemoteEndpoint.Basic getBasicRemote();

Source Link

Usage

From source file:feedme.controller.SocketServer.java

private void sendMessageToResturent(JSONObject msg) {
    System.out.println("Message  " + msg);
    try {// www . j  a  va  2s.  c o  m
        JSONObject order = msg.getJSONObject("order");
        Session ses = nameSessionPair.get(String.valueOf(order.getInt("rest_id")));
        if (ses != null)
            ses.getBasicRemote().sendText(order.toString());
    } catch (JSONException ex) {
        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:furkan.app.tictactoewebsocket.TicTacToeServer.java

private void sendJsonMessage(Session session, Game game, Message message) {
    try {/*from  w ww  . j  a v a2s .c  o m*/
        session.getBasicRemote().sendText(TicTacToeServer.mapper.writeValueAsString(message));
    } catch (IOException ioe) {
        this.handleException(ioe, game);
    }
}

From source file:de.tuttas.websockets.ChatServer.java

@OnOpen
public void onOpen(Session session) {
    Log.d(session.getId() + " has opened a connection");
    sessions.add(session);//from   w ww . j  a  v a2  s. co m

    mySession = session;
    ChatLine l = new ChatLine("System", "");
    users.put(session.getId(), "NN");
    try {
        session.getBasicRemote().sendText(l.toJson());
    } catch (IOException ex) {
        Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    Log.d("Total Number of Clients =" + sessions.size());
}

From source file:com.github.mrstampy.gameboot.otp.websocket.WebSocketEndpoint.java

/**
 * Send message.//from  w  ww  . ja  va 2  s .  c o m
 *
 * @param msg
 *          the msg
 * @param session
 *          the session
 * @throws Exception
 *           the exception
 */
public void sendMessage(byte[] msg, Session session) throws Exception {
    byte[] converted = isEncrypting(session) ? pad.convert(otpKey, msg) : msg;

    session.getBasicRemote().sendBinary(ByteBuffer.wrap(converted));
}

From source file:org.sample.client.MyClient.java

@Override
public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override//  w w  w  . ja v  a2  s  .  c om
        public void onMessage(String text) {
            System.out.println("Received response in client from endpoint: " + text);
        }
    });
    System.out.println("Connected to endpoint: " + session.getBasicRemote());
    try {
        String name = "Duke";
        System.out.println("Sending message from client -> endpoint: " + name);
        session.getBasicRemote().sendText(name);
    } catch (IOException ex) {
        Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.bluemix.droneselfie.UploadPictureServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String id = request.getParameter("id");
    if (id == null)
        return;/*from   w w  w  .ja  v a2 s  .  c o m*/
    if (id.equals(""))
        return;

    InputStream inputStream = null;
    Part filePart = request.getPart("my_file");
    if (filePart != null) {
        inputStream = filePart.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.apache.commons.io.IOUtils.copy(inputStream, baos);
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream bistream = new ByteArrayInputStream(bytes);
        String contentType = "image/png";

        java.util.Date date = new java.util.Date();
        String uniqueId = String.valueOf(date.getTime());
        AttachmentDoc document = new AttachmentDoc(id, AttachmentDoc.TYPE_FULL_PICTURE, date);
        DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
        document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, id);
        AttachmentInputStream ais = new AttachmentInputStream(id, bistream, contentType);
        DatabaseUtilities.getSingleton().getDB().createAttachment(id, document.getRevision(), ais);

        javax.websocket.Session ssession;
        ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
        if (ssession != null) {
            for (Session session : ssession.getOpenSessions()) {
                try {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText("fpic?id=" + id);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

        String alchemyUrl = "";
        String apiKey = ConfigUtilities.getSingleton().getAlchemyAPIKey();
        String bluemixAppName = ConfigUtilities.getSingleton().getBluemixAppName();

        /*
        if (bluemixAppName == null) {
           String host = request.getServerName();
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + host +"/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }
        else {
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + bluemixAppName +".mybluemix.net/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }*/

        alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://ar-drone-selfie.mybluemix.net/pic?id="
                + id + "&apikey=1657f33d25d39ff6d226c5547db6190ea8d5af76&outputMode=json";
        System.out.println("alchemyURL: " + alchemyUrl);
        org.apache.http.client.fluent.Request req = Request.Post(alchemyUrl);
        org.apache.http.client.fluent.Response res = req.execute();

        String output = res.returnContent().asString();
        Gson gson = new Gson();

        AlchemyResponse alchemyResponse = gson.fromJson(output, AlchemyResponse.class);

        if (alchemyResponse != null) {
            List<ImageFace> faces = alchemyResponse.getImageFaces();
            if (faces != null) {
                for (int i = 0; i < faces.size(); i++) {
                    ImageFace face = faces.get(i);
                    String sH = face.getHeight();
                    String sPX = face.getPositionX();
                    String sPY = face.getPositionY();
                    String sW = face.getWidth();
                    int height = Integer.parseInt(sH);
                    int positionX = Integer.parseInt(sPX);
                    int positionY = Integer.parseInt(sPY);
                    int width = Integer.parseInt(sW);

                    int fullPictureWidth = 640;
                    int fullPictureHeight = 360;
                    positionX = positionX - width / 2;
                    positionY = positionY - height / 2;
                    height = height * 2;
                    width = width * 2;
                    if (positionX < 0)
                        positionX = 0;
                    if (positionY < 0)
                        positionY = 0;
                    if (positionX + width > fullPictureWidth)
                        width = width - (fullPictureWidth - positionX);
                    if (positionY + height > fullPictureHeight)
                        height = height - (fullPictureHeight - positionY);

                    bistream = new ByteArrayInputStream(bytes);
                    javaxt.io.Image image = new javaxt.io.Image(bistream);
                    image.crop(positionX, positionY, width, height);
                    byte[] croppedImage = image.getByteArray();

                    ByteArrayInputStream bis = new ByteArrayInputStream(croppedImage);

                    date = new java.util.Date();
                    uniqueId = String.valueOf(date.getTime());
                    document = new AttachmentDoc(uniqueId, AttachmentDoc.TYPE_PORTRAIT, date);
                    DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
                    document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, uniqueId);

                    ais = new AttachmentInputStream(uniqueId, bis, contentType);
                    DatabaseUtilities.getSingleton().getDB().createAttachment(uniqueId, document.getRevision(),
                            ais);

                    ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
                    if (ssession != null) {
                        for (Session session : ssession.getOpenSessions()) {
                            try {
                                if (session.isOpen()) {
                                    /*
                                     * In addition to portrait url why don't we send a few meta back to client
                                     */
                                    ImageTag tag = face.getImageTag();
                                    tag.setUrl("pic?id=" + uniqueId);
                                    session.getBasicRemote().sendText(tag.toString());
                                }
                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.atteo.moonshine.websocket.jsonmessages.HandlerDispatcher.java

public <T> SenderProvider<T> addSender(Class<T> klass) {
    checkState(klass.isInterface(), "Provided Class object must represent an interface");

    for (Method method : klass.getMethods()) {
        registerSenderMethod(method);//from   ww  w  . j  a  va 2s  .c  o m
    }
    @SuppressWarnings("unchecked")
    final Class<T> proxyClass = (Class<T>) Proxy.getProxyClass(Thread.currentThread().getContextClassLoader(),
            klass);

    class SenderInvocationHandler implements InvocationHandler {
        private final Session session;

        public SenderInvocationHandler(Session session) {
            this.session = session;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String request = encoderObjectMapper.writeValueAsString(args[0]);
            session.getBasicRemote().sendText(request);
            return null;
        }
    }

    return new SenderProvider<T>() {
        @Override
        public T get(Session session) {
            try {
                return proxyClass.getConstructor(new Class<?>[] { InvocationHandler.class })
                        .newInstance(new SenderInvocationHandler(session));
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException ex) {
                throw new RuntimeException(ex);
            }
        }
    };
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testWSClient() throws InterruptedException, DeploymentException, IOException {
    System.out.println("WS TEST: Testing WebSocket endpoint...");

    String endpoint = String.format("ws://%s:%d/gcs/ws", InetAddress.getLocalHost().getHostAddress(),
            config.getWSPort());//from   w ww .  j a  v  a2 s .c o m

    System.out.printf("WS TEST: Connecting to %s", endpoint);
    System.out.println();

    ClientManager client = ClientManager.createClient();

    Session session = client.connectToServer(WSClient.class, URI.create(endpoint));

    System.out.printf("WS TEST: Connected to %s", endpoint);
    System.out.println();

    MAVLinkPacket packet = getSamplePacket();
    session.getBasicRemote().sendBinary(ByteBuffer.wrap(packet.encodePacket()));

    Thread.sleep(10000);

    System.out.println("WS TEST: Complete.");

    session.close();
}

From source file:cito.server.AbstractEndpoint.java

@OnError
@Override/*from   w w w . ja  v a  2s  .  co  m*/
public void onError(Session session, Throwable cause) {
    final String errorId = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
    this.log.warn("WebSocket error. [id={},principle={},errorId={}]", session.getId(),
            session.getUserPrincipal(), errorId, cause);
    try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
        this.errorEvent.select(cito.annotation.OnError.Literal.onError()).fire(cause);
        final Frame errorFrame = Frame.error()
                .body(MediaType.TEXT_PLAIN_TYPE, format("%s [errorId=%s]", cause.getMessage(), errorId))
                .build();
        session.getBasicRemote().sendObject(errorFrame);
        session.close(
                new CloseReason(CloseCodes.PROTOCOL_ERROR, format("See server log. [errorId=%s]", errorId)));
    } catch (IOException | EncodeException e) {
        this.log.error("Unable to send error frame! [id={},principle={}]", session.getId(),
                session.getUserPrincipal(), e);
    }
}

From source file:feedme.controller.SocketServer.java

/**
 * Called when a socket connection opened
 * *///  w ww.j  av a2 s.c  om
@OnOpen
public void onOpen(Session session) {

    System.out.println(session.getId() + " has opened a connection");

    Map<String, String> queryParams = getQueryMap(session.getQueryString());

    String name = "";

    if (queryParams.containsKey("name")) {

        // Getting client name via query param
        name = queryParams.get("name");
        try {
            name = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // Mapping client name and session id

    }
    if (!name.equals("customer")) {
        nameSessionPair.put(name, session);
        sessions.add(session);
    }

    // Adding session to session list

    try {
        // Sending session id to the client that just connected
        session.getBasicRemote().sendText(jsonUtils.getClientDetailsJson(name, "Your session details"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Sessions size " + sessions.size());
    for (Iterator<Map.Entry<String, Session>> it = nameSessionPair.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, Session> e = it.next();
        System.out.println("rest id " + e.getKey() + " rest_session_id " + e.getValue().getId().toString());
    }

}