org.kurento.jsonrpc.message.Request Java Examples

The following examples show how to use org.kurento.jsonrpc.message.Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonRpcUserControl.java    From kurento-room with Apache License 2.0 6 votes vote down vote up
public void joinRoom(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) throws IOException, InterruptedException,
    ExecutionException {
  String roomName = getStringParam(request, ProtocolElements.JOINROOM_ROOM_PARAM);
  String userName = getStringParam(request, ProtocolElements.JOINROOM_USER_PARAM);

  boolean dataChannels = false;
  if (request.getParams().has(ProtocolElements.JOINROOM_DATACHANNELS_PARAM)) {
    dataChannels = request.getParams().get(ProtocolElements.JOINROOM_DATACHANNELS_PARAM)
        .getAsBoolean();
  }

  ParticipantSession participantSession = getParticipantSession(transaction);
  participantSession.setParticipantName(userName);
  participantSession.setRoomName(roomName);
  participantSession.setDataChannels(dataChannels);

  roomManager.joinRoom(userName, roomName, dataChannels, true, participantRequest);
}
 
Example #2
Source File: CloseSessionTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final Transaction transaction, Request<String> request)
    throws Exception {

  Session session = transaction.getSession();

  if (session.isNew()) {
    transaction.sendResponse("new");
  } else {
    transaction.sendResponse("old");
  }

  if (counter == 2) {
    session.close();
  }
  counter++;
}
 
Example #3
Source File: BidirectionalMultiTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(Transaction transaction, Request<Integer> request) throws Exception {

  log.debug("Request id:" + request.getId());
  log.debug("Request method:" + request.getMethod());
  log.debug("Request params:" + request.getParams());

  transaction.sendResponse(request.getParams());

  final Session session = transaction.getSession();
  final Object params = request.getParams();

  new Thread() {
    @Override
    public void run() {
      asyncReverseSend(session, params);
    }
  }.start();
}
 
Example #4
Source File: BidirectionalMultiTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws IOException, InterruptedException {

  log.debug("Client started");

  JsonRpcClient client = createJsonRpcClient("/BidirectionalMultiTest");

  client.setServerRequestHandler(new DefaultJsonRpcHandler<Integer>() {

    @Override
    public void handleRequest(Transaction transaction, Request<Integer> request)
        throws Exception {

      log.debug("Reverse request: " + request);
      transaction.sendResponse(request.getParams() + 1);
    }
  });

  for (int i = 0; i < 60; i++) {
    client.sendRequest("echo", i, Integer.class);
  }

  client.close();

  log.debug("Client finished");
}
 
Example #5
Source File: JsonUtils.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
/**
 * Gson object accessor (getter).
 *
 * @return son object
 */
public static Gson getGson() {

  if (gson == null) {
    synchronized (JsonUtils.class) {
      if (gson == null) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Request.class, new JsonRpcRequestDeserializer());

        builder.registerTypeAdapter(Response.class, new JsonRpcResponseDeserializer());

        builder.registerTypeAdapter(Props.class, new JsonPropsAdapter());

        builder.disableHtmlEscaping();

        gson = builder.create();
      }
    }
  }

  return gson;
}
 
Example #6
Source File: GenericMessageTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requestTest() {

  Params params = new Params();
  params.param1 = "Value1";
  params.param2 = "Value2";
  params.data = new Data();
  params.data.data1 = "XX";
  params.data.data2 = "YY";

  Request<Params> request = new Request<Params>(1, "method", params);

  String requestJson = JsonUtils.toJsonRequest(request);

  log.debug(requestJson);

  Request<Params> newRequest = JsonUtils.fromJsonRequest(requestJson, Params.class);

  Assert.assertEquals(params.param1, newRequest.getParams().param1);
  Assert.assertEquals(params.param2, newRequest.getParams().param2);
  Assert.assertEquals(params.data.data1, newRequest.getParams().data.data1);
  Assert.assertEquals(params.data.data2, newRequest.getParams().data.data2);

}
 
