Search in sources :

Example 1 with WebSocketConfigurationException

use of org.apache.nifi.websocket.WebSocketConfigurationException in project nifi by apache.

the class JettyWebSocketClient method maintainSessions.

void maintainSessions() throws Exception {
    if (client == null) {
        return;
    }
    connectionLock.lock();
    final ComponentLog logger = getLogger();
    try {
        // Loop through existing sessions and reconnect.
        for (String clientId : activeSessions.keySet()) {
            final WebSocketMessageRouter router;
            try {
                router = routers.getRouterOrFail(clientId);
            } catch (final WebSocketConfigurationException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("The clientId {} is no longer active. Discarding the clientId.", new Object[] { clientId });
                }
                activeSessions.remove(clientId);
                continue;
            }
            final String sessionId = activeSessions.get(clientId);
            // If this session is still alive, do nothing.
            if (!router.containsSession(sessionId)) {
                // This session is no longer active, reconnect it.
                // If it fails, the sessionId will remain in activeSessions, and retries later.
                // This reconnect attempt is continued until user explicitly stops a processor or this controller service.
                connect(clientId, sessionId);
            }
        }
    } finally {
        connectionLock.unlock();
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Session maintenance completed. activeSessions={}", new Object[] { activeSessions });
    }
}
Also used : WebSocketMessageRouter(org.apache.nifi.websocket.WebSocketMessageRouter) WebSocketConfigurationException(org.apache.nifi.websocket.WebSocketConfigurationException) ComponentLog(org.apache.nifi.logging.ComponentLog)

Example 2 with WebSocketConfigurationException

use of org.apache.nifi.websocket.WebSocketConfigurationException in project nifi by apache.

