Postpath needs to contain all segments of
        the url, if it is incomplete then that incomplete url will be passed on
        to the child resource (in this case our wsgi application).
345231
def getChild(self, name, request):
        
        request.prepath = []
        request.postpath.insert(0, name)
        # re-establishes request.postpath so to contain the entire path
        return self.wsgi_resource
980653
def check_path_consistency(self, resource):
        ''''''
        msg = ('Method "{}" path variables {}) do not conform with the '
               'resource subpath declaration ({}).')
        errors = []
        # If subpath is not set, it will be detected by another checker
        if resource.subpath is None:
            return errors
        declared = sorted(self.path_params_regex.findall(resource.subpath))
        for callback in resource.callbacks:
            actual = sorted(utils.filter_annotations_by_ptype(
                callback, Ptypes.path))
            if declared == actual:
                continue
            errors.append(msg.format(
                '{}.{}'.format(resource.__name__, callback.__name__),
                actual, resource.subpath))
        return errors
276123
function validPath(path, site) {
  let reservedRoute;

  if (path[0] !== '/') {
    log('warn', `Cannot attach route '${path}' for site ${site.slug}. Path must begin with a slash.`);
    return false;
  }

  reservedRoute = _.find(reservedRoutes, (route) => path.indexOf(route) === 1);

  if (reservedRoute) {
    log('warn', `Cannot attach route '${path}' for site ${site.slug}. Route prefix /${reservedRoute} is reserved by Amphora.`);
    return false;
  }

  return true;
}
1210750
function process_post(request, response, uri, body) {
	if (!authorised(request))
		return fail(401, "unauthorized", response);

	// be safe
	if (body === undefined)
		body = null;
		
	let path = URL.parse(request.url).pathname;

	// does path start with /things/thingID for some thingID?

	if (/^\/things\/.+/.test(path)) {
		path = path.substr(8);
		
		let i = path.indexOf('/');
		var thingID;
		
		if (i < 0) {
			thingID = path;
			path = "";
		} else {
			thingID = path.substr(0, i);
			path = path.substr(i);
		}
		
		if (thingID) {
			let thing = things[thingID];
			
			if (!thing)
				return fail(404, "unknown thing: " + thingID, response);
				
			// /things/thingID/properties to update all properties
			// /things/thingID/properties/propName to update given property
			
			if (path === "/properties") {
				// update properties from request body
				
				try {
					let values = JSON.parse(body);
					if (typeof values != 'object')
						return fail(555, "invalid data", response);
					
					// fail if any of the values are invalid or readonly
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property === undefined)
								return fail(404, "unknown property name: " + name, response);

							if (property.meta) {
								if (property.meta.writable !== undefined  && !property.meta.writable)
									return fail(405, "read-only", response);
							
								if (invalid(value, property.meta, thing))
									return fail(400, "invalid data", response);
							}							
						}
					}
					
					// all values are good so update and notify
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property != undefined) {
								property.value = value;
								
								// notify exposing app of external change
								if (property.handler)
									property.handler(value);
							}
						}
					}
					
					thing.emitState(values); // notify all clients
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					return succeed(204, "no data", response);
				} catch (err) {
					return fail(404, "invalid: " + body, response);
				}
			} else if (/^\/properties\/.+/.test(path)) {
				path = path.substr(12);
				console.log("property name: " + path);
				let property = thing.properties[path];
				
				if (property === undefined)
					return fail(404, "unknown property: " + path, response);
					
				console.log('parsing request body');
					
				// update named property from request body
				try {
					let value = JSON.parse(body);
					
					if (property.meta) {
						if (property.meta.writable !== undefined  && !property.meta.writable)
							return fail(405, "read-only", response);

						if (invalid(value, property.meta, thing)) {
							console.log('failed to set ' + path + ' to ' + value);
							return fail(400, "invalid data", response);
						}
					}

					property.value = value;
					
					// notify exposing app of external change
					if (property.handler)
						property.handler(value);
									
					console.log('setting ' + property.name + ' to ' + value);
					console.log('calling emitValue with path = ' + path + ' and value = ' + value);
					thing.emitValue(path, value);
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					console.log('succeeded in setting ' + property.name + ' to ' + property.value);
					return succeed(204, "no data", response);
				} catch (err) {
					console.log('failed to parse request body');
					return fail(404, "invalid: " + body, response);
				}
			}
			
			// /things/thingID/actions/actName to invoke given action (POST only)
			
			if (/^\/actions\/.+/.test(path)) {
				path = path.substr(9);
				//console.log("action name: " + path);
				
				let action = thing.actions[path];
				
				if (action === undefined)
					return fail(404, "unknown action: " + path, response);
					
				// *** need to validate input data against model's data type
				let input = null;
				
				//console.log(" input body is: " + JSON.stringify(body));
				
				if (body !== undefined) {
					try {
						input = JSON.parse(body);
					} catch (err) {
						return fail(404, "invalid: " + body, response);
					}
				}
				
				if (action.meta && action.meta.input && invalid(input, action.meta.input, thing))
					return fail(400, "invalid input", response);
					
				if (action.handler === undefined) {
					// succeed immediately as nothing to be done
					console.log('action ' + action.name + ' has no handler');
					return succeed(204, "no data", response);
				} else {
					//console.log('ready to invoke handler for action ' + action.name);
					// invoke handler and use promise to deliver response
					// after testing response against model's data type
					action.handler(input).then(output => {
						if (action.meta && action.meta.output && invalid(output, action.meta.output, thing)) {
							console.log(output + ' is invalid');
							return fail(400, "invalid output", response);
						}
						let body = JSON.stringify(output, null, 4);
						
						console.log('output body is ' + body);
						
						if (body === undefined) {
							console.log('body is undefined');
							response.writeHead(204, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*'
							});
						} else {
							response.writeHead(200, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*',
								'Content-Length': body.length
							});
							response.write(body);
						}
						
						response.end();
						return;
					}).catch(err => {
						console.log('handler failed: ' + err);
						return fail(500, "action failed: " + err, response);
					});
					
					return;  // deferred response
				}
			}
		}
		
		return fail(404, "missing thingID: " + uri.path, response);
	}
}
747744
def join_url_parts(*args):
    
    # check for edge case
    if len(args) == 1:
        return args[0]

    return_val = clean_url_segment(args[0])

    for i in range(1, len(args)):
        arg = args[i]

        if i == len(args) - 1:
            # no need to remove a trailing slash if this is the last segment
            return_val += '/' + arg
        else:
            # remove a trailing slash so it won't be duplicated
            return_val += '/' + clean_url_segment(arg)

    return return_val