Example #7
Source File: RpcHandler.java    From openvidu with Apache License 2.0 6 votes vote down vote up
private void publishVideo(RpcConnection rpcConnection, Request<JsonObject> request) {
	Participant participant;
	try {
		participant = sanityCheckOfSession(rpcConnection, "publish");
	} catch (OpenViduException e) {
		return;
	}

	if (sessionManager.isPublisherInSession(rpcConnection.getSessionId(), participant)) {
		MediaOptions options = sessionManager.generateMediaOptions(request);
		sessionManager.publishVideo(participant, options, request.getId());
	} else {
		log.error("Error: participant {} is not a publisher", participant.getParticipantPublicId());
		throw new OpenViduException(Code.USER_UNAUTHORIZED_ERROR_CODE,
				"Unable to publish video. The user does not have a valid token");
	}
}
 
Example #8
Source File: RpcHandler.java    From openvidu with Apache License 2.0 6 votes vote down vote up
private void onIceCandidate(RpcConnection rpcConnection, Request<JsonObject> request) {
	Participant participant;
	try {
		participant = sanityCheckOfSession(rpcConnection, "onIceCandidate");
	} catch (OpenViduException e) {
		return;
	}

	String endpointName = getStringParam(request, ProtocolElements.ONICECANDIDATE_EPNAME_PARAM);
	String candidate = getStringParam(request, ProtocolElements.ONICECANDIDATE_CANDIDATE_PARAM);
	String sdpMid = getStringParam(request, ProtocolElements.ONICECANDIDATE_SDPMIDPARAM);
	int sdpMLineIndex = getIntParam(request, ProtocolElements.ONICECANDIDATE_SDPMLINEINDEX_PARAM);

	log.info(
			"New candidate received from participant {}: {connectionId: \"{}\", sdpMid: {}, sdpMLineIndex: {}, candidate: \"{}\"}",
			participant.getParticipantPublicId(), endpointName, sdpMid, sdpMLineIndex, candidate);

	sessionManager.onIceCandidate(participant, endpointName, candidate, sdpMLineIndex, sdpMid, request.getId());
}
 
Example #9
Source File: RpcHandler.java    From openvidu with Apache License 2.0 6 votes vote down vote up
private void removeFilter(RpcConnection rpcConnection, Request<JsonObject> request) {
	Participant participant;
	try {
		participant = sanityCheckOfSession(rpcConnection, "removeFilter");
	} catch (OpenViduException e) {
		return;
	}
	String streamId = getStringParam(request, ProtocolElements.FILTER_STREAMID_PARAM);
	boolean isModerator = this.sessionManager.isModeratorInSession(rpcConnection.getSessionId(), participant);

	// Allow removing filter if the user is a MODERATOR (owning the stream or other
	// user's stream) or if the user is the owner of the stream
	if (isModerator || this.userIsStreamOwner(rpcConnection.getSessionId(), participant, streamId)) {
		Participant moderator = isModerator ? participant : null;
		sessionManager.removeFilter(sessionManager.getSession(rpcConnection.getSessionId()), streamId, moderator,
				request.getId(), "removeFilter");
	} else {
		log.error("Error: participant {} is not a moderator", participant.getParticipantPublicId());
		throw new OpenViduException(Code.USER_UNAUTHORIZED_ERROR_CODE,
				"Unable to remove filter. The user does not have a valid token");
	}
}
 
Example #10
Source File: RpcHandler.java    From openvidu with Apache License 2.0 6 votes vote down vote up
private void receiveVideoFrom(RpcConnection rpcConnection, Request<JsonObject> request) {
	Participant participant;
	try {
		participant = sanityCheckOfSession(rpcConnection, "subscribe");
	} catch (OpenViduException e) {
		return;
	}

	String senderPublicId = getStringParam(request, ProtocolElements.RECEIVEVIDEO_SENDER_PARAM);

	// Parse sender public id from stream id
	if (senderPublicId.startsWith(IdentifierPrefixes.STREAM_ID + "IPC_")
			&& senderPublicId.contains(IdentifierPrefixes.IPCAM_ID)) {
		// If IPCAM
		senderPublicId = senderPublicId.substring(senderPublicId.indexOf("_" + IdentifierPrefixes.IPCAM_ID) + 1,
				senderPublicId.length());
	} else {
		// Not IPCAM
		senderPublicId = senderPublicId.substring(
				senderPublicId.lastIndexOf(IdentifierPrefixes.PARTICIPANT_PUBLIC_ID), senderPublicId.length());
	}

	String sdpOffer = getStringParam(request, ProtocolElements.RECEIVEVIDEO_SDPOFFER_PARAM);

	sessionManager.subscribe(participant, senderPublicId, sdpOffer, request.getId());
}
 
