Ejemplo n.º 1
0
  @Override
  public void onWebSocketText(final String data) {

    if (data == null) {
      logger.log(Level.WARNING, "Empty text message received.");
      return;
    }

    logger.log(
        Level.FINE,
        "############################################################ RECEIVED \n{0}",
        data.substring(0, Math.min(data.length(), 1000)));

    // parse web socket data from JSON
    final WebSocketMessage webSocketData = gson.fromJson(data, WebSocketMessage.class);

    final App app = StructrApp.getInstance(securityContext);

    try (final Tx tx = app.tx()) {

      this.callback = webSocketData.getCallback();

      final String command = webSocketData.getCommand();
      final Class type = commandSet.get(command);

      final String sessionIdFromMessage = webSocketData.getSessionId();

      if (type != null) {

        if (sessionIdFromMessage != null) {

          // try to authenticated this connection by sessionId
          authenticate(sessionIdFromMessage);
        }

        // we only permit LOGIN commands if authentication based on sessionId was not successful
        if (!isAuthenticated() && !type.equals(LoginCommand.class)) {

          // send 401 Authentication Required
          send(MessageBuilder.status().code(401).message("").build(), true);

          return;
        }

        AbstractCommand abstractCommand = (AbstractCommand) type.newInstance();

        abstractCommand.setWebSocket(this);
        abstractCommand.setSession(session);
        abstractCommand.setIdProperty(idProperty);

        // store authenticated-Flag in webSocketData
        // so the command can access it
        webSocketData.setSessionValid(isAuthenticated());

        // process message
        try {

          abstractCommand.processMessage(webSocketData);

          // commit transaction
          tx.success();

        } catch (FrameworkException fex) {

          fex.printStackTrace(System.out);

          // send 400 Bad Request
          send(MessageBuilder.status().code(400).message(fex.toString()).build(), true);
        }

      } else {

        logger.log(Level.WARNING, "Unknow command {0}", command);

        // send 400 Bad Request
        send(MessageBuilder.status().code(400).message("Unknown command").build(), true);
      }

    } catch (FrameworkException | IllegalAccessException | InstantiationException t) {

      logger.log(Level.WARNING, "Unable to parse message.", t);
    }
  }