****************************** Internal methods ****************************** 
Search for states... use $timeout to simulate
remote dataservice call.
16896
function querySearch (query) {
      return query ? self.states.filter(createFilterFor(query)) : self.states;
    }
52544
private void parsePersistTimeout(Map<Object, Object> props) {
        Object value = props.get(HttpConfigConstants.PROPNAME_PERSIST_TIMEOUT);
        if (null != value) {
            try {
                this.persistTimeout = TIMEOUT_MODIFIER * minLimit(convertInteger(value), HttpConfigConstants.MIN_TIMEOUT);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Config: Persist timeout is " + getPersistTimeout());
                }
            } catch (NumberFormatException nfe) {
                FFDCFilter.processException(nfe, getClass().getName() + ".parsePersistTimeout", "1");
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Config: Invalid persist timeout; " + value);
                }
            }
        }
    }
847959
@Override
  public InetSocketAddress lookup(final Identifier id) throws Exception {

    return cache.get(id, new Callable<InetSocketAddress>() {

      @Override
      public InetSocketAddress call() throws Exception {
        final int origRetryCount = NameLookupClient.this.retryCount;
        int retriesLeft = origRetryCount;
        while (true) {
          try {
            return remoteLookup(id);
          } catch (final NamingException e) {
            if (retriesLeft <= 0) {
              throw e;
            } else {
              final int currentRetryTimeout = NameLookupClient.this.retryTimeout
                  * (origRetryCount - retriesLeft + 1);
              LOG.log(Level.WARNING,
                  "Caught Naming Exception while looking up " + id
                      + " with Name Server. Will retry " + retriesLeft
                      + " time(s) after waiting for " + currentRetryTimeout + " msec.");
              Thread.sleep(currentRetryTimeout);
              --retriesLeft;
            }
          }
        }
      }

    });
  }
