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:hydrograph.ui.graph.utility.JobScpAndProcessUtility.java

/**
 * Close Websocket connection Connection
 * @param session//from  w w  w .j  av a2 s . c  o  m
 */
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 closeConnection(Session session, String hdfsUsername,
        NotebookServerImplFactory notebookServerImplFactory) {
    try {//from w  ww.j  av a  2 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:org.apache.nifi.processors.websockets.ListenWebSocket.java

@OnStopped
public void stopWebSocketListener() {
    if (session.isOpen()) {
        getLogger().info("Stopping WebSocket session...");
        try {/*from www .  ja  v  a2s  . c  om*/
            session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "ListenWebSocket stopped ..."));
            getLogger().info("WebSocket session stopped");
        } catch (Exception ex) {
            getLogger().error(ex.getMessage(), ex);
        }
    } else {
        getLogger().warn("WebSocket session wasn't open");
    }
}

From source file:org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.SubscriptionEndpoint.java

/**
 * Web socket onError use to handle  socket connection error
 *
 * @param session    - Registered  session.
 * @param throwable  - Web socket exception
 * @param deviceType - DeviceType//from  ww  w  .j  a  va 2  s .  co m
 * @param deviceId   - Device Identifier
 */
public void onError(Session session, Throwable throwable, @PathParam("deviceType") String deviceType,
        @PathParam("deviceId") String deviceId) {

    if (throwable instanceof IOException) {
        if (log.isDebugEnabled()) {
            log.error("Error occurred in session ID: " + session.getId() + " device type: " + deviceType
                    + "device id: " + deviceId + ", for request URI - " + session.getRequestURI() + ", "
                    + throwable.getMessage(), throwable);
        }
    } else {
        log.error("Error occurred in session ID: " + session.getId() + " device type: " + deviceType
                + " device " + "id: " + deviceId + ", for request URI - " + session.getRequestURI() + ", "
                + throwable.getMessage(), throwable);
    }
    try {
        ServiceHolder.getInstance().getRemoteSessionManagementService().endSession(session,
                "Remote session closed");
        if (session.isOpen()) {
            session.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Unexpected Error Occurred"));
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.error("Failed to disconnect the client.", ex);
        }
    }
}

From source file:org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementServiceImpl.java

/**
 * Closing the session and cleanup the resources
 *
 * @param session Web socket Remote Session
 *//*ww  w  . ja  v a 2s.  c om*/
