Example usage for javax.websocket CloseReason CloseReason

List of usage examples for javax.websocket CloseReason CloseReason

Introduction

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

Prototype

public CloseReason(CloseReason.CloseCode closeCode, String reasonPhrase) 

Source Link

Usage

From source file:com.raspoid.network.pushbullet.Pushbullet.java

/**
 * Constructor for a new Pushbullet instance with a specific access token, a device name
 * corresponding to the name that your robot will take in your Pushbullet list of devices,
 * and the Raspoid router to use with this Pushbullet instance.
 * //from w ww . j a v  a  2  s. c om
 * <p>The access token can easily be retrieved from your Pushbullet account settings.</p>
 * 
 * <p>Note that if a device with the specified name already exists, this device will be
 * retrieved. If no devices with this name exists, a new one will be created.</p>
 * 
 * <p>As for other types of servers, the router is used to deal with requests
 * received on this Pushbullet instance.</p>
 * 
 * @param accessToken the access token used to access Pushbullet services.
 * @param deviceName the name corresponding to your robot's Pushbullet device.
 * @param router the router to use to deal with requests received on the deviceName.
 */
public Pushbullet(String accessToken, String deviceName, Router router) {
    this.accessToken = accessToken;

    gson = new Gson();

    this.deviceIden = initDevice(deviceName);
    this.lastPushReceivedTime = initLastPushReceivedTime();

    // WebSocket
    final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    WebSocketContainer websocketClient = ContainerProvider.getWebSocketContainer();
    try {
        session = websocketClient.connectToServer(new PushbulletClientEndpoint(router), clientEndpointConfig,
                new URI("wss://stream.pushbullet.com/websocket/" + accessToken));
    } catch (DeploymentException | IOException | URISyntaxException e) {
        throw new RaspoidException("Error when connecting to Pushbullet server.", e);
    }

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Websocket closed by client"));
        } catch (IOException e) {
            throw new RaspoidException("Error when closing the websocket session with Pushbullet.", e);
        }
    }));
}

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

@OnOpen
public void open(Session conn, EndpointConfig config, @PathParam("projectID") String projectId)
        throws GenericException {
    try {/*from ww  w .j  a v  a  2s  .  c  o  m*/
        this.session = conn;
        this.sender = (String) config.getUserProperties().get("user");
        this.project = getProject(projectId);
        authenticateUser(conn, this.project, this.sender);
        if (this.userRole == null) {
            LOG.log(Level.INFO, "User not authorized for Zeppelin Access: {0}", this.sender);
            return;
        }
        if (project.getPaymentType().equals(PaymentType.PREPAID)) {
            YarnProjectsQuota projectQuota = yarnProjectsQuotaFacade.findByProjectName(project.getName());
            if (projectQuota == null || projectQuota.getQuotaRemaining() < 0) {
                session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,
                        "This project is out of credits."));
                return;
            }
        }
        this.impl = notebookServerImplFactory.getNotebookServerImps(project.getName(), conn);
        if (impl.getConf() == null) {
            impl.removeConnectedSockets(conn, notebookServerImplFactory);
            LOG.log(Level.INFO, "Could not create Zeppelin config for user: {0}, project: {1}",
                    new Object[] { this.sender, project.getName() });
            return;
        }
        addUserConnection(this.hdfsUsername, conn);
        addUserConnection(project.getProjectGenericUser(), conn);
        this.session.getUserProperties().put("projectID", this.project.getId());
        String httpHeader = (String) config.getUserProperties().get(WatcherSecurityKey.HTTP_HEADER);
        this.session.getUserProperties().put(WatcherSecurityKey.HTTP_HEADER, httpHeader);
        impl.unicast(new Message(OP.CREATED_SOCKET), conn);
    } catch (IOException | RepositoryException | TaskRunnerException ex) {
        throw new GenericException(RESTCodes.GenericErrorCode.UNKNOWN_ERROR, Level.SEVERE, null,
                ex.getMessage(), ex);
    }
}

From source file:com.smartling.cms.gateway.client.CmsGatewayClientTest.java

