Creates a substitution function for query param values, such as
<code>@RequiresPermission("resource|update|{?id}")</code>
188339
private Function<HttpRequestContext, String> createQuerySubstitution(final String param) {
        return new Function<HttpRequestContext, String>() {
            @Override
            public String apply(HttpRequestContext request) {
                MultivaluedMap<String, String> params = request.getQueryParameters();
                if (!params.containsKey(param)) {
                    throw new IllegalStateException("Parameter required for authentication is missing: " + param);
                }
                List<String> values = params.get(param);
                if (values.size() != 1) {
                    throw new IllegalStateException("Exactly one parameter expected for authentication: " + param);
                }
                return values.get(0);
            }
        };
    }
1277701
protected String buildQuery(Properties parms, RequestType type) {
    if (parms.isEmpty())
      type = RequestType.query;
    RString result = new RString(_queryHtml);
    result.replace("REQ_NAME", this.getClass().getSimpleName());
    StringBuilder query = new StringBuilder();
    query.append("<form onsubmit='return false;'>");
    RString script = new RString(_queryJs);
    script.replace("REQUEST_NAME", getClass().getSimpleName());
    for (Argument arg: _arguments) {
      try {
        arg.check(RequestQueries.this, parms.getProperty(arg._name,""));
        queryArgumentValueSet(arg, parms);
      } catch( IllegalArgumentException e ) {
        // in query mode only display error for arguments present
        if ((type != RequestType.query) || !parms.getProperty(arg._name,"").isEmpty())
          query.append("<div class='alert alert-error'>"+e.getMessage()+"</div>");
      }
      if (arg._hideInQuery)
        continue;
      if (!arg.disabled()) {
        RString x = script.restartGroup("REQUEST_ELEMENT");
        x.replace("ELEMENT_NAME",arg._name);
        // If some Argument has prerequisites, and those pre-reqs changed on
        // this very page load then we do not assign the arg here: the values
        // passed will be something valid from the PRIOR page - based on the
        // old pre-req - and won't be correct.  Not assigning them here means
        // we'll act "as if" the field was never filled in.
        if( arg._prerequisites != null ) {
          StringBuilder sb = new StringBuilder("if( ");
          ArrayList<RequestArguments.Argument> preqs = arg._prerequisites;
          for( RequestArguments.Argument dep : preqs )
            sb.append("specArg!=='").append(dep._name).append("' && ");
          sb.append("true ) ");
          x.replace("ELEMENT_PREQ",sb);
        }
        x.append();
        x = script.restartGroup("ELEMENT_VALUE");
        x.replace("ELEMENT_NAME",arg._name);
        x.replace("BODY","function query_value_"+arg._name+"() { "+arg.jsValue()+"} ");
        x.append();
      }
      if (arg.refreshOnChange()) {
        RString x = script.restartGroup("ELEMENT_ONCHANGE");
        x.replace("BODY",arg.jsRefresh("query_refresh"));
        x.append();
      }
      RString x = script.restartGroup("ELEMENT_ADDONS");
      x.replace("BODY", arg.jsAddons());
      x.append();
    }
    for(Argument arg:_arguments){
      if (arg._hideInQuery)
        continue;
      query.append(arg.query());
    }
    query.append("</form>");
    result.replace("QUERY",query.toString());
    result.replace("SCRIPT",script.toString());
    return result.toString();
  }

}
340128
function(requiredPermissions) {
      if (requiredPermissions instanceof Array) {
        requiredPermissions = {
          all: requiredPermissions
        }
      } else if (typeof requiredPermissions !== 'object') {
        requiredPermissions = {
          all: [requiredPermissions]
        }
      }

      return function(req, res, next) {
        var user    = req.user
          , method  = req.method.toLowerCase()
          , id      = req.params.id
          , action  = req.params.action || id;

        if (!!id && !!action && action === 'list') {
          action = 'get'
          req.params.action = 'get';
        } else if (!action && method === 'get' && /^\/.*\/(.*\/?)$/ig.test(req.url)) {
          action = 'list';
        } else if (/^[0-9a-fA-F]{24}$/.test(action) || !isNaN(action)) {
          action = 'get';
        } else {
          if (req.params.action) {
            action = req.params.action;
          } else if (method === 'get' && !id) {
            action = 'list';
          } else {
            action = method;
          }
        }

        async.waterfall(
          [

            function determinePermissions(callback) {
              var actionName = (!!action ? action : method) + 'Action'
                , permissions = [];
              
              if (typeof requiredPermissions[actionName] !== 'undefined') {
                if (requiredPermissions[actionName] !== null) {
                  if (requiredPermissions[actionName] instanceof Array) {
                    permissions = permissions.concat(requiredPermissions[actionName]);
                  } else {
                    permissions.push(requiredPermissions[actionName]);
                  }
                }
              } else if (typeof requiredPermissions.all !== 'undefined') {
                if (requiredPermissions.all !== null) {
                  permissions = requiredPermissions.all instanceof Array ? requiredPermissions.all : [requiredPermissions.all];
                }
              }

              callback(null, permissions);
            },

            function userRoleHasPermission(permissions, callback) {
              var hasPermission = true;

              if (!!permissions.length && !req.isAuthenticated()) {
                return callback('User is not authenticated!');
              }

              permissions.every(function(requiredPermission) {
                if (/^([^\$]+)\.\$action/.test(requiredPermission)) {
                  requiredPermission = RegExp.$1 + '.';

                  switch(action) {
                  
                  case 'get':
                    requiredPermission += 'view';
                    break;
                  case 'post':
                    requiredPermission += 'create';
                    break;
                  case 'put':
                    requiredPermission += 'edit';
                    break;
                  default:
                    requiredPermission += action;
                    break;
                  }
                }

                if (requiredPermission !== 'requiresLogin' && _.findWhere([].slice.call(user.Role.Permissions), { action: requiredPermission }) === undefined) {
                  callback('Logged in user does not have ' + requiredPermission + ' permission.');
                  hasPermission = false;
                  return false;
                }
                return true;
              });

              if (!!hasPermission) {
                callback(null);
              }
            }
          ],
          function(err) {
            if (err === null) {
              next();
            } else {
              console.dir(err);
              res.send(401, { statusCode: 401, message: err });
            }
          }

       );
      }
    }
