Identical to WebPypeClient.execute(), except this function accepts a
        url instead of a dictionary or string.
771181
def execute_from_url(self, url, input_url):
        '''
        

        '''
        inputs = self._request(input_url)
        resp = self.execute(url, inputs)
        return resp
479285
def urlopen(link):
    
    try:
        return urllib2.urlopen(link)
    except urllib2.URLError:
        pass
    except ValueError:
        return ""
    except KeyboardInterrupt:
        print("")
        raise SystemExit()
749239
def from_url(cls, url, show_host=True):
        ''''''
        # url must be idna-encoded and url-quotted

        if six.PY2:
            if isinstance(url, six.text_type):
                url = url.encode('utf-8')
            parsed = urlparse(url)
            netloc = parsed.netloc.decode('utf-8') # XXX HACK
        else:# pragma: no cover
            if isinstance(url, six.binary_type):
                url = url.decode('utf-8', errors='replace') # XXX
            parsed = urlparse(url)
            netloc = parsed.netloc

        query = _parse_qs(parsed.query)
        host = netloc.split(':', 1)[0] if ':' in netloc else netloc

        port = netloc.split(':')[1] if ':' in netloc else ''
        path = unquote(parsed.path)
        fragment = unquote(parsed.fragment)
        if not fragment and not url.endswith('#'):
            fragment = None
        return cls(path,
                   query, host,
                   port, parsed.scheme, fragment, show_host)
1128855
function URLGET(url, fields, method, callback)
	{
		// method variable is optional
		if (typeof method == "function")
		{
			callback = method;
			method = "GET";
		}

		_URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) {
			if (err)
			{
				// got error, bounce it up
				if (callback) callback(err);
				return;
			}
			else
			{
				var JSONBody;
				if (typeof body == "object")
				{
					// already a JSON object?
					JSONBody = body;
				}
				else
				{
					// try to parse JSON body
					if (!body || !/\S/.test(body))
					{
						// string is empty, return empty object
						if (callback) callback(false, {});
						return;
					}
					else
					{
						try
						{
							JSONBody = JSON.parse(body);
						}
						catch(parse_err)
						{
							// error parsing JSON result
							Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body);
							if (callback) callback("Parse JSON error: " + parse_err);
							return;
						}
					}
				}

				// success! return JSON object
				if (callback) callback(false, JSONBody);
			}
		});
	}
1087072
def _call(self, method, path, data=None):
    
    if is_python3():
      conn = http.client.HTTPConnection(API_HOST)
    else:
      conn = httplib.HTTPConnection(API_HOST)

    headers = {'User-Agent' : USER_AGENT}

    if data:
      headers.update( {'Content-type': 'application/x-www-form-urlencoded'} )
      conn.request(method, path, self._urlencode(data), headers)

    else:
      conn.request(method, path, None, headers)

    response = conn.getresponse()
    result   =  [response.status, self._parse_body(response.read())]
    conn.close()
    return result
1091235
def accepts_valid_urls(func):
    
    @functools.wraps(func)
    def wrapper(obj, urls, *args, **kwargs):
        """Run the function and return a value for valid URLs.

        :param obj: an object in whose class f is defined
        :param urls: an iterable containing URLs
        :returns: a return value of the function f
        :raises InvalidURLError: if the iterable contains invalid URLs
        """
        invalid_urls = [u for u in urls if not is_valid_url(u)]
        if invalid_urls:
            msg_tpl = 'The values: {} are not valid URLs'
            msg = msg_tpl.format(','.join(invalid_urls))
            raise InvalidURLError(msg)
        return func(obj, urls, *args, **kwargs)
    return wrapper
310157
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
        
        if fields:
            url += '?' + urlencode(fields)
        return self.urlopen(method, url, **urlopen_kw)
540130
def execute_javascript(self, *args, **kwargs):
		'''
		
		'''

		ret = self.__exec_js(*args, **kwargs)
		return ret
521298
def execute(self, ignore_cache=False, raise_on_error=True):
        
        if ignore_cache or not hasattr(self, '_response'):
            es = connections.get_connection(self._using)

            responses = es.msearch(
                index=self._index,
                body=self.to_dict(),
                **self._params
            )

            out = []
            for s, r in zip(self._searches, responses['responses']):
                if r.get('error', False):
                    if raise_on_error:
                        raise TransportError('N/A', r['error']['type'], r['error'])
                    r = None
                else:
                    r = Response(s, r)
                out.append(r)

            self._response = out

        return self._response