@Test
public void disconnectsAfterFailedAttemptToReconnectCommandChannel() throws Exception {
    CloseReason reason = new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, null);

    CmsGatewayClient.CommandChannelTransportEndpoint transportEndpoint = getCommandChannelTransportEndpoint();

    reset(commandChannelTransport);//  ww  w  .  jav a 2 s. c  o  m
    when(commandChannelTransport.connectToServer(anyObject(), any(URI.class)))
            .thenThrow(mock(IOException.class)).thenThrow(mock(CmsGatewayClientException.class))
            .thenThrow(mock(RuntimeException.class));

    transportEndpoint.onClose(null, reason);

    verify(commandChannelTransport, times(3)).connectToServer(anyObject(), eq(STUB_COMMAND_CHANNEL_URI));
    verify(handler, times(3)).onError(any(Exception.class));
    verify(handler).onDisconnect();
    verifyNoMoreInteractions(handler);
}

From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java

/**
 * Called when a web socket connection is made.  The format for the web socket URL endpoint is:
 * //  w  ww.  j ava  2s  . c  o  m
 *   /designs/{designId}?uuid={uuid}&user={user}&secret={secret}
 *   
 * The uuid, user, and secret query parameters must be present for a connection to be 
 * successfully made.
 * 
 * @param session
 */
@OnOpen
public void onOpenSession(Session session) {
    String designId = session.getPathParameters().get("designId");
    logger.debug("WebSocket opened: {}", session.getId());
    logger.debug("\tdesignId: {}", designId);

    String queryString = session.getQueryString();
    Map<String, String> queryParams = parseQueryString(queryString);
    String uuid = queryParams.get("uuid");
    String userId = queryParams.get("user");
    String secret = queryParams.get("secret");

    this.metrics.socketConnected(designId, userId);

    logger.debug("\tuuid: {}", uuid);
    logger.debug("\tuser: {}", userId);

    ApiDesignEditingSession editingSession = null;

    try {
        long contentVersion = editingSessionManager.validateSessionUuid(uuid, designId, userId, secret);

        // Join the editing session (or create a new one) for the API Design
        editingSession = this.editingSessionManager.getOrCreateEditingSession(designId);
        Set<Session> otherSessions = editingSession.getSessions();
        if (editingSession.isEmpty()) {
            this.metrics.editingSessionCreated(designId);
        }
        editingSession.join(session, userId);

        // Send "join" messages for each user already in the session
        for (Session otherSession : otherSessions) {
            String otherUser = editingSession.getUser(otherSession);
            editingSession.sendJoinTo(session, otherUser, otherSession.getId());
        }

        // Send any commands that have been created since the user asked to join the editing session.
        List<ApiDesignCommand> commands = this.storage.listContentCommands(userId, designId, contentVersion);
        for (ApiDesignCommand command : commands) {
            String cmdData = command.getCommand();

            StringBuilder builder = new StringBuilder();
            builder.append("{");
            builder.append("\"contentVersion\": ");
            builder.append(command.getContentVersion());
            builder.append(", ");
            builder.append("\"type\": \"command\", ");
            builder.append("\"command\": ");
            builder.append(cmdData);
            builder.append("}");

            logger.debug("Sending command to client (onOpenSession): {}", builder.toString());

            session.getBasicRemote().sendText(builder.toString());
        }

        editingSession.sendJoinToOthers(session, userId);
    } catch (ServerError | StorageException | IOException e) {
        if (editingSession != null) {
            editingSession.leave(session);
        }
        logger.error("Error validating editing session UUID for API Design ID: " + designId, e);
        try {
            session.close(new CloseReason(CloseCodes.CANNOT_ACCEPT,
                    "Error opening editing session: " + e.getMessage()));
        } catch (IOException e1) {
            logger.error(
                    "Error closing web socket session (attempted to close due to error validating editing session UUID).",
                    e1);
        }
    }
}

From source file:com.smartling.cms.gateway.client.CmsGatewayClientTest.java

@Test
public void reconnectsAfterFailedAttemptOnIOException() throws Exception {
    CloseReason reason = new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, null);

    CmsGatewayClient.CommandChannelTransportEndpoint transportEndpoint = getCommandChannelTransportEndpoint();

    reset(commandChannelTransport);//from w w w  .  j  a v  a2 s. c  o  m
    when(commandChannelTransport.connectToServer(anyObject(), any(URI.class)))
            .thenThrow(mock(IOException.class)).thenThrow(mock(IOException.class)).thenReturn(commandChannel);

    transportEndpoint.onClose(null, reason);

    verify(commandChannelTransport, times(3)).connectToServer(anyObject(), eq(STUB_COMMAND_CHANNEL_URI));
    verify(handler, never()).onDisconnect();
}

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