the class PutWebSocket method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession processSession) throws ProcessException {
    final FlowFile flowfile = processSession.get();
    if (flowfile == null) {
        return;
    }
    final String sessionId = context.getProperty(PROP_WS_SESSION_ID).evaluateAttributeExpressions(flowfile).getValue();
    final String webSocketServiceId = context.getProperty(PROP_WS_CONTROLLER_SERVICE_ID).evaluateAttributeExpressions(flowfile).getValue();
    final String webSocketServiceEndpoint = context.getProperty(PROP_WS_CONTROLLER_SERVICE_ENDPOINT).evaluateAttributeExpressions(flowfile).getValue();
    final String messageTypeStr = context.getProperty(PROP_WS_MESSAGE_TYPE).evaluateAttributeExpressions(flowfile).getValue();
    final WebSocketMessage.Type messageType = WebSocketMessage.Type.valueOf(messageTypeStr);
    if (StringUtils.isEmpty(sessionId)) {
        getLogger().debug("Specific SessionID not specified. Message will be broadcast to all connected clients.");
    }
    if (StringUtils.isEmpty(webSocketServiceId) || StringUtils.isEmpty(webSocketServiceEndpoint)) {
        transferToFailure(processSession, flowfile, "Required WebSocket attribute was not found.");
        return;
    }
    final ControllerService controllerService = context.getControllerServiceLookup().getControllerService(webSocketServiceId);
    if (controllerService == null) {
        transferToFailure(processSession, flowfile, "WebSocket ControllerService was not found.");
        return;
    } else if (!(controllerService instanceof WebSocketService)) {
        transferToFailure(processSession, flowfile, "The ControllerService found was not a WebSocket ControllerService but a " + controllerService.getClass().getName());
        return;
    }
    final WebSocketService webSocketService = (WebSocketService) controllerService;
    final byte[] messageContent = new byte[(int) flowfile.getSize()];
    final long startSending = System.currentTimeMillis();
    final AtomicReference<String> transitUri = new AtomicReference<>();
    final Map<String, String> attrs = new HashMap<>();
    attrs.put(ATTR_WS_CS_ID, webSocketService.getIdentifier());
    if (!StringUtils.isEmpty(sessionId)) {
        attrs.put(ATTR_WS_SESSION_ID, sessionId);
    }
    attrs.put(ATTR_WS_ENDPOINT_ID, webSocketServiceEndpoint);
    attrs.put(ATTR_WS_MESSAGE_TYPE, messageTypeStr);
    processSession.read(flowfile, in -> {
        StreamUtils.fillBuffer(in, messageContent, true);
    });
    try {
        webSocketService.sendMessage(webSocketServiceEndpoint, sessionId, sender -> {
            switch(messageType) {
                case TEXT:
                    sender.sendString(new String(messageContent, CHARSET_NAME));
                    break;
                case BINARY:
                    sender.sendBinary(ByteBuffer.wrap(messageContent));
                    break;
            }
            attrs.put(ATTR_WS_LOCAL_ADDRESS, sender.getLocalAddress().toString());
            attrs.put(ATTR_WS_REMOTE_ADDRESS, sender.getRemoteAddress().toString());
            transitUri.set(sender.getTransitUri());
        });
        final FlowFile updatedFlowFile = processSession.putAllAttributes(flowfile, attrs);
        final long transmissionMillis = System.currentTimeMillis() - startSending;
        processSession.getProvenanceReporter().send(updatedFlowFile, transitUri.get(), transmissionMillis);
        processSession.transfer(updatedFlowFile, REL_SUCCESS);
    } catch (WebSocketConfigurationException | IllegalStateException | IOException e) {
        // WebSocketConfigurationException: If the corresponding WebSocketGatewayProcessor has been stopped.
        // IllegalStateException: Session is already closed or not found.
        // IOException: other IO error.
        getLogger().error("Failed to send message via WebSocket due to " + e, e);
        transferToFailure(processSession, flowfile, e.toString());
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) ControllerService(org.apache.nifi.controller.ControllerService) WebSocketService(org.apache.nifi.websocket.WebSocketService) WebSocketMessage(org.apache.nifi.websocket.WebSocketMessage) WebSocketConfigurationException(org.apache.nifi.websocket.WebSocketConfigurationException)

Example 3 with WebSocketConfigurationException

use of org.apache.nifi.websocket.WebSocketConfigurationException in project nifi by apache.

the class JettyWebSocketClient method connect.

private void connect(final String clientId, String sessionId) throws IOException {
    connectionLock.lock();
    try {
        final WebSocketMessageRouter router;
        try {
            router = routers.getRouterOrFail(clientId);
        } catch (WebSocketConfigurationException e) {
            throw new IllegalStateException("Failed to get router due to: " + e, e);
        }
        final RoutingWebSocketListener listener = new RoutingWebSocketListener(router);
        listener.setSessionId(sessionId);
        final ClientUpgradeRequest request = new ClientUpgradeRequest();
        final Future<Session> connect = client.connect(listener, webSocketUri, request);
        getLogger().info("Connecting to : {}", new Object[] { webSocketUri });
        final Session session;
        try {
            session = connect.get(connectionTimeoutMillis, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            throw new IOException("Failed to connect " + webSocketUri + " due to: " + e, e);
        }
        getLogger().info("Connected, session={}", new Object[] { session });
        activeSessions.put(clientId, listener.getSessionId());
    } finally {
        connectionLock.unlock();
    }
}
Also used : WebSocketMessageRouter(org.apache.nifi.websocket.WebSocketMessageRouter) WebSocketConfigurationException(org.apache.nifi.websocket.WebSocketConfigurationException) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) IOException(java.io.IOException) WebSocketConfigurationException(org.apache.nifi.websocket.WebSocketConfigurationException) IOException(java.io.IOException) Session(org.eclipse.jetty.websocket.api.Session)

Aggregations

WebSocketConfigurationException (org.apache.nifi.websocket.WebSocketConfigurationException)3 IOException (java.io.IOException)2 WebSocketMessageRouter (org.apache.nifi.websocket.WebSocketMessageRouter)2 HashMap (java.util.HashMap)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 ControllerService (org.apache.nifi.controller.ControllerService)1 FlowFile (org.apache.nifi.flowfile.FlowFile)1 ComponentLog (org.apache.nifi.logging.ComponentLog)1 WebSocketMessage (org.apache.nifi.websocket.WebSocketMessage)1 WebSocketService (org.apache.nifi.websocket.WebSocketService)1 Session (org.eclipse.jetty.websocket.api.Session)1 ClientUpgradeRequest (org.eclipse.jetty.websocket.client.ClientUpgradeRequest)1