Example #11
Source File: RpcHandler.java    From openvidu with Apache License 2.0 6 votes vote down vote up
private void execFilterMethod(RpcConnection rpcConnection, Request<JsonObject> request) {
	Participant participant;
	try {
		participant = sanityCheckOfSession(rpcConnection, "execFilterMethod");
	} catch (OpenViduException e) {
		return;
	}
	String streamId = getStringParam(request, ProtocolElements.FILTER_STREAMID_PARAM);
	String filterMethod = getStringParam(request, ProtocolElements.FILTER_METHOD_PARAM);
	JsonObject filterParams = JsonParser.parseString(getStringParam(request, ProtocolElements.FILTER_PARAMS_PARAM))
			.getAsJsonObject();
	boolean isModerator = this.sessionManager.isModeratorInSession(rpcConnection.getSessionId(), participant);

	// Allow executing filter method if the user is a MODERATOR (owning the stream
	// or other user's stream) or if the user is the owner of the stream
	if (isModerator || this.userIsStreamOwner(rpcConnection.getSessionId(), participant, streamId)) {
		Participant moderator = isModerator ? participant : null;
		sessionManager.execFilterMethod(sessionManager.getSession(rpcConnection.getSessionId()), streamId,
				filterMethod, filterParams, moderator, request.getId(), "execFilterMethod");
	} else {
		log.error("Error: participant {} is not a moderator", participant.getParticipantPublicId());
		throw new OpenViduException(Code.USER_UNAUTHORIZED_ERROR_CODE,
				"Unable to execute filter method. The user does not have a valid token");
	}
}
 
Example #12
Source File: JsonRpcRequestSenderHelper.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public <P, R> R sendRequest(Request<P> request, Class<R> resultClass)
    throws JsonRpcErrorException, IOException {

  Response<R> response = internalSendRequest(request, resultClass);

  if (response == null) {
    return null;
  }

  if (response.getSessionId() != null) {
    sessionId = response.getSessionId();
  }

  if (response.getError() != null) {
    throw new JsonRpcErrorException(response.getError());
  }

  return response.getResult();
}
 
Example #13
Source File: ProtocolManager.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
private void processCloseMessage(ServerSessionFactory factory, Request<JsonElement> request,
    ResponseSender responseSender, String transportId) {

  ServerSession session = sessionsManager.getByTransportId(transportId);
  if (session != null) {
    session.setGracefullyClosed();
    cancelCloseTimer(session);
  }

  try {
    responseSender.sendResponse(new Response<>(request.getId(), "bye"));
  } catch (IOException e) {
    log.warn("Exception sending close message response to client", e);
  }

  if (session != null) {
    this.closeSession(session, CLIENT_CLOSED_CLOSE_REASON);
  }
}
 
Example #14
Source File: DemoJsonRpcUserControl.java    From kurento-room with Apache License 2.0 6 votes vote down vote up
@Override
public void customRequest(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) {
  try {
    if (request.getParams() == null
        || request.getParams().get(filterType.getCustomRequestParam()) == null) {
      throw new RuntimeException(
          "Request element '" + filterType.getCustomRequestParam() + "' is missing");
    }
    switch (filterType) {
      case MARKER:
        handleMarkerRequest(transaction, request, participantRequest);
        break;
      case HAT:
      default:
        handleHatRequest(transaction, request, participantRequest);
    }
  } catch (Exception e) {
    log.error("Unable to handle custom request", e);
    try {
      transaction.sendError(e);
    } catch (IOException e1) {
      log.warn("Unable to send error response", e1);
    }
  }
}
 
