Returns observable to create a conversation.

@param request Request with conversation details to create.
@return Observable to to create a conversation.
484004
public Observable<ComapiResult<ConversationDetails>> createConversation(@NonNull final ConversationCreate request) {

        final String token = getToken();

        if (sessionController.isCreatingSession()) {
            return getTaskQueue().queueCreateConversation(request);
        } else if (TextUtils.isEmpty(token)) {
            return Observable.error(getSessionStateErrorDescription());
        } else {
            return doCreateConversation(token, request);
        }
    }
1366439
protected Object getNewSelection(final Request request) {
		String paramValue = request.getParameter(getId());

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

		// Figure out which option has been selected.
		List<?> options = getOptions();

		if (options == null || options.isEmpty()) {
			if (!isEditable()) {
				// User could not have made a selection.
				return null;
			}

			options = Collections.EMPTY_LIST;
		}

		int optionIndex = 0;

		for (Object option : options) {
			if (option instanceof OptionGroup) {
				List<?> groupOptions = ((OptionGroup) option).getOptions();
				if (groupOptions != null) {
					for (Object nestedOption : groupOptions) {
						if (paramValue.equals(optionToCode(nestedOption, optionIndex++))) {
							return nestedOption;
						}
					}
				}
			} else if (paramValue.equals(optionToCode(option, optionIndex++))) {
				return option;
			}
		}

		// Option not found, but if editable, user entered text
		if (isEditable()) {
			return paramValue;
		}

		// Invalid option. Ignore and use the current selection
		LOG.warn(
				"Option \"" + paramValue + "\" on the request is not a valid option. Will be ignored.");
		Object currentOption = getValue();
		return currentOption;
	}