694523
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    WorkflowRequestServiceInterface workflowRequestService =
        adManagerServices.get(session, WorkflowRequestServiceInterface.class);

    // Create a statement to select workflow requests.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("type = :type")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("type", WorkflowRequestType.WORKFLOW_APPROVAL_REQUEST.toString());

    // Retrieve a small amount of workflow requests at a time, paging through
    // until all workflow requests have been retrieved.
    int totalResultSetSize = 0;
    do {
      WorkflowRequestPage page =
          workflowRequestService.getWorkflowRequestsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each workflow request.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (WorkflowRequest workflowRequest : page.getResults()) {
          System.out.printf(
              "%d) Workflow request with ID %d, entity type '%s', and entity ID %d was found.%n",
              i++,
              workflowRequest.getId(),
              workflowRequest.getEntityType(),
              workflowRequest.getEntityId()
          );
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
281275
function(input, callback, context, remoteData)
  {
    var db = this;
    var promise = new Promise();

    promise.success( callback, context || db );

    function checkModel()
    {
      var result = db.parseModel( input, remoteData );

      if ( result !== false && !promise.isComplete() && db.initialized )
      {
        var remoteLoaded = db.remoteLoaded || !db.hasLoad( Load.All );
        var missingModel = (result === null || !result.$isSaved());
        var lazyLoad = db.hasLoad( Load.Lazy );

        if ( lazyLoad && remoteLoaded && missingModel )
        {
          if ( !result )
          {
            result = db.keyHandler.buildObjectFromKey( db.keyHandler.buildKeyFromInput( input ) );
          }

          result.$once( Model.Events.RemoteGets, function()
          {
            if ( !promise.isComplete() )
            {
              if ( isObject( input ) )
              {
                result.$set( input );
              }

              promise.resolve( result.$isSaved() ? result : null );
            }
          });

          result.$refresh( Cascade.All, db.fetchOptions );
        }
        else
        {
          promise.resolve( result );
        }
      }

      return promise.isComplete() ? false : true;
    }

    if ( checkModel() )
    {
      db.ready( checkModel, db, true );
    }

    return promise;
  }
596486
@Override
    public String invoke(Object conn, String request, int timeout, Map<String, String> headers)
    throws ConnectionException, AdapterException {
        Exception savedException = null;
        int connectTimeout = -1;
        int readTimeout = -1;
        String httpMethod = null;
        StringBuffer sb = new StringBuffer();

        sb.append("<RESTResponseList>");

        for (Object connObj : getConnectionObjs()) {
            HttpHelper  httpHelper = null;
            try {
                sb.append("\r\n<RESTResponse uri=\"" + ((HttpURLConnection)connObj).getURL().toString() + "\">\r\n");

                httpHelper = getHttpHelper(connObj);

                connectTimeout = connectTimeout < 0 ? getConnectTimeout() : connectTimeout;
                if (connectTimeout > 0)
                    httpHelper.setConnectTimeout(connectTimeout);

                readTimeout = readTimeout < 0 ? getReadTimeout() : readTimeout;
                if (readTimeout > 0)
                    httpHelper.setReadTimeout(readTimeout);

                if (headers != null)
                    httpHelper.setHeaders(headers);

                if (httpMethod == null)
                    httpMethod = getHttpMethod();

                if (httpMethod.equals("GET"))
                    sb.append(httpHelper.get());
                else if (httpMethod.equals("POST"))
                    sb.append(httpHelper.post(request));
                else if (httpMethod.equals("PUT"))
                    sb.append(httpHelper.put(request));
                else if (httpMethod.equals("DELETE"))
                    sb.append(httpHelper.delete());
                else if (httpMethod.equals("PATCH"))
                    sb.append(httpHelper.patch(request));
                else
                    throw new AdapterException("Unsupported HTTP Method: " + httpMethod);
            }
            catch (IOException ex) {
                if (httpHelper != null && httpHelper.getResponse() != null)
                    sb.append(httpHelper.getResponse());
                /**
                 * Plugs into automatic retrying
                 */
                logexception(ex.getMessage(), ex);
                savedException = ex;
            }
            catch (Exception ex) {
                int responseCode = -1;
                if (httpHelper != null)
                    responseCode = httpHelper.getResponseCode();
                throw new AdapterException(responseCode, ex.getMessage() , ex);
            }
            finally {
                sb.append("\r\n</RESTResponse>");
                if (httpHelper != null)
                    setResponseHeaders(httpHelper.getHeaders());
            }
        }
        sb.append("\r\n</RESTResponseList>");
        if (savedException != null) {
            logResponse(new Response(sb.toString()));
            throw new ConnectionException(-1, savedException.getMessage(), savedException);
        }

        return sb.toString();
    }
638810
public void setQueryTimeoutMs(long millis) throws SQLException {
    checkClosed();

    if (millis < 0) {
      throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."),
          PSQLState.INVALID_PARAMETER_VALUE);
    }
    timeout = millis;
  }
76927
function rootSearch(args) {
		
		// get the datacenters
		return _client.retrieve({
			type: 'Datacenter',
			properties: ['name', 'datastoreFolder', 'hostFolder', 'networkFolder', 'vmFolder']
		})
		.then(function(dcs) {

			// look through each of the dcs and map the return values
			return Promise.map(dcs, function(dc) {
				
				var folderId;
				
				// get the correct folder id to start search from or if searching
				if (args.type === 'Datastore') {
					folderId = dc.datastoreFolder;
				}
				else if (args.type === 'HostSystem') {
					folderId = dc.hostFolder;
				}
				else if (args.type === 'Network') {
					folderId = dc.networkFolder;
				}
				else if (args.type === 'VirtualMachine') {
					folderId = dc.vmFolder;
				}
				
				// return the entity details
				return {
					type: 'Folder',
					id: folderId
				};
			});
		});
	}
211541
function(input) {
  var code = 'var $_isidentifier = ' + $_isidentifier.toString() + ';\n' +
    // FIXME: could we remove that eval?
    'eval((' + literaltovar.toString() + ')($_scope));\n';
  code += 'var $_parsers = {\n';
  var parsernames = Object.keys(parsers);
  for (var i = 0; i < parsernames.length; i++) {
    code += '  ' + JSON.stringify(parsernames[i]) + ': ' +
      parsers[parsernames[i]].toString() + ',\n';
  };
  code += '}\n';
  code += 'var $_written = "";\n' +
          'var $_write = function(data) { $_written += data; };\n';
  code += compile(input);
  code += '$_written\n';
  return function($_write, $_scope, timeout, cb) {
    var res;
    try {
      res = vm.runInNewContext(code, {$_scope: $_scope},
          {timeout: timeout || 1000});
    } catch(err) {
      console.error(err); $_write('');
      if (cb) { cb(err); }
      return;
    }
    $_write(res);
    if (cb) { cb(null); }
  };
}
383739
function _try_multicall($msgs, $timeout, $method)
		{
			// Construct multicall message
			$calls = array();
			foreach($msgs as $msg)
			{
				$call['methodName'] = new xmlrpcval($msg->method(),'string');
				$numParams = $msg->getNumParams();
				$params = array();
				for($i = 0; $i < $numParams; $i++)
				{
					$params[$i] = $msg->getParam($i);
				}
				$call['params'] = new xmlrpcval($params, 'array');
				$calls[] = new xmlrpcval($call, 'struct');
			}
			$multicall = new xmlrpcmsg('system.multicall');
			$multicall->addParam(new xmlrpcval($calls, 'array'));

			// Attempt RPC call
			$result =& $this->send($multicall, $timeout, $method);

			if($result->faultCode() != 0)
			{
				// call to system.multicall failed
				return $result;
			}

			// Unpack responses.
			$rets = $result->value();

			if ($this->return_type == 'xml')
			{
					return $rets;
			}
			else if ($this->return_type == 'phpvals')
			{
				///@todo test this code branch...
				$rets = $result->value();
				if(!is_array($rets))
				{
					return false;		// bad return type from system.multicall
				}
				$numRets = count($rets);
				if($numRets != count($msgs))
				{
					return false;		// wrong number of return values.
				}

				$response = array();
				for($i = 0; $i < $numRets; $i++)
				{
					$val = $rets[$i];
					if (!is_array($val)) {
						return false;
					}
					switch(count($val))
					{
						case 1:
							if(!isset($val[0]))
							{
								return false;		// Bad value
							}
							// Normal return value
							$response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');
							break;
						case 2:
							///	@todo remove usage of @: it is apparently quite slow
							$code = @$val['faultCode'];
							if(!is_int($code))
							{
								return false;
							}
							$str = @$val['faultString'];
							if(!is_string($str))
							{
								return false;
							}
							$response[$i] = new xmlrpcresp(0, $code, $str);
							break;
						default:
							return false;
					}
				}
				return $response;
			}
			else // return type == 'xmlrpcvals'
			{
				$rets = $result->value();
				if($rets->kindOf() != 'array')
				{
					return false;		// bad return type from system.multicall
				}
				$numRets = $rets->arraysize();
				if($numRets != count($msgs))
				{
					return false;		// wrong number of return values.
				}

				$response = array();
				for($i = 0; $i < $numRets; $i++)
				{
					$val = $rets->arraymem($i);
					switch($val->kindOf())
					{
						case 'array':
							if($val->arraysize() != 1)
							{
								return false;		// Bad value
							}
							// Normal return value
							$response[$i] = new xmlrpcresp($val->arraymem(0));
							break;
						case 'struct':
							$code = $val->structmem('faultCode');
							if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
							{
								return false;
							}
							$str = $val->structmem('faultString');
							if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
							{
								return false;
							}
							$response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
							break;
						default:
							return false;
					}
				}
				return $response;
			}
		}
950720
function ldapQuery($scope, $params) {

    $this->connectAndBindIfNotAlready();

    switch ($scope) {
      case LDAP_SCOPE_SUBTREE:
        $result = @ldap_search($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not return result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_search() function error. LDAP Error: %message, ldap_search() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
            WATCHDOG_ERROR);
        }
        break;

      case LDAP_SCOPE_BASE:
        $result = @ldap_read($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_read() function error.  LDAP Error: %message, ldap_read() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => @$params['query_display']),
            WATCHDOG_ERROR);
        }
        break;

      case LDAP_SCOPE_ONELEVEL:
        $result = @ldap_list($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_list() function error. LDAP Error: %message, ldap_list() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
            WATCHDOG_ERROR);
        }
        break;
    }
    return $result;
  }
