Example usage for javax.websocket Session getOpenSessions

List of usage examples for javax.websocket Session getOpenSessions

Introduction

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

Prototype

Set<Session> getOpenSessions();

Source Link

Document

Obtain the set of open sessions associated with the same local endpoint as this session.

Usage

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;/*w ww . j a  v a2s.  c om*/
    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.damcode.web.c4webserver.Server.java

@OnOpen
public void onOpen(Session session, @PathParam("id") String gameId) throws IOException {
    printSysOut("new session: " + session.getId() + ", game id: " + gameId + "from ip: ");
    session.getUserProperties().put("gameid", gameId);
    session.getUserProperties().put("lobby", true);

    String connectedPlayers = "";
    int pCount = 0;
    for (Session s : session.getOpenSessions()) {
        if (!s.equals(session)) {
            String name = (String) s.getUserProperties().get("name");
            connectedPlayers += name + ", ";
            pCount++;/*www  .  j av a  2 s  .com*/
        }
    }
    if (pCount > 0) {
        printSysOut("Connected Players: " + connectedPlayers);
        session.getBasicRemote()
                .sendText(Utils.assembleChatMessage("Server", connectedPlayers, "other players"));
    }

    for (GameController gc : waitingGames) {
        sendGameAvailMessage(session, gc.getId().toString(), gc.players.get(0));
    }
}

From source file:org.damcode.web.c4webserver.Server.java

@OnMessage
public void onMessage(MessageBean message, Session session, @PathParam("id") String gameId) {
    printSysOut("Current active games: " + activeGames.size());
    printSysOut("Current waiting games: " + waitingGames.size());
    String players = "";
    int pCount = 0;
    for (Session s : session.getOpenSessions()) {
        if (!s.equals(session)) {
            String name = (String) s.getUserProperties().get("name");
            players += name;/*from w  w  w  . j  a va  2  s  . c  o  m*/
            pCount++;
        }
    }
    printSysOut("Connected Players: " + players + " / " + pCount);

    try {

        processMessage(message, session);

    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.damcode.web.c4webserver.Server.java

private void processMessage(MessageBean m, Session s) throws IOException {
    Player p, o;// w w  w .j  a  v a2s .c o  m
    GameController g;

    switch (m.getCommand()) {

    case MessageBean.MSG_CHAT:
        doChatMessage(m, s);
        break;

    case MessageBean.MSG_PASS_MOVE_TOKEN:
        getGame(s).passMoveToken(s);
        break;

    case MessageBean.MSG_MOVE_ACTION:
        int c = Integer.parseInt(m.getData());
        getGame(s).dropPiece(s, c);
        printSysOut("player move: " + m.getData());
        break;

    case MessageBean.MSG_START_GAME:
        if (isAlreadyPlaying(s)) {
            break;
        }
        GameController game = new GameController();
        game.addPlayer(s);
        s.getUserProperties().put("gameid", game.getId());
        waitingGames.add(game);
        game.gameStatus = GameController.GAME_WAITING;

        s.getBasicRemote().sendText(Utils.assembleChatMessage("Server",
                "ok, started game, waiting for players to join.", "server"));

        game.getPlayer(s).sendDataMessage(MessageBean.MSG_START_GAME, game.getId().toString());
        //sendDataMessage(s, , );
        printSysOut("start game: " + m.getData());
        break;

    case MessageBean.MSG_PLAYER_NAME:
        String name = m.getData();
        s.getUserProperties().put("name", name);
        printSysOut("user with name: " + name);
        for (Session ss : s.getOpenSessions()) {
            if (ss.equals(s))
                continue;
            ss.getBasicRemote()
                    .sendText(Utils.assembleChatMessage("Server", "Player join lobby: " + name, "server"));
        }
        break;

    case MessageBean.MSG_JOIN_GAME:
        if (isAlreadyPlaying(s)) {
            break;
        }

        printSysOut("joingame: " + m.getData());
        g = joinGame(s, m);
        if (g != null) {
            try {
                waitingGames.remove(g);
            } catch (Exception e) {
                printSysOut("JOIN FAILED");
            }
        } else {
            printSysOut("NO GAME MATCH FOUND: " + m.getData());
            Utils.sendDataMessage(MessageBean.MSG_PLAYER_QUIT, "Game has expired!", s);
        }
        break;

    case MessageBean.MSG_JOIN_LOBBY_CHAT:
        s.getUserProperties().put("lobby", Boolean.parseBoolean(m.getData()));
        break;

    case MessageBean.MSG_GAME_AVAILABLE:
        if (isAlreadyPlaying(s)) {
            break;
        }
        synchronized (waitingGames) {
            if (waitingGames.isEmpty()) {
                s.getBasicRemote().sendText(
                        Utils.assembleChatMessage("Server", "No games available, try starting one!", "server"));
            }
            for (GameController gc : waitingGames) {
                sendGameAvailMessage(s, gc.getId().toString(), gc.players.get(0));
            }
        }
        break;

    case MessageBean.MSG_PLAYER_READY:
        g = getGame(s);
        if (g == null || g.gameStatus == GameController.GAME_STARTED)
            break;
        printSysOut("gamestate = " + g.gameStatus);
        p = g.getPlayer(s);
        o = g.getOpponent(s);

        p.ready = true;

        if (g.readyCheck()) {
            p.sendDataMessage(MessageBean.MSG_PLAYER_READY, "rdy");
            o.sendDataMessage(MessageBean.MSG_PLAYER_READY, "rdy");
            g.start();
        }
        break;

    case MessageBean.MSG_PLAYER_QUIT:
        quitGame(s, MessageBean.MSG_PLAYER_QUIT);
        break;

    case MessageBean.MSG_PLAYER_SELECT:
        g = getGame(s);
        if (g == null)
            break;
        p = g.getPlayer(s);
        p.imageId = Integer.parseInt(m.getData());
        o = g.getOpponent(s);
        if (o != null) {
            printSysOut("SENT DISABLE MESSAGE: " + p.imageId + " to: " + o.session.getId());
            o.sendDataMessage(MessageBean.MSG_PLAYER_SELECT, m.getData());
        }
        break;

    default:
        break;

    }

}

From source file:org.damcode.web.c4webserver.Server.java

private synchronized void doChatMessage(MessageBean message, Session session) {
    String name = (String) session.getUserProperties().get("name");
    if (name == null) {
        name = "unknown";
    }/*from  w  w w .ja v  a2s . c om*/

    String data = message.getData().replace("\\", "");
    data = data.replace("\"", "\\\"");

    for (Session s : session.getOpenSessions()) {
        try {
            if (s == session)
                continue;

            if (s.getUserProperties().get("gameid").equals(session.getUserProperties().get("gameid"))) { // only send messages to people in same "game"
                s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data));

            } else if ((Boolean) s.getUserProperties().get("lobby") == true
                    && (Boolean) session.getUserProperties().get("lobby") == true) {
                if (!session.getUserProperties().get("gameid").equals("lobby")) {
                    s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data, "playing"));
                } else {
                    s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data, "lobby"));
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}