Пример #1
0
    def __init__(self, params, username = None, password = None):
        """
        Builds an HttpRequest

        :param params: an <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a>
        :param username: the username
            (optional, it will override the credentials defined on the <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> object)
        :param password: an password
            (optional, it will override the credentials defined on the <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
Пример #2
0
    def __init__(self, params, username = None, password = None, verify = True):
        """
        Builds an HttpRequest

        :param username: the username for basic authentication
            (optional, no authentication will be used if empty)
        :param password: an password
            (optional)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
        self.verify   = verify
    def __init__(self, params, username=None, password=None):
        """
        Builds an HttpRequest

        :param params: an HttpConnection
        :param username: the username
            (optional, it will override the credentials defined on the HttpConnection object)
        :param password: an password
            (optional, it will override the credentials defined on the HttpConnection object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
Пример #4
0
class QtestHTTPRequest(HttpRequest):
    def __init__(self, params, username=None, password=None, token=None):
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
        self.token = token

    def setCredentials(self, request):
        if self.token:
            request.addHeader('Authorization', self.token)
            return
        elif self.username:
            username = self.username
        elif self.params.getUsername():
            username = self.params.getUsername()
        else:
            return
        encoding = Base64.encodeBase64String(
            String(username + ':').getBytes('ISO-8859-1'))
        request.addHeader('Authorization', 'Basic ' + encoding)

    def buildRequest(self, method, context, body, contentType, headers):
        url = self.quote(self.createPath(self.params.getUrl(), context))

        method = method.upper()

        if method == 'GET':
            request = HttpGet(url)
        elif method == 'HEAD':
            request = HttpHead(url)
        elif method == 'POST':
            request = HttpPost(url)
            request.setEntity(StringEntity(body))
        elif method == 'PUT':
            request = HttpPut(url)
            request.setEntity(StringEntity(body))
        elif method == 'DELETE':
            request = HttpDelete(url)
        elif method == 'PATCH':
            request = HttpPatch(url)
            request.setEntity(StringEntity(body))
        else:
            raise Exception('Unsupported method: ' + method)

        request.addHeader('Content-Type', contentType)
        self.setCredentials(request)
        self.setProxy(request)
        self.setHeaders(request, headers)

        return request
Пример #5
0
    def __init__(self, params, username=None, password=None, verify=True):
        """
        Builds an HttpRequest

        :param username: the username for basic authentication
            (optional, no authentication will be used if empty)
        :param password: an password
            (optional)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
        self.verify = verify
        self.logger = LoggerFactory.getLogger(
            "com.xebialabs.dockerregistryv2-plugin")
Пример #6
0
    def __init__(self, params, username=None, password=None, domain=None):
        """
        Builds an HttpRequest

        :param params: an HttpConnection
        :param username: the username
            (optional, it will override the credentials defined on the HttpConnection object)
        :param password: an password
            (optional, it will override the credentials defined on the HttpConnection object)
        """
        self.params = HttpConnection(params)
        self.shared_domain = params['domain']
        self.username = username
        self.password = password
        self.domain = domain
        self.authentication = params['authenticationMethod']