302353
public void doProcess(InputStream in, PrintWriter out, Map<String, Object> properties)
        throws RemoteException
    {
        String strCommand = this.getProperty(REMOTE_COMMAND, properties);
        if (MAKE_REMOTE_TABLE.equals(strCommand))
        {
            String strRecordClassName = this.getNextStringParam(in, NAME, properties);
            String strTableSessionClassName = this.getNextStringParam(in, SESSION_CLASS_NAME, properties);
            Map<String,Object> propIn = this.getNextPropertiesParam(in, PROPERTIES, properties);
            Map<String,Object> propDatabase = this.getNextPropertiesParam(in, PROPERTIES_DB, properties);
            if (propIn != null)
                properties.putAll(propIn);
            RemoteTable remoteTable = ((RemoteTask)m_remoteObject).makeRemoteTable(strRecordClassName, strTableSessionClassName, properties, propDatabase);
            String strTableID = this.add(new TableHolder(this, remoteTable));
            this.setReturnString(out, strTableID);
        }
        else if (CREATE_REMOTE_TASK.equals(strCommand))
        {   // Note: I am not the parent, the proxyTask (the application task) is.
            Map<String,Object> propIn = this.getNextPropertiesParam(in, PROPERTIES, properties);
            if (propIn != null)
                properties.putAll(propIn);
            Application app = ((TaskSession)this.getRemoteObject()).getApplication();
            RemoteTask remoteTask = m_proxyTask.getNewRemoteTask(app, properties);  // Parent is MY APPLICATION not ME.
            String strUniqueID = m_proxyTask.add(new TaskHolder(m_proxyTask, remoteTask));  // Parent is Parent Proxy not ME.
            out.write(strUniqueID);
        }
        else if (CREATE_REMOTE_RECEIVE_QUEUE.equals(strCommand))
        {
            String strQueueName = this.getNextStringParam(in, MessageConstants.QUEUE_NAME, properties);
            String strQueueType = this.getNextStringParam(in, MessageConstants.QUEUE_TYPE, properties);
            RemoteReceiveQueue remoteReceiveQueue = ((RemoteTask)m_remoteObject).createRemoteReceiveQueue(strQueueName, strQueueType);
            String strID = this.find(remoteReceiveQueue);
            if (strID == null)
                strID = this.add(new ReceiveQueueHolder(this, remoteReceiveQueue));
            this.setReturnString(out, strID);
        }
        else if (CREATE_REMOTE_SEND_QUEUE.equals(strCommand))
        {
            String strQueueName = this.getNextStringParam(in, MessageConstants.QUEUE_NAME, properties);
            String strQueueType = this.getNextStringParam(in, MessageConstants.QUEUE_TYPE, properties);
            RemoteSendQueue remoteSendQueue = ((RemoteTask)m_remoteObject).createRemoteSendQueue(strQueueName, strQueueType);
            String strID = this.find(remoteSendQueue);
            if (strID == null)
                strID = this.add(new SendQueueHolder(this, remoteSendQueue));
            this.setReturnString(out, strID);
        }
        else if (SET_REMOTE_MESSAGE_TASK.equals(strCommand))
        {
            String strTaskID = this.getNextStringParam(in, ID, properties);
            BaseHolder sessionHolder = this.getSessionFromPath(strTaskID);
            if (sessionHolder instanceof TaskHolder)
            {       // Always
                RemoteTask remoteTask = (RemoteTask)sessionHolder.getRemoteObject();
                ((RemoteTask)m_remoteObject).setRemoteMessageTask(remoteTask);
            }
            else
                Utility.getLogger().warning("Remote session not found");
        }
        else if (LOGIN.equals(strCommand))
        {
            String strUserName = this.getNextStringParam(in, Params.USER_NAME, properties);
            String strPassword = this.getNextStringParam(in, Params.PASSWORD, properties);
            String strDomain = this.getNextStringParam(in, Params.DOMAIN, properties);
            Map<String,Object> mapLoginInfo = ((RemoteTask)m_remoteObject).login(strUserName, strPassword, strDomain);
            // First, see if this is in my list already?
            this.setReturnObject(out, mapLoginInfo);
        }
        else
            super.doProcess(in, out, properties);
    }