818
function filterOutOptionalQueryParams(data) {
  data.queryParameters = data.queryParameters.filter(function(queryParam) {
    // Let's be conservative and treat params without explicit required field as not-optional
    var optional = queryParam.required !== undefined && !queryParam.required;
    var dataProvided = data.requestParameters.hasOwnProperty(queryParam.name);

    return !optional || dataProvided;
  });
  return data;
}
596780
function replace(searchValue, replaceValue) {
        var O = requireObjectCoercible(this);
        var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
        return replacer !== undefined
          ? replacer.call(searchValue, O, replaceValue)
          : nativeReplace.call(String(O), searchValue, replaceValue);
      }
1138840
function(params) {

                corbel.validate.value('id', this.id);

                var options = params ? corbel.utils.clone(params) : {};

                var args = corbel.utils.extend(options, {
                    url: this._buildUriWithDomain(this.id),
                    method: corbel.request.method.GET,
                    query: params ? corbel.utils.serializeParams(params) : null
                });

                return this.request(args);

            }
1057318
protected String substituteParametersInTemplate(final FunctionTemplate template, final Map<String, String> params) {
        String ret = template.getFiles().get("function.java");
        for (final Map.Entry<String, String> entry : params.entrySet()) {
            ret = ret.replace(String.format("$%s$", entry.getKey()), entry.getValue());
        }
        return ret;
    }
669959
private void appendParameter(Object value, StringBuffer buf)
    {
        if (value instanceof Query)
        {
            appendSubQuery((Query) value, buf);
        }
        else
        {
            buf.append("?");
        }
    }
242523
public void addQueryParam( String paramName, String value )
    {
        if ( _queryString == null )
        {
            _queryString = new InternalStringBuilder( "?" );
        }
        else
        {
            _queryString.append( '&' );
        }
        
        _queryString.append( paramName );
        
        if ( value != null )
        {
            _queryString.append( '=' ).append( value );
        }
    }