191810
def invoke(self, method, relpath=None, params=None, data=None, headers=None):
    
    path = self._join_uri(relpath)
    resp = self._client.execute(method,
                                path,
                                params=params,
                                data=data,
                                headers=headers)
    try:
      body = resp.read()
    except Exception, ex:
      raise Exception("Command '%s %s' failed: %s" %
                      (method, path, ex))

    self._client.logger.debug(
        "%s Got response: %s%s" %
        (method, body[:32], len(body) > 32 and "..." or ""))

    # Is the response application/json?
    if len(body) != 0 and \
          resp.info().getmaintype() == "application" and \
          resp.info().getsubtype() == "json":
      try:
        json_dict = json.loads(body)
        return json_dict
      except Exception, ex:
        self._client.logger.exception('JSON decode error: %s' % (body,))
        raise ex
    else:
      return body
1212088
def send_request(self, url):
        
        while True:
            try:
                return urllib.request.urlopen(url)
            except urllib.error.HTTPError as e:
                raise serror(
                    "Request `%s` failed (%s:%s)." %
                    (url, e.__class__.__name__, e.code))
            except Exception as e:
                choice = input(serror(
                    "Error occured: %s - Retry? [yN]" % type(e)))
                if choice.strip().lower() != "y":
                    raise serror(e)
296872
def _get_request(self, url, params=None, **kwargs):
        
        '''  '''
        
    # construct request kwargs
        request_kwargs = {
            'method': 'GET',
            'url': url,
            'params': params
        }
        for key, value in kwargs.items():
            request_kwargs[key] = value

    # send request and handle response
        return self._request(**request_kwargs)
1022444
def urlopen(self, method, url, body=None, headers=None, **kwargs):
        """"""
        # pylint: disable=arguments-differ
        # We use kwargs to collect additional args that we don't need to
        # introspect here. However, we do explicitly collect the two
        # positional arguments.

        # Use a kwarg for this instead of an attribute to maintain
        # thread-safety.
        _credential_refresh_attempt = kwargs.pop(
            '_credential_refresh_attempt', 0)

        if headers is None:
            headers = self.headers

        # Make a copy of the headers. They will be modified by the credentials
        # and we want to pass the original headers if we recurse.
        request_headers = headers.copy()

        self.credentials.before_request(
            self._request, method, url, request_headers)

        response = self.http.urlopen(
            method, url, body=body, headers=request_headers, **kwargs)

        # If the response indicated that the credentials needed to be
        # refreshed, then refresh the credentials and re-attempt the
        # request.
        # A stored token may expire between the time it is retrieved and
        # the time the request is made, so we may need to try twice.
        # The reason urllib3's retries aren't used is because they
        # don't allow you to modify the request headers. :/
        if (response.status in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts):

            _LOGGER.info(
                'Refreshing credentials due to a %s response. Attempt %s/%s.',
                response.status, _credential_refresh_attempt + 1,
                self._max_refresh_attempts)

            self.credentials.refresh(self._request)

            # Recurse. Pass in the original headers, not our modified set.
            return self.urlopen(
                method, url, body=body, headers=headers,
                _credential_refresh_attempt=_credential_refresh_attempt + 1,
                **kwargs)

        return response
856833
def _request(method, url, session=None, **kwargs):
    
    url = BASE_URL + url

    if session:
        request_func = getattr(session, method)
    else:
        request_func = getattr(requests, method)
    response = request_func(url, **kwargs)
    # raise an exception if request is not successful
    if not response.status_code == requests.codes.ok:
        raise DweepyError('HTTP {0} response'.format(response.status_code))
    response_json = response.json()
    if response_json['this'] == 'failed':
        raise DweepyError(response_json['because'])
    return response_json['with']
652653
def object_url(self, object_t, object_id=None, relation=None, **kwargs):
        
        if object_t not in self.objects_types:
            raise TypeError("{} is not a valid type".format(object_t))
        request_items = (
            str(item) for item in [object_t, object_id, relation] if item is not None
        )
        request = "/".join(request_items)
        base_url = self.url(request)
        if self.access_token is not None:
            kwargs["access_token"] = str(self.access_token)
        if kwargs:
            for key, value in kwargs.items():
                if not isinstance(value, str):
                    kwargs[key] = str(value)
            # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7)
            sorted_kwargs = SortedDict.from_dict(kwargs)
            result = "{}?{}".format(base_url, urlencode(sorted_kwargs))
        else:
            result = base_url
        return result