Example #15
Source File: ServerJsonRpcHandler.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
private Notification participantUnpublished(Transaction transaction, Request<JsonObject> request) {
  String name = JsonRoomUtils.getRequestParam(request,
      ProtocolElements.PARTICIPANTUNPUBLISHED_NAME_PARAM, String.class);
  ParticipantUnpublishedInfo eventInfo = new ParticipantUnpublishedInfo(name);
  log.debug("Recvd participant unpublished event {}", eventInfo);
  return eventInfo;
}
 
Example #16
Source File: ServerJsonRpcHandler.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
private Notification participantLeft(Transaction transaction, Request<JsonObject> request) {
  String name = JsonRoomUtils.getRequestParam(request,
      ProtocolElements.PARTICIPANTLEFT_NAME_PARAM, String.class);
  ParticipantLeftInfo eventInfo = new ParticipantLeftInfo(name);
  log.debug("Recvd participant left event {}", eventInfo);
  return eventInfo;
}
 
Example #17
Source File: EchoJsonRpcHandler.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(Transaction transaction, Request<JsonObject> request) throws Exception {

  if (demoBean == null) {
    throw new RuntimeException("Not autowired dependencies");
  }
  log.debug("Request id:" + request.getId());
  log.debug("Request method:" + request.getMethod());
  log.debug("Request params:" + request.getParams());

  transaction.sendResponse(request.getParams());

}
 
Example #18
Source File: ServerJsonRpcHandler.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
private Notification participantJoined(Transaction transaction, Request<JsonObject> request) {
  String id = JsonRoomUtils.getRequestParam(request,
      ProtocolElements.PARTICIPANTJOINED_USER_PARAM, String.class);
  ParticipantJoinedInfo eventInfo = new ParticipantJoinedInfo(id);
  log.debug("Recvd participant joined event {}", eventInfo);
  return eventInfo;
}
 
Example #19
Source File: RomClientJsonRpcClient.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public RequestAndResponseType createUnsubscribeRequest(String objectRef,
    String listenerSubscription) {

  JsonObject params = JsonUtils.toJsonObject(
      new Props(UNSUBSCRIBE_OBJECT, objectRef).add(UNSUBSCRIBE_LISTENER, listenerSubscription));

  return new RequestAndResponseType(new Request<>(UNSUBSCRIBE_METHOD, params), Void.class);
}
 
Example #20
Source File: RomClientJsonRpcClient.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void addRomEventHandler(final RomEventHandler eventHandler) {

  this.client.setServerRequestHandler(new DefaultJsonRpcHandler<JsonObject>() {

    @Override
    public void handleRequest(Transaction transaction, Request<JsonObject> request)
        throws Exception {
      processEvent(eventHandler, request);
    }
  });
}
 
Example #21
Source File: JsonRoomUtils.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public static <T> T getRequestParam(Request<JsonObject> request, String paramName, Class<T> type,
    boolean allowNull) {
  JsonObject params = request.getParams();
  if (params == null) {
    if (!allowNull) {
      throw new OpenViduException(Code.TRANSPORT_REQUEST_ERROR_CODE,
          "Invalid request lacking parameter '" + paramName + "'");
    } else {
      return null;
    }
  }
  return getConverted(params.get(paramName), paramName, type, allowNull);
}
 
Example #22
Source File: MultipleSessionsTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(Transaction transaction, Request<String> request) throws Exception {

  if (demoBean == null) {
    throw new RuntimeException("Not autowired dependencies");
  }

  transaction.sendResponse(counter);
  counter++;
}
 
Example #23
Source File: JsonRpcAndJavaMethodManager.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private Response<JsonElement> execJavaMethod(Session session, Object object, Method m,
    Transaction transaction, Request<JsonObject> request)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

  Object[] values = calculateParamValues(session, m, request);

  Object result = m.invoke(object, values);

  if (result == null) {
    return null;
  } else {
    return new Response<>(null, gson.toJsonTree(result));
  }
}
 