@Override
public void endSession(Session session, String closeReason) {

    RemoteSession remoteSession = RemoteSessionManagementDataHolder.getInstance().getSessionMap()
            .remove(session.getId());
    if (remoteSession != null) {
        //String operationId = remoteSession.getOperationId();
        String deviceKey = remoteSession.getTenantDomain() + "/" + remoteSession.getDeviceType() + "/"
                + remoteSession.getDeviceId();
        RemoteSession lastSession = RemoteSessionManagementDataHolder.getInstance()
                .getActiveDeviceClientSessionMap().get(deviceKey);
        if (lastSession != null && lastSession.getMySession().getId().equals(session.getId())) {
            RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap().remove(deviceKey);
        }
        if (remoteSession.getPeerSession() != null) {
            Session peerSession = remoteSession.getPeerSession().getMySession();
            if (peerSession != null) {
                RemoteSessionManagementDataHolder.getInstance().getSessionMap().remove(peerSession.getId());
                if (lastSession != null && lastSession.getMySession().getId().equals(peerSession.getId())) {
                    RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap()
                            .remove(deviceKey);
                }
                if (peerSession.isOpen()) {
                    try {
                        peerSession.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, closeReason));
                    } catch (IOException ex) {
                        if (log.isDebugEnabled()) {
                            log.error("Failed to disconnect the client.", ex);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementServiceImpl.java

/**
 * Starting new client session//  w  w  w  .  ja va  2s  . c o  m
 *
 * @param session      Web socket Session
 * @param tenantDomain Tenant domain
 * @param deviceType   Device Type
 * @param deviceId     Device Id
 * @throws RemoteSessionManagementException throws when session has errors with accessing device resources
 * @throws OperationManagementException     throws when error occured during new operation
 * @throws InvalidDeviceException           throws when incorrect device identifier
 */
private void initializeClientSession(Session session, String tenantDomain, String deviceType, String deviceId)
        throws RemoteSessionManagementException, OperationManagementException, InvalidDeviceException {

    RemoteSession clientRemote = new RemoteSession(session, tenantDomain, deviceType, deviceId,
            RemoteSessionConstants.CONNECTION_TYPE.CLIENT);
    String deviceKey = tenantDomain + "/" + deviceType + "/" + deviceId;
    // Create new remote control operation to start the session
    RemoteSession activeSession = RemoteSessionManagementDataHolder.getInstance()
            .getActiveDeviceClientSessionMap().putIfAbsent(deviceKey, clientRemote);
    if (activeSession != null && activeSession.getMySession().isOpen()
            && activeSession.getPeerSession() == null) {
        throw new RemoteSessionManagementException("Another client session waiting on device to connect.");
    } else {
        // if there is pending session exists but already closed, then we need to remove it.
        if (activeSession != null) {
            RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap().remove(deviceKey);
            try {
                activeSession.getMySession().close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY,
                        "Remote " + "session closed due to new session request"));
            } catch (IOException ex) {
                if (log.isDebugEnabled()) {
                    log.error("Failed to disconnect the client.", ex);
                }
            }
            // Use put if absent for adding session to waiting list since we need to overcome
            // multithreaded session requests.
            activeSession = RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap()
                    .putIfAbsent(deviceKey, clientRemote);
        }
        // If another client tried to start session same time then active session will be
        // exist. So we are adding session request only no parallel sessions added to map
        if (activeSession == null) {

            // Create operation if session initiated by client
            Operation operation = new ConfigOperation();
            operation.setCode(RemoteSessionConstants.REMOTE_CONNECT);
            operation.setEnabled(true);
            operation.setControl(Operation.Control.NO_REPEAT);
            JSONObject payload = new JSONObject();
            payload.put("serverUrl", RemoteSessionManagementDataHolder.getInstance().getServerUrl());
            operation.setPayLoad(payload.toString());
            String date = new SimpleDateFormat(RemoteSessionConstants.DATE_FORMAT_NOW).format(new Date());
            operation.setCreatedTimeStamp(date);
            List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
            deviceIdentifiers.add(new DeviceIdentifier(deviceId, deviceType));
            Activity activity = RemoteSessionManagementDataHolder.getInstance()
                    .getDeviceManagementProviderService()
                    .addOperation(deviceType, operation, deviceIdentifiers);
            clientRemote.setOperationId(activity.getActivityId()
                    .replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
            RemoteSessionManagementDataHolder.getInstance().getSessionMap().put(session.getId(), clientRemote);
            log.info("Client remote session opened for session id: " + session.getId() + " device Type : "
                    + deviceType + " , " + "deviceId : " + deviceId);
        } else {
            throw new RemoteSessionManagementException(
                    "Another client session waiting on " + "device to connect.");
        }
    }
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.SuperTenantSubscriptionEndpoint.java

/**
 * Web socket onOpen - When client sends a message
 *
 * @param session    - Users registered session.
 * @param streamName - StreamName extracted from the ws url.
 * @param version    -  Version extracted from the ws url.
 *///from ww w  . ja  va  2s  . co m
@OnOpen
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
        @PathParam("version") String version) {
    if (log.isDebugEnabled()) {
        log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
    }
    Map<String, List<String>> sessionQueryParam = new HashedMap();
    List<String> sessionQueryParamList = new LinkedList<>();
    sessionQueryParamList.add(session.getQueryString());
    sessionQueryParam.put(Constants.QUERY_STRING, sessionQueryParamList);
    Authenticator authenticator = ServiceHolder.getWebsocketValidationService().getAuthenticator();
    AuthenticationInfo authenticationInfo = authenticator.isAuthenticated(sessionQueryParam);
    if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
        Authorizer authorizer = ServiceHolder.getWebsocketValidationService().getAuthorizer();
        boolean isAuthorized = authorizer.isAuthorized(authenticationInfo, session, streamName);
        if (isAuthorized) {
            try {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService()
                        .subscribeWebsocket(streamName, version, session);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        } else {
            log.info("Failed to authorize the connection for the stream : " + streamName + " , version : "
                    + version);
        }
    } else {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
        } catch (IOException e) {
            log.error("Failed to disconnect the unauthorized client.", e);
        }
    }
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.TenantSubscriptionEndpoint.java

/**
 * Web socket onOpen - When client sends a message
 *
 * @param session - Users registered session.
 * @param streamName - StreamName extracted from the ws url.
 * @param version -  Version extracted from the ws url.
 * @param tdomain - Tenant domain extracted from ws url.
 *///w w  w.jav  a 2  s .co  m
@OnOpen
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
        @PathParam("version") String version, @PathParam("tdomain") String tdomain) {
    if (log.isDebugEnabled()) {
        log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
    }
    Map<String, List<String>> sessionQueryParam = new HashedMap();
    List<String> sessionQueryParamList = new LinkedList<>();
    sessionQueryParamList.add(session.getQueryString());
    sessionQueryParam.put(Constants.QUERY_STRING, sessionQueryParamList);
    Authenticator authenticator = ServiceHolder.getWebsocketValidationService().getAuthenticator();
    AuthenticationInfo authenticationInfo = authenticator.isAuthenticated(sessionQueryParam);
    if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
        Authorizer authorizer = ServiceHolder.getWebsocketValidationService().getAuthorizer();
        boolean isAuthorized = authorizer.isAuthorized(authenticationInfo, session, streamName);
        if (isAuthorized) {
            try {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .setTenantDomain(authenticationInfo.getTenantDomain(), true);
                ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService()
                        .subscribeWebsocket(streamName, version, session);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        } else {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
            } catch (IOException e) {
                log.error("Failed to disconnect the unauthorized client.", e);
            }
        }
    } else {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
        } catch (IOException e) {
            log.error("Failed to disconnect the unauthorized client.", e);
        }
    }
}