906772
public boolean execute(Context context) throws Exception
   {
      GenericWebAppContext webCtx = (GenericWebAppContext)context;
      HttpServletResponse response = webCtx.getResponse();
      HttpServletRequest request = webCtx.getRequest();

      // standalone request?
      String servletPath = request.getPathInfo();
      boolean doClose = true;
      // or included?
      if (servletPath == null)
      {
         servletPath = (String)request.getAttribute("javax.servlet.include.path_info");
         if (servletPath != null)
            doClose = false;
      }

      Node file = (Node)webCtx.getSession().getItem((String)context.get(pathKey));
      file.refresh(false);

      Node content = null;

      try
      {
         content = JCRCommandHelper.getNtResourceRecursively(file);
      }
      catch (ItemNotFoundException e)
      {
         // Patch for ver 1.0 back compatibility
         // as exo:image was not primary item
         if (file.isNodeType("exo:article"))
         {
            try
            {
               content = file.getNode("exo:image");
            }
            catch (PathNotFoundException e1)
            {
               throw e; // new ItemNotFoundException("No nt:resource node found at
               // "+file.getPath()+" nor primary items of nt:resource type
               // ");
            }
         }
         else
         {
            throw e; // new ItemNotFoundException("No nt:resource node found at
            // "+file.getPath()+" nor primary items of nt:resource type
            // ");
         }

      }

      // if(file.isNodeType("nt:file")) {
      // content = file.getNode("jcr:content");
      // } else if(file.isNodeType("exo:article")) {
      // content = file.getNode("exo:image");
      // } else
      // throw new Exception("Invalid node type, expected nt:file or exo:article,
      // have "+file.getPrimaryNodeType().getName()+" at "+file.getPath());

      Property data;
      try
      {
         data = content.getProperty("jcr:data");
      }
      catch (PathNotFoundException e)
      {
         throw new PathNotFoundException("No jcr:data node found at " + content.getPath());
      }

      String mime = content.getProperty("jcr:mimeType").getString();
      String encoding =
         content.hasProperty("jcr:encoding") ? content.getProperty("jcr:encoding").getString() : DEFAULT_ENCODING;

      MimeTypeResolver resolver = new MimeTypeResolver();
      String fileName = file.getName();
      String fileExt = "";
      if (fileName.lastIndexOf(".") > -1)
      {
         fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
         fileName = fileName.substring(0, fileName.lastIndexOf("."));
      }
      String mimeExt = resolver.getExtension(mime);
      if (fileExt == null || fileExt.length() == 0)
      {
         fileExt = mimeExt;
      }
      response.setContentType(mime + "; charset=" + encoding);
      String parameter = (String)context.get("cache-control-max-age");
      String cacheControl = parameter == null ? "" : "public, max-age=" + parameter;
      response.setHeader("Cache-Control: ", cacheControl);
      response.setHeader("Pragma: ", ""); // leave blank to avoid IE errors
      response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "." + fileExt + "\"");

      if (mime.startsWith("text"))
      {
         PrintWriter out = response.getWriter();
         out.write(data.getString());
         out.flush();
         if (doClose)
            out.close();
      }
      else
      {
         InputStream is = data.getStream();
         byte[] buf = new byte[is.available()];
         is.read(buf);
         ServletOutputStream os = response.getOutputStream();
         os.write(buf);
         os.flush();
         if (doClose)
            os.close();
      }

      return true;
   }
951745
def request(self, url, method="get", format="json", data=None,
                expected_status=None, headers=None, use_xpost=True, **options):
        
        if expected_status is None:
            if method == "get":
                expected_status = 200
            elif method == "post":
                expected_status = 201
            else:
                raise ValueError("No expected status supplied and method unknown.")

        if not url.startswith("http"):
            url = "{self.host}/api/v4/{url}".format(**locals())
        if format is not None:
            options = dict({'format': format}, **options)
        options = {field: value for field, value in options.items() if value is not None}
        headers = dict(headers or {}, Authorization="Token {}".format(self.token))
        #headers['Accept-encoding'] = 'gzip'

        if method == "get" and use_xpost:
            # If method is purely GET, we can use X-HTTP-METHOD-OVERRIDE to send our
            # query via POST. This allows for a large number of parameters to be supplied
            assert(data is None)

            headers.update({"X-HTTP-METHOD-OVERRIDE": method})
            data = options
            options = None
            method = "post"

        r = requests.request(method, url, data=data, params=options, headers=headers)

        log.debug(
            "HTTP {method} {url} (options={options!r}, data={data!r},"
            "headers={headers}) -> {r.status_code}".format(**locals())
        )
        return check(r, expected_status=expected_status)