Example usage for javax.websocket Session isOpen

List of usage examples for javax.websocket Session isOpen

Introduction

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

Prototype

boolean isOpen();

Source Link

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  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:com.github.mrstampy.gameboot.otp.websocket.OtpWebSocketTest.java

private void sendMessage(AbstractGameBootMessage message, Session channel) throws Exception {
    if (channel == null || !channel.isOpen())
        return;//from   w  ww  .  j av a 2s. co  m

    CountDownLatch cdl = new CountDownLatch(1);
    endpoint.setResponseLatch(cdl);

    boolean b = endpoint.hasKey();

    log.info("Sending {} to session {}: {}", (b ? "encrypted" : "unencrypted"), channel.getId(),
            converter.toJson(message));

    endpoint.sendMessage(converter.toJsonArray(message), channel);

    cdl.await(1, TimeUnit.SECONDS);
}

From source file:hydrograph.ui.graph.execution.tracking.utils.TrackingDisplayUtils.java

/**
 * //from   w  w w  . ja  v a  2 s  .  c om
 * Close websocket client connection.
 * @param session
 */
public void closeWebSocketConnection(Session session) {
    try {
        Thread.sleep(DELAY);
    } catch (InterruptedException e1) {
    }
    if (session != null && session.isOpen()) {
        try {
            CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE, "Closed");
            session.close(closeReason);
            logger.info("Session closed");
        } catch (IOException e) {
            logger.error("Fail to close connection ", e);
        }

    }

}

From source file:hydrograph.ui.graph.utility.JobScpAndProcessUtility.java

/**
 * Close Websocket connection Connection
 * @param session//from ww w. j  a  va 2 s  .  c om
 */