Пример #7
0
    def __init__(self, params, username=None, password=None):
        """
        Builds an HttpRequest

        :param params: an HttpConnection
        :param username: the username
            (optional, it will override the credentials defined on the HttpConnection object)
        :param password: an password
            (optional, it will override the credentials defined on the HttpConnection object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
Пример #8
0
 def __init__(self, params, username=None, password=None, token=None):
     self.params = HttpConnection(params)
     self.username = username
     self.password = password
     self.token = token
Пример #9
0
class HttpRequest:
    def __init__(self, params, username = None, password = None, verify = True):
        """
        Builds an HttpRequest

        :param username: the username for basic authentication
            (optional, no authentication will be used if empty)
        :param password: an password
            (optional)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password
        self.verify   = verify

    def doRequest(self, **options):
        """
        Performs an HTTP Request

        :param options: A keyword arguments object with the following properties :
            method: the HTTP method : 'GET', 'PUT', 'POST', 'DELETE', 'PATCH'
                (optional: GET will be used if empty)
            context: the context url
                (optional: the url on <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> will be used if empty)
            body: the body of the HTTP request for PUT & POST calls
                (optional: an empty body will be used if empty)
            contentType: the content type to use
                (optional, no content type will be used if empty)
            headers: a dictionary of headers key/values
                (optional, no headers will be used if empty)
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        request = self.buildRequest(
            options.get('method', 'GET'),
            options.get('context', ''),
            options.get('body', ''),
            options.get('contentType', None),
            options.get('headers', None))
        return self.executeRequest(request)


    def get(self, context, **options):
        """
        Performs an HTTP GET Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'GET'
        options['context'] = context
        return self.doRequest(**options)


    def head(self, context, **options):
        """
        Performs an HTTP HEAD Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'HEAD'
        options['context'] = context
        return self.doRequest(**options)


    def put(self, context, body, **options):
        """
        Performs an HTTP PUT Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'PUT'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)


    def post(self, context, body, **options):
        """
        Performs an HTTP POST Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'POST'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)


    def delete(self, context, **options):
        """
        Performs an HTTP DELETE Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'DELETE'
        options['context'] = context
        return self.doRequest(**options)

    def patch(self, context, body, **options):
        """
        Performs an HTTP PATCH Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'PATCH'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def buildRequest(self, method, context, body, contentType, headers):
        url = self.quote(self.createPath(self.params.getUrl(), context))

        method = method.upper()

        if method == 'GET':
            request = HttpGet(url)
        elif method == 'HEAD':
            request = HttpHead(url)
        elif method == 'POST':
            request = HttpPost(url)
            request.setEntity(StringEntity(body))
        elif method == 'PUT':
            request = HttpPut(url)
            request.setEntity(StringEntity(body))
        elif method == 'DELETE':
            request = HttpDelete(url)
        elif method == 'PATCH':
            request = HttpPatch(url)
            request.setEntity(StringEntity(body))
        else:
            raise Exception('Unsupported method: ' + method)

        request.addHeader('Content-Type', contentType)
        request.addHeader('Accept', contentType)
        self.setCredentials(request)
        self.setProxy(request)
        self.setHeaders(request, headers)

        return request


    def createPath(self, url, context):
        url = re.sub('/*$', '', url)
        if context is None:
            return url
        elif context.startswith('/'):
            return url + context
        else:
            return url + '/' + context

    def quote(self, url):
        return urllib.quote(url, ':/?&=%')


    def setCredentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(String(username + ':' + password).getBytes('ISO-8859-1'))
        request.addHeader('Authorization', 'Basic ' + encoding)


    def setProxy(self, request):
        if not self.params.getProxyHost():
            return

        proxy = HttpHost(self.params.getProxyHost(), int(self.params.getProxyPort()))
        config = RequestConfig.custom().setProxy(proxy).build()
        request.setConfig(config)


    def setHeaders(self, request, headers):
        if headers:
            for key in headers:
                request.setHeader(key, headers[key])


    def executeRequest(self, request):
        client = None
        response = None
        try:
            if not self.verify:
                client = self.create_http_client()
            elif self.params.proxyUsername and self.params.proxyPassword:
                credentials = UsernamePasswordCredentials(self.params.proxyUsername, self.params.proxyPassword)
                auth_scope = AuthScope(self.params.proxyHost, Integer.valueOf(self.params.proxyPort))
                creds_provider = BasicCredentialsProvider()
                creds_provider.setCredentials(auth_scope, credentials)
                client = HttpClientBuilder.create().setDefaultCredentialsProvider(creds_provider).build()
            else:
                client = HttpClients.createDefault()

            response = client.execute(request)
            status = response.getStatusLine().getStatusCode()
            entity = response.getEntity()
            result = EntityUtils.toString(entity, "UTF-8") if entity else None
            headers = response.getAllHeaders()
            EntityUtils.consume(entity)

            return HttpResponse(status, result, headers)
        finally:
            if response:
                response.close()
            if client:
                client.close()

    def create_http_client(self):
        builder = SSLContextBuilder()
        builder.loadTrustMaterial(None, TrustAllStrategy())
        tls_versions = ["TLSv1", "TLSv1.1", "TLSv1.2"]
        socketfactory = SSLConnectionSocketFactory(builder.build(), tls_versions, None, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
        # print 'DEBUG: Created custom HttpClient to trust all certs\n'
        return HttpClients.custom().setSSLSocketFactory(socketfactory).build()
class HttpRequest:
    def __init__(self, params, username=None, password=None):
        """
        Builds an HttpRequest

        :param params: an HttpConnection
        :param username: the username
            (optional, it will override the credentials defined on the HttpConnection object)
        :param password: an password
            (optional, it will override the credentials defined on the HttpConnection object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password

    def doRequest(self, **options):
        """
        Performs an HTTP Request

        :param options: A keyword arguments object with the following properties :
            method: the HTTP method : 'GET', 'PUT', 'POST', 'DELETE', 'PATCH'
                (optional: GET will be used if empty)
            context: the context url
                (optional: the url on HttpConnection will be used if empty)
            body: the body of the HTTP request for PUT & POST calls
                (optional: an empty body will be used if empty)
            contentType: the content type to use
                (optional, no content type will be used if empty)
            headers: a dictionary of headers key/values
                (optional, no headers will be used if empty)
        :return: an HttpResponse instance
        """
        request = self.buildRequest(options.get('method', 'GET'),
                                    options.get('context', ''),
                                    options.get('body', ''),
                                    options.get('contentType', None),
                                    options.get('headers', None))
        return self.executeRequest(request)

    def get(self, context, **options):
        """
        Performs an Http GET Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options['method'] = 'GET'
        options['context'] = context
        return self.doRequest(**options)

    def put(self, context, body, **options):
        """
        Performs an Http PUT Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options['method'] = 'PUT'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def post(self, context, body, **options):
        """
        Performs an Http POST Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options['method'] = 'POST'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def delete(self, context, **options):
        """
        Performs an Http DELETE Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options['method'] = 'DELETE'
        options['context'] = context
        return self.doRequest(**options)

    def patch(self, context, body, **options):
        """
        Performs an Http PATCH Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options['method'] = 'PATCH'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def buildRequest(self, method, context, body, contentType, headers):
        url = self.quote(self.createPath(self.params.getUrl(), context))

        method = method.upper()

        if method == 'GET':
            request = HttpGet(url)
        elif method == 'POST':
            request = HttpPost(url)
            request.setEntity(StringEntity(body))
        elif method == 'PUT':
            request = HttpPut(url)
            request.setEntity(StringEntity(body))
        elif method == 'DELETE':
            request = HttpDelete(url)
        elif method == 'PATCH':
            request = HttpPatch(url)
            request.setEntity(StringEntity(body))
        else:
            raise Exception('Unsupported method: ' + method)

        request.addHeader('Content-Type', contentType)
        request.addHeader('Accept', contentType)
        self.setCredentials(request)
        self.setProxy(request)
        self.setHeaders(request, headers)

        return request

    def createPath(self, url, context):
        url = re.sub('/*$', '', url)
        if context is None:
            return url
        elif context.startswith('/'):
            return url + context
        else:
            return url + '/' + context

    def quote(self, url):
        return urllib.quote(url, ':/?&=%')

    def setCredentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(
            String(username + ':' + password).getBytes('ISO-8859-1'))
        request.addHeader('Authorization', 'Basic ' + encoding)

    def setProxy(self, request):
        if not self.params.getProxyHost():
            return

        proxy = HttpHost(self.params.getProxyHost(),
                         int(self.params.getProxyPort()))
        config = RequestConfig.custom().setProxy(proxy).build()
        request.setConfig(config)

    def setHeaders(self, request, headers):
        if headers:
            for key in headers:
                request.setHeader(key, headers[key])

    def executeRequest(self, request):
        client = None
        response = None
        try:
            client = HttpClients.createDefault()
            response = client.execute(request)
            status = response.getStatusLine().getStatusCode()
            entity = response.getEntity()
            result = EntityUtils.toString(entity, "UTF-8") if entity else None
            headers = response.getAllHeaders()
            EntityUtils.consume(entity)

            return HttpResponse(status, result, headers)
        finally:
            if response:
                response.close()
            if client:
                client.close()
Пример #11
0
class HttpRequest:
    def __init__(self, params, username=None, password=None):
        """
        Builds an HttpRequest

        :param params: an HttpConnection
        :param username: the username
            (optional, it will override the credentials defined on the HttpConnection object)
        :param password: an password
            (optional, it will override the credentials defined on the HttpConnection object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password

    def doRequest(self, **options):
        """
        Performs an HTTP Request

        :param options: A keyword arguments object with the following properties :
            method: the HTTP method : 'GET', 'PUT', 'POST', 'DELETE'
                (optional: GET will be used if empty)
            context: the context url
                (optional: the url on HttpConnection will be used if empty)
            body: the body of the HTTP request for PUT & POST calls
                (optional: an empty body will be used if empty)
            contentType: the content type to use
                (optional, no content type will be used if empty)
            headers: a dictionary of headers key/values
                (optional, no headers will be used if empty)
        :return: an HttpResponse instance
        """
        request = self.buildRequest(
            options.get("method", "GET"),
            options.get("context", ""),
            options.get("body", ""),
            options.get("contentType", None),
            options.get("headers", None),
        )
        return self.executeRequest(request)

    def get(self, context, **options):
        """
        Performs an Http GET Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options["method"] = "GET"
        options["context"] = context
        return self.doRequest(**options)

    def put(self, context, body, **options):
        """
        Performs an Http PUT Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options["method"] = "PUT"
        options["context"] = context
        options["body"] = body
        return self.doRequest(**options)

    def post(self, context, body, **options):
        """
        Performs an Http POST Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options["method"] = "POST"
        options["context"] = context
        options["body"] = body
        return self.doRequest(**options)

    def delete(self, context, **options):
        """
        Performs an Http DELETE Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an HttpResponse instance
        """
        options["method"] = "DELETE"
        options["context"] = context
        return self.doRequest(**options)

    def buildRequest(self, method, context, body, contentType, headers):
        url = self.quote(self.createPath(self.params.getUrl(), context))

        method = method.upper()

        if method == "GET":
            request = HttpGet(url)
        elif method == "POST":
            request = HttpPost(url)
            request.setEntity(StringEntity(body))
        elif method == "PUT":
            request = HttpPut(url)
            request.setEntity(StringEntity(body))
        elif method == "DELETE":
            request = HttpDelete(url)
        else:
            raise Exception("Unsupported method: " + method)

        request.addHeader("Content-Type", contentType)
        request.addHeader("Accept", contentType)
        self.setCredentials(request)
        self.setProxy(request)
        self.setHeaders(request, headers)

        return request

    def createPath(self, url, context):
        url = re.sub("/*$", "", url)
        if context is None:
            return url
        elif context.startswith("/"):
            return url + context
        else:
            return url + "/" + context

    def quote(self, url):
        return urllib.quote(url, ":/?&=%")

    def setCredentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(String(username + ":" + password).getBytes())
        request.addHeader("Authorization", "Basic " + encoding)

    def setProxy(self, request):
        if not self.params.getProxyHost():
            return

        proxy = HttpHost(self.params.getProxyHost(), int(self.params.getProxyPort()))
        config = RequestConfig.custom().setProxy(proxy).build()
        request.setConfig(config)

    def setHeaders(self, request, headers):
        if headers:
            for key in headers:
                request.setHeader(key, headers[key])

    def executeRequest(self, request):
        client = None
        response = None
        try:
            client = HttpClients.createDefault()
            response = client.execute(request)
            status = response.getStatusLine().getStatusCode()
            entity = response.getEntity()
            result = EntityUtils.toString(entity, "UTF-8") if entity else None
            headers = response.getAllHeaders()
            EntityUtils.consume(entity)

            return HttpResponse(status, result, headers)
        finally:
            if response:
                response.close()
            if client:
                client.close()
Пример #12
0
class HttpRequestPlus:
    logger = logging.getLogger('HttpRequestPlus')

    def __init__(self, params, username=None, password=None):
        """
        Builds an HttpRequest

        :param params: an <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a>
        :param username: the username
            (optional, it will override the credentials defined on the <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> object)
        :param password: an password
            (optional, it will override the credentials defined on the <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> object)
        """
        self.params = HttpConnection(params)
        self.username = username
        self.password = password

    def doRequest(self, **options):
        """
        Performs an HTTP Request

        :param options: A keyword arguments object with the following properties :
            method: the HTTP method : 'GET', 'PUT', 'POST', 'DELETE', 'PATCH'
                (optional: GET will be used if empty)
            context: the context url
                (optional: the url on <a href="/jython-docs/#!/_PROD_VERSION_/service/com.xebialabs.xlrelease.domain.configuration.HttpConnection">HttpConnection</a> will be used if empty)
            body: the body of the HTTP request for PUT & POST calls
                (optional: an empty body will be used if empty)
            contentType: the content type to use
                (optional, no content type will be used if empty)
            headers: a dictionary of headers key/values
                (optional, no headers will be used if empty)
            quotePlus:  boolean to control quoting with urllib.quote_plus() versus urllib.quote()
                (optional, urllib.quote() will be used if empty or false)
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        request = self.buildRequest(options.get('method', 'GET'),
                                    options.get('context', ''),
                                    options.get('body', ''),
                                    options.get('contentType', None),
                                    options.get('headers', None),
                                    options.get('quotePlus', False))
        return self.executeRequest(request)

    def get(self, context, **options):
        """
        Performs an HTTP GET Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'GET'
        options['context'] = context
        return self.doRequest(**options)

    def head(self, context, **options):
        """
        Performs an HTTP HEAD Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'HEAD'
        options['context'] = context
        return self.doRequest(**options)

    def put(self, context, body, **options):
        """
        Performs an HTTP PUT Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'PUT'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def post(self, context, body, **options):
        """
        Performs an HTTP POST Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'POST'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def delete(self, context, **options):
        """
        Performs an HTTP DELETE Request

        :param context: the context url
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'DELETE'
        options['context'] = context
        return self.doRequest(**options)

    def patch(self, context, body, **options):
        """
        Performs an HTTP PATCH Request

        :param context: the context url
        :param body: the body of the HTTP request
        :param options: the options keyword argument described in doRequest()
        :return: an <a href="/jython-docs/#!/_PROD_VERSION_/service/HttpResponse.HttpResponse">HttpResponse</a> instance
        """
        options['method'] = 'PATCH'
        options['context'] = context
        options['body'] = body
        return self.doRequest(**options)

    def buildRequest(self, method, context, body, contentType, headers,
                     quotePlus):
        url = self.quote(self.createPath(self.params.getUrl(), context),
                         quotePlus)

        method = method.upper()
        self.logger.debug('buildRequest:       method: %s' % method)
        self.logger.debug('buildRequest:          url: %s' % url)
        self.logger.debug('buildRequest: content-type: %s' % contentType)

        if method == 'GET':
            request = HttpGet(url)
        elif method == 'HEAD':
            request = HttpHead(url)
        elif method == 'POST':
            request = HttpPost(url)
            request.setEntity(StringEntity(str(body)))
        elif method == 'PUT':
            request = HttpPut(url)
            request.setEntity(StringEntity(str(body)))
        elif method == 'DELETE':
            request = HttpDelete(url)
        elif method == 'PATCH':
            request = HttpPatch(url)
            request.setEntity(StringEntity(body))
        else:
            raise Exception('Unsupported method: ' + method)

        request.addHeader('Content-Type', contentType)
        request.addHeader('Accept', contentType)
        self.setCredentials(request)
        self.setProxy(request)
        self.setHeaders(request, headers)

        return request

    def createPath(self, url, context):
        url = re.sub('/*$', '', url)
        if context is None:
            return url
        elif context.startswith('/'):
            return url + context
        else:
            return url + '/' + context

    def quote(self, url, quotePlus):
        if quotePlus:
            return urllib.quote_plus(url, ':/?&=%')
        else:
            return urllib.quote(url, ':/?&=%')

    def setCredentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(
            String(username + ':' + password).getBytes('ISO-8859-1'))
        request.addHeader('Authorization', 'Basic ' + encoding)

    def setProxy(self, request):
        if not self.params.getProxyHost():
            return

        proxy = HttpHost(self.params.getProxyHost(),
                         int(self.params.getProxyPort()))
        config = RequestConfig.custom().setProxy(proxy).build()
        request.setConfig(config)

    def setHeaders(self, request, headers):
        if headers:
            for key in headers:
                request.setHeader(key, headers[key])

    def executeRequest(self, request):
        self.logger.debug('executeRequest:  request: %s' % repr(request))
        client = None
        response = None
        try:
            client = HttpClients.createDefault()
            response = client.execute(request)
            self.logger.debug('executeRequest: response: %s' % repr(response))

            status = response.getStatusLine().getStatusCode()
            self.logger.debug('executeRequest:   status: %s' % status)

            entity = response.getEntity()
            data = EntityUtils.toString(entity, "UTF-8") if entity else None
            headers = response.getAllHeaders()
            EntityUtils.consume(entity)

            return HttpResponse(status, data, headers)

        except Exception as e:
            self.logger.error('executeRequest: failed: %s' % repr(e))
            raise e

        finally:
            if response:
                response.close()
            if client:
                client.close()
Пример #13
0
import httplib
import base64
import string
from xml.dom.minidom import parse, parseString
from com.xebialabs.xlrelease.domain.configuration import HttpConnection

#url="http://localhost:8080/view/List/job/PetPortal-build-only/ws/dar/target/PetPortal-3.0-CD-SNAPSHOT.dar"

xld_conn = HttpConnection({
    'url': 'http://localhost:4516',
    'username': '******',
    'password': '******'
})
xld_request = HttpRequest(xld_request, 'admin', 'admin')
url = "%s/view/List/job/%s/ws/%s" % (jenkinsServer['url'], jobName,
                                     pathInWorkspace)
print "URL %s " % (url)

importReponse = xld_request.post("/deployit/package/fetch",
                                 url,
                                 contentType='application/xml')
if buildResponse.isSuccessful():
    dom = parseString(importResponse.response)
    version = dom.getElementsByTagName("udm.DeploymentPackage")[0]

#auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
#headers = {"Content-type": "application/xml", "Accept": "application/xml","Authorization":"Basic %s" % auth}
#conn = httplib.HTTPConnection("localhost:4516")
#conn.request("POST", "/deployit/package/fetch", url, headers)
response = conn.getresponse()
print response