@OnMessage
public void onMessage(String msg, Session conn) {
    Notebook notebook = impl.notebook();
    try {//  w w w. ja  va  2s  . c  o m
        Message messagereceived = deserializeMessage(msg);
        LOG.log(Level.FINE, "RECEIVE << {0}", messagereceived.op);
        LOG.log(Level.FINE, "RECEIVE PRINCIPAL << {0}", messagereceived.principal);
        LOG.log(Level.FINE, "RECEIVE TICKET << {0}", messagereceived.ticket);
        LOG.log(Level.FINE, "RECEIVE ROLES << {0}", messagereceived.roles);

        String ticket = TicketContainer.instance.getTicket(messagereceived.principal);
        Users user = userBean.findByEmail(this.sender);
        if (ticket != null && (messagereceived.ticket == null || !ticket.equals(messagereceived.ticket))) {

            /*
             * not to pollute logs, log instead of exception
             */
            if (StringUtils.isEmpty(messagereceived.ticket)) {
                LOG.log(Level.INFO, "{0} message: invalid ticket {1} != {2}",
                        new Object[] { messagereceived.op, messagereceived.ticket, ticket });
            } else if (!messagereceived.op.equals(OP.PING)) {
                impl.sendMsg(conn, serializeMessage(new Message(OP.SESSION_LOGOUT).put("info",
                        "Your ticket is invalid possibly due to server restart. Please login again.")));
            }
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,
                        "Invalid ticket " + messagereceived.ticket + " != " + ticket));
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }

        boolean allowAnonymous = impl.getConf().getConf().isAnonymousAllowed();
        if (!allowAnonymous && messagereceived.principal.equals("anonymous")) {
            throw new Exception("Anonymous access not allowed ");
        }

        messagereceived.principal = this.project.getProjectGenericUser();
        HashSet<String> userAndRoles = new HashSet<>();
        userAndRoles.add(messagereceived.principal);
        if (!messagereceived.roles.equals("")) {
            HashSet<String> roles = gson.fromJson(messagereceived.roles, new TypeToken<HashSet<String>>() {
            }.getType());
            if (roles != null) {
                userAndRoles.addAll(roles);
            }
        }

        AuthenticationInfo subject = new AuthenticationInfo(messagereceived.principal, messagereceived.roles,
                messagereceived.ticket);
        /**
         * Lets be elegant here
         */
        switch (messagereceived.op) {
        case LIST_NOTES:
            impl.unicastNoteList(conn, subject, userAndRoles);
            break;
        case RELOAD_NOTES_FROM_REPO:
            impl.broadcastReloadedNoteList(subject, userAndRoles);
            break;
        case GET_HOME_NOTE:
            impl.sendHomeNote(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case GET_NOTE:
            impl.sendNote(conn, userAndRoles, notebook, messagereceived, user, this.hdfsUsername);
            break;
        case NEW_NOTE:
            impl.createNote(conn, userAndRoles, notebook, messagereceived);
            break;
        case DEL_NOTE:
            impl.removeNote(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case REMOVE_FOLDER:
            impl.removeFolder(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case MOVE_NOTE_TO_TRASH:
            impl.moveNoteToTrash(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case MOVE_FOLDER_TO_TRASH:
            impl.moveFolderToTrash(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case EMPTY_TRASH:
            impl.emptyTrash(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case RESTORE_FOLDER:
            impl.restoreFolder(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case RESTORE_NOTE:
            impl.restoreNote(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case RESTORE_ALL:
            impl.restoreAll(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case CLONE_NOTE:
            impl.cloneNote(conn, userAndRoles, notebook, messagereceived);
            break;
        case IMPORT_NOTE:
            impl.importNote(conn, userAndRoles, notebook, messagereceived);
            break;
        case COMMIT_PARAGRAPH:
            impl.updateParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case RUN_PARAGRAPH:
            impl.runParagraph(conn, userAndRoles, notebook, messagereceived, user, certificateMaterializer,
                    settings, dfsService);
            break;
        case PARAGRAPH_EXECUTED_BY_SPELL:
            impl.broadcastSpellExecution(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case RUN_ALL_PARAGRAPHS:
            impl.runAllParagraphs(conn, userAndRoles, notebook, messagereceived, user, certificateMaterializer,
                    settings, dfsService);
            break;
        case CANCEL_PARAGRAPH:
            impl.cancelParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case MOVE_PARAGRAPH:
            impl.moveParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case INSERT_PARAGRAPH:
            impl.insertParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case COPY_PARAGRAPH:
            impl.copyParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case PARAGRAPH_REMOVE:
            impl.removeParagraph(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case PARAGRAPH_CLEAR_OUTPUT:
            impl.clearParagraphOutput(conn, userAndRoles, notebook, messagereceived, user, this.hdfsUsername);
            break;
        case PARAGRAPH_CLEAR_ALL_OUTPUT:
            impl.clearAllParagraphOutput(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case NOTE_UPDATE:
            impl.updateNote(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case NOTE_RENAME:
            impl.renameNote(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case FOLDER_RENAME:
            impl.renameFolder(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case UPDATE_PERSONALIZED_MODE:
            impl.updatePersonalizedMode(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case COMPLETION:
            impl.completion(conn, userAndRoles, notebook, messagereceived);
            break;
        case PING:
            break; //do nothing
        case ANGULAR_OBJECT_UPDATED:
            impl.angularObjectUpdated(conn, userAndRoles, notebook, messagereceived);
            break;
        case ANGULAR_OBJECT_CLIENT_BIND:
            impl.angularObjectClientBind(conn, userAndRoles, notebook, messagereceived);
            break;
        case ANGULAR_OBJECT_CLIENT_UNBIND:
            impl.angularObjectClientUnbind(conn, userAndRoles, notebook, messagereceived);
            break;
        case LIST_CONFIGURATIONS:
            impl.sendAllConfigurations(conn, userAndRoles, notebook);
            break;
        case CHECKPOINT_NOTE:
            impl.checkpointNote(conn, notebook, messagereceived);
            break;
        case LIST_REVISION_HISTORY:
            impl.listRevisionHistory(conn, notebook, messagereceived);
            break;
        case SET_NOTE_REVISION:
            impl.setNoteRevision(conn, userAndRoles, notebook, messagereceived, user);
            break;
        case NOTE_REVISION:
            impl.getNoteByRevision(conn, notebook, messagereceived);
            break;
        case LIST_NOTE_JOBS:
            impl.unicastNoteJobInfo(conn, messagereceived);
            break;
        case UNSUBSCRIBE_UPDATE_NOTE_JOBS:
            impl.unsubscribeNoteJobInfo(conn);
            break;
        case GET_INTERPRETER_BINDINGS:
            impl.getInterpreterBindings(conn, messagereceived);
            break;
        case SAVE_INTERPRETER_BINDINGS:
            impl.saveInterpreterBindings(conn, messagereceived, zeppelinResource);
            break;
        case EDITOR_SETTING:
            impl.getEditorSetting(conn, messagereceived);
            break;
        case GET_INTERPRETER_SETTINGS:
            impl.getInterpreterSettings(conn, subject);
            break;
        case WATCHER:
            impl.switchConnectionToWatcher(conn, messagereceived, this.hdfsUsername, notebookServerImplFactory);
            break;
        default:
            break;
        }
    } catch (Exception e) {
        Level logLevel = Level.SEVERE;
        if (e.getMessage().contains("is not allowed to empty the Trash")) {
            logLevel = Level.INFO;
        }
        LOG.log(logLevel, "Can't handle message", e);
    }
}

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

/**
 * /*  w w  w  . j  a  v a 2 s .c o m*/
 * 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.server.execution.tracking.client.main.HydrographMain.java

/**
 *    //from   ww w . j  a  va2  s .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:io.hops.hopsworks.api.zeppelin.socket.NotebookServer.java

public void closeConnection() {
    try {/*ww w. j  a va 2  s  .  co  m*/
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText("Restarting zeppelin.");
            this.session.close(new CloseReason(CloseReason.CloseCodes.SERVICE_RESTART, "Restarting zeppelin."));
        }
        impl.removeConnectionFromAllNote(this.session);
        impl.removeConnectedSockets(this.session, notebookServerImplFactory);
        impl.removeUserConnection(this.hdfsUsername, this.session);
        impl.removeUserConnection(project.getProjectGenericUser(), this.session);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

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

private void authenticateUser(Session session, Project project, String user) {
    //returns the user role in project. Null if the user has no role in project
    this.userRole = projectTeamBean.findCurrentRole(project, user);
    LOG.log(Level.FINEST, "User role in this project {0}", this.userRole);
    Users users = userBean.findByEmail(user);
    if (users == null || this.userRole == null) {
        try {//from   w  w  w  . j  a v a 2  s. co  m
            session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,
                    "You do not have a role in this project."));
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
    this.hdfsUsername = hdfsUsersController.getHdfsUserName(project, users);
}