<commit_before>#!/usr/bin/env python

"""
This is a python interface for using Openshift-2.0 REST 
version = 2.0  changed the basic support to use the new requests module
 (http://docs.python-requests.org/en/latest/index.html)

"""

import os
import sys
import logging
from optparse import OptionParser
import time
import traceback
import json

import requests


class OpenShiftException(BaseException):
    pass


class OpenShiftLoginException(OpenShiftException):
    """Authorization failed."""
    pass

class OpenShiftAppException(OpenShiftException):
    """App not found."""
    pass

class OpenShiftNullDomainException(OpenShiftException):
    """User's domain hasn't been initialized."""
    pass


class OpenShift500Exception(OpenShiftException):
    """Internal Server Error"""
    pass

#### set this to True if we want to enable performance analysis
DOING_PERFORMANCE_ANALYSIS = False

global log


def config_logger():
    # create formatter
    formatter = logging.Formatter("%(levelname)s [%(asctime)s] %(message)s",
                                  "%H:%M:%S")
    logger = logging.getLogger("dump_logs")
    log_formatter = logging.Formatter(
        "%(name)s: %(asctime)s - %(levelname)s: %(message)s")

    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logging.DEBUG)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(stream_handler)
    return logger


def config_parser():
    # these are required options.
    parser.set_defaults(VERBOSE=False)
    parser.set_defaults(DEBUG=False)
    parser.add_option("-d", action="store_true", dest="DEBUG", help="enable DEBUG (default true)")
    #parser.add_option("-a", "--action", help="action you want to take (list|create|store)")
    parser.add_option("-i", "--ip", default="openshift.redhat.com", help="ip addaress of your devenv")
    parser.add_option("-v", action="store_true", dest="VERBOSE", help="enable VERBOSE printing")
    parser.add_option("-u", "--user", default=None, help="User name")
    parser.add_option("-p", "--password", default=None, help="RHT password")
    (options, args) = parser.parse_args()

    if options.user is None:
        options.user = os.getenv('OPENSHIFT_user_email')

    if options.password is None:
        options.password = os.getenv('OPENSHIFT_user_passwd')

    return options, args
log = config_logger()
parser = OptionParser()


# helper function for to measure timedelta.
def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        log.info("%r (%r, %r) %2.2f sec" % (method.__name__, args, kw, te-ts))
        return result, te-ts

    return timed


class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            return func
        else:
            return self.decorator(func)


class RestApi(object):
    """
    A base connection class to derive from.
    """

    host = '127.0.0.1'
    port = 443
    username = None
    password = None
    headers = None
    response = None
    base_uri = None
    verbose = False
    debug = False

    def __init__(self, host=None, port=443, username=username, password=password,
                 debug=False, verbose=False):
        if host is not None:
            self.host = host

        if username:
            self.username = username

        if password:
            self.password = password

        if verbose:
            self.verbose = verbose

        self.debug = debug
        self.base_uri = "https://" + host + "/broker/rest"

    def _get_auth_headers(self, username=None, password=<PASSWORD>):
        if username:
            self.username = username

        if password:
            self.password = password

        return (self.username, self.password)

    def request(self, url, method, headers=None, params=None):
        """
        wrapper method for Requests' methods
        """
        if url.startswith("https://"):
            self.url = url  # self.base_uri + url
        else:
            self.url = self.base_uri + url
        log.debug("URL: %s" % self.url)
        auth = (self.username, self.password)  # self._get_auth_headers()

        if method:
            method = method.lower()
        method_call = getattr(requests, method)
        self.response = method_call(
            url=self.url, auth=auth, params=params,
            timeout=130, verify=False)
        try:
            raw_response = self.response.raw
        except Exception as e:
            print >>sys.stderr, "-"*80
            traceback.print_exc(file=sys.stderr)
            print >>sys.stderr, "-"*80
            raise e

        self.data = self.response.json

        # see https://github.com/kennethreitz/requests/blob/master/requests/status_codes.py
        if self.response.status_code == requests.codes.internal_server_error:
            raise OpenShift500Exception('Internal Server Error: %s' % self.data)

        if self.response.status_code == (200 or 201):
            print >>sys.stderr, "-"*80
            log.debug("status:  %s" % self.response.status_code)
            #log.debug("msg: %s" % self.data()['messages'][0]['text'])
            # the raw_response is not available
            #log.debug("raw:  %s"%raw_response)
            print >>sys.stderr, "-"*80
        return (self.response.status_code, self.data)


class Openshift(object):
    """
    wrappers class around REST API so use can use it with python
    """
    rest = None
    user = None
    passwd = None

    def __init__(self, host, user=None, passwd=<PASSWORD>, debug=False, verbose=False, logger=None):
        if user:
            self.user = user
        if passwd:
            self.passwd = <PASSWORD>
        if logger:<commit_msg>Use print functions instead of print statements<commit_after>#!/usr/bin/env python
from __future__ import print_function