1163347
@OverrideOnDemand
  protected boolean linkNeedsContextPath (@Nullable final String sHref)
  {
    if (sHref == null)
      return false;

    // If prefix is defined and already present no need to change something
    // Or if the server prefix path is just "/" and the links starts with "/"
    // it's also fine
    if (sHref.startsWith (m_sServerPrefixPath))
      return false;

    // javascript: and mailto: are handled by URLProtocolRegistry
    if (URLProtocolRegistry.getInstance ().hasKnownProtocol (sHref) || sHref.startsWith ("#"))
      return false;

    // Prefix is needed
    return true;
  }
301610
def post_query(path, data = {})
      @request_uri = "#{@base_uri}#{path}" 
      body = URI.encode_www_form(data)
      extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' }
      req  = post_request(path, body, extheader)
      @res = http_connection.start {|http| http.request(req) }
      handle_error(@res, @request_uri)
      JSON.parse(@res.body)
    end
725561
def url_should_contain(self, url):
    """"""

    if url not in world.browser.current_url:
        raise AssertionError(
            "Browser URL expected to contain {!r}, got {!r}.".format(
                url, world.browser.current_url))
1079707
public static List<Resource> parsePath(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException {

		final String path = request.getPathInfo();

		// intercept empty path and send 204 No Content
		if (StringUtils.isBlank(path)) {

			throw new NoResultsException("No content");
		}

		// 1.: split request path into URI parts
		final String[] pathParts = path.split("[/]+");

		// 2.: create container for resource constraints
		final Set<String> propertyViews    = Services.getInstance().getConfigurationProvider().getPropertyViews();
		final List<Resource> resourceChain = new ArrayList<>(pathParts.length);

		// 3.: try to assign resource constraints for each URI part
		for (int i = 0; i < pathParts.length; i++) {

			// eliminate empty strings
			final String part = pathParts[i].trim();

			if (part.length() > 0) {

				boolean found = false;

				// check views first
				if (propertyViews.contains(part)) {

					Resource resource = new ViewFilterResource();
					resource.checkAndConfigure(part, securityContext, request);
					resource.configurePropertyView(propertyView);

					resourceChain.add(resource);

					// mark this part as successfully parsed
					found = true;

				} else {

					// look for matching pattern
					for (Map.Entry<Pattern, Class<? extends Resource>> entry : resourceMap.entrySet()) {

						Pattern pattern = entry.getKey();
						Matcher matcher = pattern.matcher(pathParts[i]);

						if (matcher.matches()) {

							Class<? extends Resource> type = entry.getValue();
							Resource resource              = null;

							try {

								// instantiate resource constraint
								resource = type.newInstance();
							} catch (Throwable t) {

								logger.warn("Error instantiating resource class", t);

							}

							if (resource != null) {

								// set security context
								resource.setSecurityContext(securityContext);

								if (resource.checkAndConfigure(part, securityContext, request)) {

									logger.debug("{} matched, adding resource of type {} for part {}", new Object[] { matcher.pattern(), type.getName(),
										part });

									// allow constraint to modify context
									resource.configurePropertyView(propertyView);

									// add constraint and go on
									resourceChain.add(resource);

									found = true;

									// first match wins, so choose priority wisely ;)
									break;

								}
							}

						}
					}
				}

				if (!found) {

					throw new NotFoundException("Cannot resolve URL path");
				}

			}
		}

		return resourceChain;

	}
185685
def set_end_point_uri(self) -> bool:
        
        expected_parts = self.__route.split("/")
        actual_parts = self.__uri.split("/")

        i = 0
        for part in expected_parts:
            if part != actual_parts[i]:
                return False
            i = i + 1

        uri_prefix = len(self.__route)
        self.__end_point_uri = self.__uri[uri_prefix:]
        return True
316298
public static URL buildPostUrl(String host, int port, String path) throws MalformedURLException {
        return buildPostUrl("http", host, port, path);
    }
219570
final URI spliceUrl(String resource, Map<String, String> parameters) throws RestEndpointIOException {
        try {
            URIBuilder builder;
            if (!Strings.isNullOrEmpty(baseUrl)) {
                builder = new URIBuilder(baseUrl);
                builder.setPath(builder.getPath() + resource);
            } else {
                builder = new URIBuilder(resource);
            }
            for (Entry<String, String> parameter : parameters.entrySet()) {
                builder.addParameter(parameter.getKey(), parameter.getValue());
            }
            return builder.build();
        } catch (URISyntaxException e) {
            throw new RestEndpointIOException(
                    "Unable to builder URL with base url '" + baseUrl + "' and resouce '" + resource + "'", e);
        }
    }
812996
def build_url_parts (self):
        
        # check userinfo@host:port syntax
        self.userinfo, host = urllib.splituser(self.urlparts[1])
        port = urlutil.default_ports.get(self.scheme, 0)
        host, port = urlutil.splitport(host, port=port)
        if port is None:
            raise LinkCheckerError(_("URL host %(host)r has invalid port") %
                    {"host": host})
        self.port = port
        # set host lowercase
        self.host = host.lower()
        if self.scheme in scheme_requires_host:
            if not self.host:
                raise LinkCheckerError(_("URL has empty hostname"))
            self.check_obfuscated_ip()
        if not self.port or self.port == urlutil.default_ports.get(self.scheme):
            host = self.host
        else:
            host = "%s:%d" % (self.host, self.port)
        if self.userinfo:
            self.urlparts[1] = "%s@%s" % (self.userinfo, host)
        else:
            self.urlparts[1] = host
        # safe anchor for later checking
        self.anchor = self.urlparts[4]
        if self.anchor is not None:
            assert isinstance(self.anchor, unicode), repr(self.anchor)
892338
def _pathify(self):
        
        try:
            (path,
             query,
             self._fragment) = urisup.uri_help_split(self.path)[2:]

            if not path:
                path = "/"

            if path[0] != "/":
                raise urisup.InvalidURIError('path %r does not start with "/"' % path)

            self._path = re.sub("^/+", "/", path, 1)

            if query:
                self._query_params = self.querylist_to_dict(query)

            return self._path
        except urisup.InvalidURIError, e:
            LOG.error("invalid URI: %s", e)
            raise self.req_error(400, str(e))
169952
public Resource addPath(String path)
        throws IOException,MalformedURLException
    {
        FileResource r=null;

        if (!isDirectory())
        {
            r=(FileResource)super.addPath(path);
        }
        else
        {
            path = org.browsermob.proxy.jetty.util.URI.canonicalPath(path);
            
            // treat all paths being added as relative
            String rel=path;
            if (path.startsWith("/"))
                rel = path.substring(1);
            
            File newFile = new File(_file,rel.replace('/', File.separatorChar));
            r=new FileResource(newFile.toURI().toURL(),null,newFile);
        }
        
        String encoded= org.browsermob.proxy.jetty.util.URI.encodePath(path);
        int expected=r._urlString.length()-encoded.length();
        int index = r._urlString.lastIndexOf(encoded, expected);
        
        if (expected!=index && ((expected-1)!=index || path.endsWith("/") || !r.isDirectory()))
        {
            r._alias=r._url;
            r._aliasChecked=true;
        }                   
        return r;
    }
888873
def mkpath(*segments, **query):
    
    # Remove empty segments (e.g. no key specified)
    segments = [bytes_to_str(s) for s in segments if s is not None]
    # Join the segments into a path
    pathstring = '/'.join(segments)
    # Remove extra slashes
    pathstring = re.sub('/+', '/', pathstring)

    # Add the query string if it exists
    _query = {}
    for key in query:
        if query[key] in [False, True]:
            _query[key] = str(query[key]).lower()
        elif query[key] is not None:
            if PY2 and isinstance(query[key], unicode):  # noqa
                _query[key] = query[key].encode('utf-8')
            else:
                _query[key] = query[key]

    if len(_query) > 0:
        pathstring += "?" + urlencode(_query)

    if not pathstring.startswith('/'):
        pathstring = '/' + pathstring

    return pathstring
475661
def join_path(base, *parts: str):
    """"""
    _parts = "/".join((_part.strip("/") for _part in parts))
    # _parts = '/'.join(parts)
    if base.endswith("/"):
        url = base + _parts
    else:
        url = base + "/" + _parts
    return url