private void closeWebSocketConnection(final Session session) {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
    }

    if (session != null && session.isOpen()) {
        try {
            CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE, "Session Closed");
            session.close(closeReason);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

public void sendMsg(Session conn, String msg) throws IOException {
    if (conn == null || !conn.isOpen()) {
        LOG.log(Level.SEVERE, "Can't handle message. The connection has been closed.");
        return;//  www  .  ja  va2  s.  co  m
    }
    conn.getBasicRemote().sendText(msg);
}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

public void closeConnection(Session session, String hdfsUsername,
        NotebookServerImplFactory notebookServerImplFactory) {
    try {/*from w w w.  jav a2  s.co m*/
        if (session.isOpen()) {
            session.getBasicRemote().sendText("Restarting zeppelin.");
            session.close(new CloseReason(CloseReason.CloseCodes.SERVICE_RESTART, "Restarting zeppelin."));
        }
        removeConnectionFromAllNote(session);
        removeConnectedSockets(session, notebookServerImplFactory);
        removeUserConnection(hdfsUsername, session);
        removeUserConnection(project.getProjectGenericUser(), session);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 *    /* w w  w.j a va  2s .  c  o m*/
 * @param latch
 * @param session
 * @param jobId
 * @param timer
 * @param execution
 * @param socket
 * @throws IOException
 */
private void sendExecutionTrackingStatus(final CountDownLatch latch, Session session, final String jobId,
        final Timer timer, final HydrographService execution, final HydrographEngineCommunicatorSocket socket)
        throws IOException {
    try {
        TimerTask task = new TimerTask() {
            ExecutionStatus previousExecutionStatus = null;

            @Override
            public void run() {
                List<ComponentInfo> componentInfos = execution.getStatus();
                if (!componentInfos.isEmpty()) {
                    List<ComponentStatus> componentStatusList = new ArrayList<ComponentStatus>();
                    for (ComponentInfo componentInfo : componentInfos) {
                        ComponentStatus componentStatus = new ComponentStatus(componentInfo.getComponentId(),
                                componentInfo.getComponentName(), componentInfo.getCurrentStatus(),
                                componentInfo.getBatch(), componentInfo.getProcessedRecords());
                        componentStatusList.add(componentStatus);
                    }
                    ExecutionStatus executionStatus = new ExecutionStatus(componentStatusList);
                    executionStatus.setJobId(jobId);
                    executionStatus.setClientId(Constants.ENGINE_CLIENT + jobId);
                    executionStatus.setType(Constants.POST);
                    Gson gson = new Gson();
                    try {
                        if (previousExecutionStatus == null
                                || !executionStatus.equals(previousExecutionStatus)) {
                            socket.sendMessage(gson.toJson(executionStatus));
                            previousExecutionStatus = executionStatus;
                        }
                    } catch (IOException e) {
                        logger.error("Fail to send status for job - " + jobId, e);
                        timer.cancel();
                    }

                    if (StringUtils.isNotBlank(jobId)) {
                        //moved this after sendMessage in order to log even if the service is not running 
                        ExecutionTrackingFileLogger.INSTANCE.log(jobId, executionStatus);
                    }

                }
                if (!execution.getJobRunningStatus()) {
                    timer.cancel();
                    latch.countDown();
                }
            }
        };

        timer.schedule(task, 0l, ExecutionTrackingUtils.INSTANCE.getStatusFrequency());
        latch.await();

    } catch (Throwable t) {
        logger.error("Failure in job - " + jobId, t);
        timer.cancel();
        throw new RuntimeException(t);
    } finally {

        if (session != null && session.isOpen()) {
            logger.debug("Closing Websocket engine client");
            CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Session Closed");
            session.close(closeReason);
        }
    }
}

From source file:org.axonframework.commandhandling.distributed.websockets.WebsocketCommandBusConnectorClient.java

public WebsocketCommandBusConnectorClient(ClientSessionFactory clientSessionFactory, int sessionCount) {
    //Create the pool. Server side connections are bound to the commands in process. Therefore scaling down the
    //amount of connections results in losing callbacks of pending commands. We will therefore never scale down or
    //invalidate connections.
    GenericObjectPool.Config config = new GenericObjectPool.Config();
    config.maxActive = sessionCount;//  ww w .  j  a v  a 2 s .c  o  m
    config.maxIdle = sessionCount;
    config.maxWait = -1;
    config.minEvictableIdleTimeMillis = -1;
    config.minIdle = 0;
    config.numTestsPerEvictionRun = 0;
    config.softMinEvictableIdleTimeMillis = -1;
    config.testOnBorrow = true;
    config.testOnReturn = false;
    config.testWhileIdle = false;
    config.timeBetweenEvictionRunsMillis = -1;
    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;

    sessions = new GenericObjectPoolFactory<>(new PoolableObjectFactory<Session>() {
        @Override
        public Session makeObject() throws Exception {
            return clientSessionFactory.createSession(WebsocketCommandBusConnectorClient.this);
        }

        @Override
        public void destroyObject(Session obj) throws Exception {
            if (obj.isOpen())
                obj.close();
        }

        @Override
        public boolean validateObject(Session obj) {
            return obj.isOpen();
        }

        @Override
        public void activateObject(Session obj) throws Exception {
            //
        }

        @Override
        public void passivateObject(Session obj) throws Exception {
            //
        }
    }, config).createPool();
}

From source file:org.b3log.symphony.processor.channel.ArticleChannel.java

/**
 * Notifies the specified article heat message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {//  w  w w . j av  a 2  s.c  o  m
 *     "articleId": "",
 *     "operation": "" // "+"/"-"
 * }
 * </pre>
 */
public static void notifyHeat(final JSONObject message) {
    message.put(Common.TYPE, Article.ARTICLE_T_HEAT);

    final String msgStr = message.toString();

    for (final Session session : SESSIONS) {
        final String viewingArticleId = (String) Channels.getHttpParameter(session, Article.ARTICLE_T_ID);
        if (Strings.isEmptyOrNull(viewingArticleId)
                || !viewingArticleId.equals(message.optString(Article.ARTICLE_T_ID))) {
            continue;
        }

        if (session.isOpen()) {
            session.getAsyncRemote().sendText(msgStr);
        }
    }
}

From source file:org.b3log.symphony.processor.channel.ArticleChannel.java

/**
 * Notifies the specified comment message to browsers.
 *
 * @param message the specified message, for example      <pre>
 * {/*w  ww.ja  v a  2 s  .co m*/
 *     "articleId": "",
 *     "commentId": "",
 *     "commentAuthorName": "",
 *     "commentAuthorThumbnailURL": "",
 *     "commentCreateTime": "", // yyyy-MM-dd HH:mm
 *     "commentContent": "",
 *     commentThankLabel": "",
 *     "thankLabel": "",
 *     "thankedLabel": "",
 *     "timeAgo": ""
 * }
 * </pre>
 */
public static void notifyComment(final JSONObject message) {
    message.put(Common.TYPE, Comment.COMMENT);

    final String msgStr = message.toString();

    final LatkeBeanManager beanManager = LatkeBeanManagerImpl.getInstance();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    final ArticleRepository articleRepository = beanManager.getReference(ArticleRepository.class);

    for (final Session session : SESSIONS) {
        final String viewingArticleId = (String) Channels.getHttpParameter(session, Article.ARTICLE_T_ID);
        if (Strings.isEmptyOrNull(viewingArticleId)
                || !viewingArticleId.equals(message.optString(Article.ARTICLE_T_ID))) {
            continue;
        }

        final int articleType = Integer.valueOf(Channels.getHttpParameter(session, Article.ARTICLE_TYPE));

        try {
            if (Article.ARTICLE_TYPE_C_DISCUSSION == articleType) {
                final JSONObject user = (JSONObject) Channels.getHttpSessionAttribute(session, User.USER);
                if (null == user) {
                    continue;
                }

                final String userName = user.optString(User.USER_NAME);
                final String userId = user.optString(Keys.OBJECT_ID);
                final String userRole = user.optString(User.USER_ROLE);

                final JSONObject article = articleRepository.get(viewingArticleId);
                final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
                if (!userId.equals(articleAuthorId)) {
                    final String articleContent = article.optString(Article.ARTICLE_CONTENT);
                    final Set<String> userNames = userQueryService.getUserNames(articleContent);

                    boolean invited = false;
                    for (final String inviteUserName : userNames) {
                        if (inviteUserName.equals(userName)) {
                            invited = true;

                            break;
                        }
                    }

                    if (Role.ADMIN_ROLE.equals(userRole)) {
                        invited = true;
                    }

                    if (!invited) {
                        continue; // next session
                    }
                }
            }

            if (session.isOpen()) {
                session.getAsyncRemote().sendText(msgStr);
            }
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Notify comment error", e);
        }
    }
}