Example #24
Source File: JsonRpcClientHttp.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() throws IOException {

  try {

    org.apache.http.client.fluent.Request.Post(url).bodyString("", ContentType.APPLICATION_JSON)
    .execute();

  } catch (ClientProtocolException e) {
    // Silence http connection exception. This indicate that server is
    // reachable and running
  }
}
 
Example #25
Source File: JsonRpcUserControl.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
public void onIceCandidate(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) {
  String endpointName = getStringParam(request, ProtocolElements.ONICECANDIDATE_EPNAME_PARAM);
  String candidate = getStringParam(request, ProtocolElements.ONICECANDIDATE_CANDIDATE_PARAM);
  String sdpMid = getStringParam(request, ProtocolElements.ONICECANDIDATE_SDPMIDPARAM);
  int sdpMLineIndex = getIntParam(request, ProtocolElements.ONICECANDIDATE_SDPMLINEINDEX_PARAM);

  roomManager.onIceCandidate(endpointName, candidate, sdpMLineIndex, sdpMid, participantRequest);
}
 
Example #26
Source File: JsonRpcUserControl.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
public void leaveRoom(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) {
  boolean exists = false;
  String pid = participantRequest.getParticipantId();
  // trying with room info from session
  String roomName = null;
  if (transaction != null) {
    roomName = getParticipantSession(transaction).getRoomName();
  }
  if (roomName == null) { // null when afterConnectionClosed
    log.warn("No room information found for participant with session Id {}. "
        + "Using the admin method to evict the user.", pid);
    leaveRoomAfterConnClosed(pid);
  } else {
    // sanity check, don't call leaveRoom unless the id checks out
    for (UserParticipant part : roomManager.getParticipants(roomName)) {
      if (part.getParticipantId().equals(participantRequest.getParticipantId())) {
        exists = true;
        break;
      }
    }
    if (exists) {
      log.debug("Participant with sessionId {} is leaving room {}", pid, roomName);
      roomManager.leaveRoom(participantRequest);
      log.info("Participant with sessionId {} has left room {}", pid, roomName);
    } else {
      log.warn("Participant with session Id {} not found in room {}. "
          + "Using the admin method to evict the user.", pid, roomName);
      leaveRoomAfterConnClosed(pid);
    }
  }
}
 
Example #27
Source File: JsonRpcUserControl.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
public void unsubscribeFromVideo(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) {

  String senderName = getStringParam(request, ProtocolElements.UNSUBSCRIBEFROMVIDEO_SENDER_PARAM);
  senderName = senderName.substring(0, senderName.indexOf("_"));

  roomManager.unsubscribe(senderName, participantRequest);
}
 
Example #28
Source File: JsonRpcUserControl.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
public void publishVideo(Transaction transaction, Request<JsonObject> request,
    ParticipantRequest participantRequest) {
  String sdpOffer = getStringParam(request, ProtocolElements.PUBLISHVIDEO_SDPOFFER_PARAM);
  boolean doLoopback = getBooleanParam(request, ProtocolElements.PUBLISHVIDEO_DOLOOPBACK_PARAM);

  roomManager.publishMedia(participantRequest, sdpOffer, doLoopback);
}
 
Example #29
Source File: NotificationTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final Transaction transaction, Request<Integer> request)
    throws Exception {

  if (!transaction.isNotification()) {
    throw new RuntimeException("Notification expected");
  }

  Thread.sleep(1000);

  transaction.getSession().sendNotification("response", request.getParams());
}
 
Example #30
Source File: ErrorServerTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final Transaction transaction, Request<String> request)
    throws Exception {

  String method = request.getMethod();

  if (method.equals("explicitError")) {

    transaction.sendError(-1, "EXCEPTION", "Exception message", "Data");

  } else if (method.equals("asyncError")) {

    transaction.startAsync();

    // Poor man method scheduling
    new Thread() {
      @Override
      public void run() {
        try {
          Thread.sleep(1000);
          transaction.sendError(-1, "GENERIC_EXCEPTION", "Exception message", "Data");
        } catch (Exception e) {
        }
      }
    }.start();

  } else if (method.equals("exceptionError")) {

    // 1, e.getMessage(), null
    throw new RuntimeException("Exception message");
  }
}