1052605
def _substitute(self, query, model_class=None):
        '''
        
        '''
        if '$' in query:
            mapping = dict(db="`%s`" % self.db_name)
            if model_class:
                mapping['table'] = "`%s`.`%s`" % (self.db_name, model_class.table_name())
            query = Template(query).safe_substitute(mapping)
        return query
219827
public Query addQueryUrlParams(String key, String value) {
    this.queryUrlParams.put(key, value);
    return this;
  }
662903
function toQueryString(params, id) {
    var paramsString = '';
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        paramsString += '&' + key + '=' + encodeURIComponent(params[key]);
      }
    }
    return 'zws-id=' + id + paramsString;
  }
318203
@API(status = EXPERIMENTAL)
    public static BodyFilter replaceFormUrlEncodedProperty(final Set<String> properties, final String replacement) {
        final Predicate<String> formUrlEncoded = MediaTypeQuery.compile("application/x-www-form-urlencoded");

        final QueryFilter delegate = properties.stream()
                .map(name -> QueryFilters.replaceQuery(name, replacement))
                .reduce(QueryFilter::merge)
                .orElseGet(QueryFilter::none);

        return (contentType, body) -> formUrlEncoded.test(contentType) ? delegate.filter(body) : body;
    }
753919
public static function replaceQueryParamInUrl($param, $value, $url)
    {
        $parsedUrl = self::parseUrl($url);
        $queryString = isset($parsedUrl['query']) ? $parsedUrl['query'] : '';
        $queryString = self::replaceQueryParam($param, $value, $queryString);
        $parsedUrl['query'] = $queryString;
        return self::buildUrl($parsedUrl);
    }
1089570
public URIBuilder queryParam(String name, String value) {
		parameters.add(name, value);
		return this;
	}
551213
public URIBuilder addParameter(final String param, final String value) {
        if (this.queryParams == null) {
            this.queryParams = new ArrayList<NameValuePair>();
        }
        this.queryParams.add(new BasicNameValuePair(param, value));
        this.encodedQuery = null;
        this.encodedSchemeSpecificPart = null;
        return this;
    }
1308963
function (requestV1) {
        var queryParams = [],
            pathVariables = [],
            traversedVars = {},
            queryParamAltered,
            traversedQueryParams = {},
            parsed = util.urlparse(requestV1.url),
            retainEmpty = this.options.retainEmptyValues;

        // Merge query params
        _.forEach(requestV1.queryParams, function (queryParam) {
            (queryParam.enabled === false) && (queryParam.disabled = true);

            delete queryParam.enabled;

            util.cleanEmptyValue(queryParam, 'description', retainEmpty);

            if (_.has(queryParam, 'equals')) {
                if (queryParam.equals) {
                    (queryParam.value === null) && (queryParam.value = '');
                    queryParamAltered = true;
                }
                else {
                    // = is not appended when the value is null
                    (queryParam.value === '') && (queryParam.value = null);
                    queryParamAltered = true;
                }
                delete queryParam.equals;
            }

            queryParams.push(queryParam);
            traversedQueryParams[queryParam.key] = true;
        });
        // parsed query params are taken from the url, so no descriptions are available from them
        _.forEach(parsed.query, function (queryParam) {
            !traversedQueryParams[queryParam.key] && queryParams.push(queryParam);
        });

        // Merge path variables
        _.forEach(requestV1.pathVariableData, function (pathVariable) {
            pathVariable = _.clone(pathVariable);
            util.cleanEmptyValue(pathVariable, 'description', retainEmpty);

            pathVariables.push(pathVariable);
            traversedVars[pathVariable.key] = true;
        });
        // pathVariables in v1 are of the form  {foo: bar}, so no descriptions can be obtained from them
        _.forEach(requestV1.pathVariables, function (value, id) {
            !traversedVars[id] && pathVariables.push({
                value: value,
                id: id
            });
        });

        !_.isEmpty(queryParams) && (parsed.query = queryParams);
        !_.isEmpty(pathVariables) && (parsed.variable = pathVariables);

        // If the query params have been altered, update the raw stringified URL
        queryParamAltered && (parsed.raw = util.urlunparse(parsed));

        // return the objectified URL only if query param or path variable descriptions are present, string otherwise
        return (parsed.query || parsed.variable) ? parsed : (parsed.raw || requestV1.url);
    }