"""
This is a python interface for using Openshift-2.0 REST 
version = 2.0  changed the basic support to use the new requests module
 (http://docs.python-requests.org/en/latest/index.html)

"""

import os
import sys
import logging
from optparse import OptionParser
import time
import traceback
import json

import requests


class OpenShiftException(BaseException):
    pass


class OpenShiftLoginException(OpenShiftException):
    """Authorization failed."""
    pass

class OpenShiftAppException(OpenShiftException):
    """App not found."""
    pass

class OpenShiftNullDomainException(OpenShiftException):
    """User's domain hasn't been initialized."""
    pass


class OpenShift500Exception(OpenShiftException):
    """Internal Server Error"""
    pass

#### set this to True if we want to enable performance analysis
DOING_PERFORMANCE_ANALYSIS = False

global log


def config_logger():
    # create formatter
    formatter = logging.Formatter("%(levelname)s [%(asctime)s] %(message)s",
                                  "%H:%M:%S")
    logger = logging.getLogger("dump_logs")
    log_formatter = logging.Formatter(
        "%(name)s: %(asctime)s - %(levelname)s: %(message)s")

    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logging.DEBUG)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(stream_handler)
    return logger


def config_parser():
    # these are required options.
    parser.set_defaults(VERBOSE=False)
    parser.set_defaults(DEBUG=False)
    parser.add_option("-d", action="store_true", dest="DEBUG", help="enable DEBUG (default true)")
    #parser.add_option("-a", "--action", help="action you want to take (list|create|store)")
    parser.add_option("-i", "--ip", default="openshift.redhat.com", help="ip addaress of your devenv")
    parser.add_option("-v", action="store_true", dest="VERBOSE", help="enable VERBOSE printing")
    parser.add_option("-u", "--user", default=None, help="User name")
    parser.add_option("-p", "--password", default=None, help="RHT password")
    (options, args) = parser.parse_args()

    if options.user is None:
        options.user = os.getenv('OPENSHIFT_user_email')

    if options.password is None:
        options.password = os.getenv('OPENSHIFT_user_passwd')

    return options, args
log = config_logger()
parser = OptionParser()


# helper function for to measure timedelta.
def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        log.info("%r (%r, %r) %2.2f sec" % (method.__name__, args, kw, te-ts))
        return result, te-ts

    return timed


class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            return func
        else:
            return self.decorator(func)


class RestApi(object):
    """
    A base connection class to derive from.
    """

    host = '127.0.0.1'
    port = 443
    username = None
    password = <PASSWORD>
    headers = None
    response = None
    base_uri = None
    verbose = False
    debug = False

    def __init__(self, host=None, port=443, username=username, password=password,
                 debug=False, verbose=False):
        if host is not None:
            self.host = host

        if username:
            self.username = username

        if password:
            self.password = password

        if verbose:
            self.verbose = verbose

        self.debug = debug
        self.base_uri = "https://" + host + "/broker/rest"

    def _get_auth_headers(self, username=None, password=<PASSWORD>):
        if username:
            self.username = username

        if password:
            self.password = password

        return (self.username, self.password)

    def request(self, url, method, headers=None, params=None):
        """
        wrapper method for Requests' methods
        """
        if url.startswith("https://"):
            self.url = url  # self.base_uri + url
        else:
            self.url = self.base_uri + url
        log.debug("URL: %s" % self.url)
        auth = (self.username, self.password)  # self._get_auth_headers()

        if method:
            method = method.lower()
        method_call = getattr(requests, method)
        self.response = method_call(
            url=self.url, auth=auth, params=params,
            timeout=130, verify=False)
        try:
            raw_response = self.response.raw
        except Exception as e:
            print("-"*80, file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            print("-"*80, file=sys.stderr)
            raise e

        self.data = self.response.json

        # see https://github.com/kennethreitz/requests/blob/master/requests/status_codes.py
        if self.response.status_code == requests.codes.internal_server_error:
            raise OpenShift500Exception('Internal Server Error: %s' % self.data)

        if self.response.status_code == (200 or 201):
            print("-"*80, file=sys.stderr)
            log.debug("status:  %s" % self.response.status_code)
            #log.debug("msg: %s" % self.data()['messages'][0]['text'])
            # the raw_response is not available
            #log.debug("raw:  %s"%raw_response)
            print("-"*80, file=sys.stderr)
        return (self.response.status_code, self.data)


class Openshift(object):
    """
    wrappers class around REST API so use can use it with python
    """
    rest = None
    user = None
    passwd = <PASSWORD>

    def __init__(self, host, user=None, passwd=None, debug=False, verbose=False, logger=None):
        if user:
            self.user = user
        if passwd:
            self.passwd = <PASSWORD>
        if logger:
{'fraction_non_alphanumeric': 0.11972538513060951, 'fraction_numerical': 0.007032819825853985, 'mean_word_length': 2.596808190304125, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 18, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3173291', 'n_tokens_mistral': 3582, 'n_tokens_neox': 3453, 'n_words': 891}