1285478
private static void request(final Request request) {
        if (null == request) {
            WonderPush.logError("Request with null request.");
            return;
        }

        WonderPush.safeDefer(new Runnable() {
            @Override
            public void run() {
                // Decorate parameters
                WonderPushRequestParamsDecorator.decorate(request.getResource(), request.getParams());

                // Generate signature
                BasicHeader authorizationHeader = request.getAuthorizationHeader();

                // Headers
                BasicHeader[] headers = null;
                if (null != authorizationHeader) {
                    headers = new BasicHeader[1];
                    headers[0] = authorizationHeader;
                }

                String url = WonderPushUriHelper.getAbsoluteUrl(request.getResource());
                WonderPush.logDebug("requesting url: " + request.getMethod() + " " + url + "?" + request.getParams().getURLEncodedString());
                // TODO: support other contentTypes such as "application/json"
                String contentType = "application/x-www-form-urlencoded";

                // Handler
                final ResponseHandler handler = request.getHandler();
                HttpEntity entity = null;
                if (request.getParams() != null) {
                    try {
                        entity = request.getParams() != null ? request.getParams().getEntity(null) : null;
                    } catch (IOException ex) {
                        WonderPush.logError("Failed to create HttpEntity from params " + request.getParams(), ex);
                        if (handler != null) {
                            handler.onFailure(ex, new Response(""));
                        }
                        return;
                    }
                }
                final long sendDate = SystemClock.elapsedRealtime();
                JsonHttpResponseHandler jsonHandler = new JsonHttpResponseHandler() {
                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        // mute this
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        syncTime(response);
                        WonderPush.setNetworkAvailable(true);
                        if (handler != null) {
                            handler.onSuccess(statusCode, new Response(response));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                        WonderPush.logError("Unexpected JSONArray answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + response.length() + ") " + response.toString());
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        WonderPush.logError("Error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: " + errorResponse);
                        syncTime(errorResponse);
                        WonderPush.logDebug("Request Error: " + errorResponse);
                        WonderPush.setNetworkAvailable(errorResponse != null);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(errorResponse));
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                        WonderPush.logError("Unexpected JSONArray error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + errorResponse.length() + ") " + errorResponse.toString());
                        this.onFailure(statusCode, headers, errorResponse.toString(), throwable);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        WonderPush.logError("Unexpected string error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                        WonderPush.setNetworkAvailable(false);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(responseString));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        WonderPush.logError("Unexpected string answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                    }

                    private void syncTime(JSONObject data) {
                        long recvDate = SystemClock.elapsedRealtime();
                        if (data == null || !data.has("_serverTime")) {
                            return;
                        }
                        TimeSync.syncTimeWithServer(sendDate, recvDate, data.optLong("_serverTime"), data.optLong("_serverTook"));
                    }
                };
                // NO UNNECESSARY WORK HERE, because of timed request
                switch (request.getMethod()) {
                    case GET:
                        sClient.get(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    case PUT:
                        sClient.put(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case POST:
                        sClient.post(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case PATCH:
                        sClient.patch(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case DELETE:
                        sClient.delete(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    default:
                        jsonHandler.sendFailureMessage(0, null, null, new UnsupportedOperationException("Unhandled method " + request.getMethod()));
                }
            }
        }, 0);
    }
1288393
Observable<ComapiResult<ConversationDetails>> doGetConversation(@NonNull final String token, @NonNull final String conversationId) {
        return wrapObservable(service.getConversation(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId).map(mapToComapiResult()), log, "Getting conversation" + conversationId);
    }
597226
@Override
	public Promise<HttpResponse> request(HttpRequest request) {
		assert eventloop.inEventloopThread();
		if (inspector != null) inspector.onRequest(request);
		String host = request.getUrl().getHost();

		assert host != null;

		return asyncDnsClient.resolve4(host)
				.thenEx((dnsResponse, e) -> {
					if (e == null) {
						if (inspector != null) inspector.onResolve(request, dnsResponse);
						if (dnsResponse.isSuccessful()) {
							//noinspection ConstantConditions - dnsResponse is successful (not null)
							return doSend(request, dnsResponse.getRecord().getIps());
						} else {
							return Promise.ofException(new DnsQueryException(AsyncHttpClient.class, dnsResponse));
						}
					} else {
						if (inspector != null) inspector.onResolveError(request, e);
						request.recycle();
						return Promise.ofException(e);
					}
				});
	}
932113
public ConversationMessage sendConversationMessage(
            final String conversationId,
            final ConversationMessageRequest request
    ) throws UnauthorizedException, GeneralException {
        String url = String.format(
                "%s%s/%s%s",
                CONVERSATIONS_BASE_URL,
                CONVERSATION_PATH,
                conversationId,
                CONVERSATION_MESSAGE_PATH
        );
        return messageBirdService.sendPayLoad(url, request, ConversationMessage.class);
    }
1361202
public Observable<ComapiResult<List<Participant>>> getParticipants(@NonNull final String conversationId) {

        final String token = getToken();

        if (sessionController.isCreatingSession()) {
            return getTaskQueue().queueGetParticipants(conversationId);
        } else if (TextUtils.isEmpty(token)) {
            return Observable.error(getSessionStateErrorDescription());
        } else {
            return doGetParticipants(token, conversationId);
        }
    }
1180597
Observable<ComapiResult<List<Participant>>> doGetParticipants(@NonNull final String token, @NonNull final String conversationId) {
        return wrapObservable(service.getParticipants(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId).map(mapToComapiResult()), log, "Getting participants for " + conversationId);
    }
510052
protected com.squareup.okhttp.Request buildHttpRequest(Request request)
    {
        RequestBody requestBody = null;
        if(request.getRequestMethod().isBodyRequest())
            requestBody = RequestBody.create(JSON, serializeBody(request));

        return new com.squareup.okhttp.Request.Builder()
                .url(buildUrl(request))
                .headers(getHeaders(request))
                .method(request.getRequestMethod().name(),requestBody)
                .build();
    }
278139
@Override
  public boolean service(RequestBaratine request)
  {
    /*
    try {
      _service.open((WebRequest) request);
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }
    */

    ServiceWebSocket<T, S> service = _factory.apply(request);

    WebSocketManager wsManager = request.webApp().wsManager();
    WebSocketBaratineImpl<T,S> ws
      = new WebSocketBaratineImpl<>(wsManager, service, _type);
    
    try {
      if (ws.handshake(request)) {
        return true;
      }
      else {
        log.fine("WebSocket handshake failed for " + request);
        return false;
      }
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      e.printStackTrace();
      
      request.fail(e);
      
      return true;
    }
    //request.flush();
  }
139377
Observable<List<ChatConversationBase>> loadAllConversations() {

        return Observable.create(emitter -> storeFactory.execute(new StoreTransaction<ChatStore>() {
            @Override
            protected void execute(ChatStore store) {
                store.open();
                List<ChatConversationBase> conversations = store.getAllConversations();
                store.close();
                emitter.onNext(conversations);
                emitter.onCompleted();
            }
        }), Emitter.BackpressureMode.LATEST);
    }
791087
public ListenableFuture<JsonRpcResponse> invoke(JsonRpcRequest request) {
    Service service = services.lookupByName(request.service());
    if (service == null) {
      JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST,
          "Unknown service: " + request.service());
      JsonRpcResponse response = JsonRpcResponse.error(error);
      return Futures.immediateFuture(response);
    }

    ServerMethod<? extends Message, ? extends Message> method = service.lookup(request.method());

    serverLogger.logMethodCall(service, method);

    if (method == null) {
      JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST,
          "Unknown method: " + request.service());
      JsonRpcResponse response = JsonRpcResponse.error(error);
      return Futures.immediateFuture(response);
    }

    return invoke(method, request.parameter(), request.id());
  }
1144676
private Observable<ChatResult> synchroniseConversations() {

        return checkState().flatMap(client -> client.service().messaging()
                .getConversations(false)
                .flatMap(result -> persistenceController.loadAllConversations()
                        .map(chatConversationBases -> compare(result.isSuccessful(), result.getResult(), chatConversationBases)))
                .flatMap(this::updateLocalConversationList)
                .flatMap(result -> lookForMissingEvents(client, result))
                .map(result -> new ChatResult(result.isSuccessful, null)));
    }
558689
public Observable<ComapiResult<MessageSentResponse>> sendMessage(@NonNull final String conversationId, @NonNull final MessageToSend message) {

        final String token = getToken();

        if (sessionController.isCreatingSession()) {
            return getTaskQueue().queueSendMessage(conversationId, message);
        } else if (TextUtils.isEmpty(token)) {
            return Observable.error(getSessionStateErrorDescription());
        } else {
            return doSendMessage(token, conversationId, message);
        }
    }
976919
@Override
	public void handleRequest(final Request request) {
		// Can only be an active DIALOG if it is AJAX targetted.
		if (isAjaxTargeted()) {
			if (getState() == INACTIVE_STATE) {
				handleTriggerOpenAction(request);
			}
			getOrCreateComponentModel().state = ACTIVE_STATE;
		} else if (getState() != INACTIVE_STATE) {
			getOrCreateComponentModel().state = INACTIVE_STATE;
		}
	}
69701
protected S createNewStatus(R request)
    {
        Job currentJob = this.jobContext.getCurrentJob();
        JobStatus currentJobStatus = currentJob != null ? currentJob.getStatus() : null;
        return (S) new DefaultJobStatus<R>(getType(), request, currentJobStatus, this.observationManager,
            this.loggerManager);
    }
626863
public HttpSession newHttpSession(HttpServletRequest request)
    {
        Session session = newSession(request);
        session.setMaxInactiveInterval(_dftMaxIdleSecs);
        synchronized(__allSessions)
        {
            synchronized(this)
            {
              _sessions.put(session.getId(),session);
              __allSessions.add(session.getId(), session);
              if (_sessions.size() > this._maxSessions)
                  this._maxSessions = _sessions.size ();
            }
        }
        
        HttpSessionEvent event=new HttpSessionEvent(session);
        
        for(int i=0;i<_sessionListeners.size();i++)
            ((HttpSessionListener)_sessionListeners.get(i))
            .sessionCreated(event);
        
        if (getCrossContextSessionIDs())
            request.setAttribute(__NEW_SESSION_ID, session.getId());
        return session;
    }