1050171
@Override
  public boolean isValid(int timeout) throws SQLException {

    int initialTimeout = -1;
    try {
      initialTimeout = socket.getSoTimeout();
      if (initialTimeout == 0) {
        socket.setSoTimeout(timeout);
      }
      if (isMasterConnection() && !galeraAllowedStates.isEmpty()) {
        //this is a galera node.
        //checking not only that node is responding, but that galera state is allowed.
        Results results = new Results();
        executeQuery(true, results, CHECK_GALERA_STATE_QUERY);
        results.commandEnd();
        ResultSet rs = results.getResultSet();

        return rs != null && rs.next() && galeraAllowedStates.contains(rs.getString(2));
      }

      return ping();

    } catch (SocketException socketException) {
      logger.trace("Connection is not valid", socketException);
      connected = false;
      return false;
    } finally {

      //set back initial socket timeout
      try {
        if (initialTimeout != -1) {
          socket.setSoTimeout(initialTimeout);
        }
      } catch (SocketException socketException) {
        logger.warn("Could not set socket timeout back to " + initialTimeout, socketException);
        connected = false;
        //eat
      }
    }
  }
300318
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    ProposalServiceInterface proposalService =
        adManagerServices.get(session, ProposalServiceInterface.class);

    // Create a statement to select proposals.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("status = :status")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("status", ProposalStatus.PENDING_APPROVAL.toString());

    // Retrieve a small amount of proposals at a time, paging through
    // until all proposals have been retrieved.
    int totalResultSetSize = 0;
    do {
      ProposalPage page =
          proposalService.getProposalsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each proposal.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Proposal proposal : page.getResults()) {
          System.out.printf(
              "%d) Proposal with ID %d and name '%s' was found.%n",
              i++,
              proposal.getId(),
              proposal.getName()
          );
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
43897
@SuppressWarnings( "unchecked" )
    public <T> T getService( final Class<T> serviceType,
                             final long timeoutInMillis )
    {
        return (T) Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class<?>[]{ serviceType },
            new InvocationHandler()
            {
                /**
                 * {@inheritDoc}
                 * Delegates the call to remote bundle context.
                 */
                public Object invoke( final Object proxy,
                                      final Method method,
                                      final Object[] params )
                    throws Throwable
                {
                    try
                    {
                        return getRemoteBundleContext().remoteCall(
                            method.getDeclaringClass(),
                            method.getName(),
                            method.getParameterTypes(),
                            timeoutInMillis,
                            params
                        );
                    }
                    catch( InvocationTargetException e )
                    {
                        throw e.getCause();
                    }
                    catch( RemoteException e )
                    {
                        throw new TestContainerException( "Remote exception", e );
                    }
                    catch( Exception e )
                    {
                        throw new TestContainerException( "Invocation exception", e );
                    }
                }
            }
        );
    }
338610
@Override
  public void onNext(final T event) {
    if (LOG.isLoggable(Level.FINE)) {
      LOG.log(Level.FINE, "remoteid: {0}\n{1}", new Object[]{remoteId.getSocketAddress(), event.toString()});
    }
    handler.onNext(new RemoteEvent<T>(myId.getSocketAddress(), remoteId.getSocketAddress(),
        seqGen.getNextSeq(remoteId.getSocketAddress()), event));
  }
138770
void timeout() {
    long time = System.currentTimeMillis();
    Iterator<Map.Entry<Long, ContextualFuture>> iterator = responseFutures.entrySet().iterator();
    while (iterator.hasNext()) {
      ContextualFuture future = iterator.next().getValue();
      if (future.time + requestTimeout < time) {
        iterator.remove();
        future.context.executor().execute(() -> future.completeExceptionally(new TimeoutException("request timed out")));
      } else {
        break;
      }
    }
  }