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

"""
 Copyright 2016 <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

__author__ = 'opiske'

import ConfigParser
import csv
import json
import logging
import optparse
import sys
from StringIO import StringIO

import requests
from requests.auth import HTTPBasicAuth

fmt_console = '[%(asctime)s] [%(levelname)s] %(name)s :: %(message)s'
datefmt_iso = '%Y-%m-%d %H:%M:%S,'

console_formatter = logging.Formatter(fmt_console, datefmt=datefmt_iso)

console_handler = logging.StreamHandler()  # Python 2.6
console_handler.setLevel(logging.ERROR)  # setting console level
console_handler.setFormatter(console_formatter)

logging.getLogger().addHandler(console_handler)
logging.getLogger().setLevel(logging.NOTSET)

logger = logging.getLogger(__name__)
config = ConfigParser.RawConfigParser();
in_opts = {};


def print_errors(http_response):
    logger.error("Error: %s" % http_response.status_code)
    logger.error("Text: %s" % http_response.content)

def read_param(section, name, default=None):
    ret = in_opts[name]
    if ret is None:
        try:
            ret = config.get(section, name)
            if ret is None and default is not None:
                ret = default
        except:
            ret = None

    return ret;


def call_service(req_url, request_json, force_update=False, session=None, is_update=False):
    logger.debug("Connecting to %s" % (req_url))

    headers = {'Content-type': 'application/json'}

    username = read_param("database", "username")
    if username is not None:
        password = read_param("database", "password")

    if session is None:
        session = requests.session()

    if is_update and not force_update:
        answer = session.put(req_url, headers=headers, data=request_json, verify=False,
                               auth=HTTPBasicAuth(username, password))
    else:
        answer = session.post(req_url, headers=headers, data = request_json, verify=False,
                               auth=HTTPBasicAuth(username, password))

    if answer.status_code < 200 or answer.status_code >= 205:
        print_errors(answer)
        return 3

    return 0


def call_service_for_check(req_url, session=None):
    logger.debug("Connecting to %s" % (req_url))

    headers = {'Content-type': 'application/json'}

    username = read_param("database", "username")
    if username is not None:
        password = read_param("database", "password")

    if session is None:
        session = requests.session()

    answer = session.get(req_url, headers=headers, verify=False, auth=HTTPBasicAuth(username, password))
    return answer


def register():
    base_url = read_param("database", "url")
    in_sut_name = read_param("sut", "sut_name")
    in_sut_key = read_param("sut", "sut_key")
    in_sut_version = read_param("sut", "sut_version")

    if base_url is None:
        logger.error("Base URL is required")

        return 1

    if in_sut_name is None or in_sut_name == "":
        logger.error("The SUT name is required")
        return 1

    if in_sut_key is None or in_sut_key == "":
        logger.error("The SUT key is required")
        return 1

    if in_sut_version is None or in_sut_version == "":
        logger.error("The SUT version is required")
        return 1

    # TODO: this is not good nor flexible. Fix it!
    filtered_version = in_sut_version.replace(".", "").replace(" ", "").replace("-", "").replace("_", "")
    sut_id = "%s-%s" % (in_sut_key, filtered_version)

    request_data = {
        "sut_name": in_sut_name,
        "sut_key": in_sut_key,
        "sut_version": in_sut_version,
    }

    logger.info("Request: %s" % (request_data))

    request_json = StringIO()
    json.dump(request_data, request_json)
    logger.info("JSON: %s" % (request_json.getvalue(),))

    is_update = in_opts["update"]
    req_url = "%s/sut/messaging/%s" % (base_url, sut_id)
    call_service(req_url, request_json.getvalue(), is_update=is_update)

    return 0

def configure_latency_mapping(session=None):
    base_url = read_param("database", "url")
    in_sut_key = read_param("sut", "sut_key")

    answer = call_service_for_check(("%s/%s/_mapping" % (base_url, in_sut_key)), session=session)
    if answer.status_code == 404:
        req_url = "%s/%s" % (base_url, in_sut_key)
        request_json = '{ "mappings": { "latency": { "properties": { "creation": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS"} } } } }'
    else:
        req_url = "%s/%s/_mapping/latency" % (base_url, in_sut_key)
        request_json = '{ "properties": { "creation": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS"} } }'

    is_update = in_opts["update"]
    ret = call_service(req_url, request_json, force_update=True, session=session, is_update=is_update)
    if ret != 0:
        logger.error("Unable to configure the mappings for latency")

def configure_throughput_mapping(session=None):
    base_url = read_param("database", "url")
    in_sut_key = read_param("sut", "sut_key")

    answer = call_service_for_check(( "%s/%s/_mapping" % (base_url, in_sut_key)), session=session)
    if answer.status_code == 404:
        req_url = "%s/%s" % (base_url, in_sut_key)
        request_json = '{ "mappings": { "throughput": { "properties": { "ts": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss"} } } } }'
    else:
        req_url = "%s/%s/_mapping/througput" % (base_url, in_sut_key)
        request_json = '{ "properties": { "ts": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss"} } }'

    is_update = in_opts["update"]
    ret = call_service(req_url, request_json, force_update=True, session=session, is_update=is_update)
    if ret != 0:
        logger.error("Unable to configure the mappings for throughput")



def count_lines(datafile):
    i = 0
    for i, l in enumerate(datafile):
      pass

    datafile.seek(0)
    return i + 1

def validate_parameters():
    base_url = read_param("database", "url")
    in_file_name = in_opts["filename"]
    in_sut_name = read_param("sut", "sut_name")
    in_sut_key = read_param("sut", "sut_key")
    in_sut_version = read_param("sut", "sut_version")
    in_test_run = read_param("test", "test_run")
    in_direction = in_opts["msg_direction"]

    if base_url is None:<commit_msg>FIX: change the sut_version field to not_analyzed<commit_after>#!/usr/bin/env python

"""
 Copyright 2016 <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

__author__ = 'opiske'

import ConfigParser
import csv
import json
import logging
import optparse
import sys
from StringIO import StringIO

import requests
from requests.auth import HTTPBasicAuth

fmt_console = '[%(asctime)s] [%(levelname)s] %(name)s :: %(message)s'
datefmt_iso = '%Y-%m-%d %H:%M:%S,'

console_formatter = logging.Formatter(fmt_console, datefmt=datefmt_iso)

console_handler = logging.StreamHandler()  # Python 2.6
console_handler.setLevel(logging.ERROR)  # setting console level
console_handler.setFormatter(console_formatter)

logging.getLogger().addHandler(console_handler)
logging.getLogger().setLevel(logging.NOTSET)

logger = logging.getLogger(__name__)
config = ConfigParser.RawConfigParser();
in_opts = {};


def print_errors(http_response):
    logger.error("Error: %s" % http_response.status_code)
    logger.error("Text: %s" % http_response.content)

def read_param(section, name, default=None):
    ret = in_opts[name]
    if ret is None:
        try:
            ret = config.get(section, name)
            if ret is None and default is not None:
                ret = default
        except:
            ret = None

    return ret;


def call_service(req_url, request_json, force_update=False, session=None, is_update=False):
    logger.debug("Connecting to %s" % (req_url))

    headers = {'Content-type': 'application/json'}

    username = read_param("database", "username")
    if username is not None:
        password = read_param("database", "password")

    if session is None:
        session = requests.session()

    if is_update and not force_update:
        answer = session.put(req_url, headers=headers, data=request_json, verify=False,
                               auth=HTTPBasicAuth(username, password))
    else:
        answer = session.post(req_url, headers=headers, data = request_json, verify=False,
                               auth=HTTPBasicAuth(username, password))

    if answer.status_code < 200 or answer.status_code >= 205:
        print_errors(answer)
        return 3

    return 0


def call_service_for_check(req_url, session=None):
    logger.debug("Connecting to %s" % (req_url))

    headers = {'Content-type': 'application/json'}

    username = read_param("database", "username")
    if username is not None:
        password = read_param("database", "password")

    if session is None:
        session = requests.session()

    answer = session.get(req_url, headers=headers, verify=False, auth=HTTPBasicAuth(username, password))
    return answer


def register():
    base_url = read_param("database", "url")
    in_sut_name = read_param("sut", "sut_name")
    in_sut_key = read_param("sut", "sut_key")
    in_sut_version = read_param("sut", "sut_version")

    if base_url is None:
        logger.error("Base URL is required")

        return 1

    if in_sut_name is None or in_sut_name == "":
        logger.error("The SUT name is required")
        return 1

    if in_sut_key is None or in_sut_key == "":
        logger.error("The SUT key is required")
        return 1

    if in_sut_version is None or in_sut_version == "":
        logger.error("The SUT version is required")
        return 1

    # TODO: this is not good nor flexible. Fix it!
    filtered_version = in_sut_version.replace(".", "").replace(" ", "").replace("-", "").replace("_", "")
    sut_id = "%s-%s" % (in_sut_key, filtered_version)

    request_data = {
        "sut_name": in_sut_name,
        "sut_key": in_sut_key,
        "sut_version": in_sut_version,
    }

    logger.info("Request: %s" % (request_data))

    request_json = StringIO()
    json.dump(request_data, request_json)
    logger.info("JSON: %s" % (request_json.getvalue(),))

    is_update = in_opts["update"]
    req_url = "%s/sut/messaging/%s" % (base_url, sut_id)
    call_service(req_url, request_json.getvalue(), is_update=is_update)

    return 0

def configure_latency_mapping(session=None):
    base_url = read_param("database", "url")
    in_sut_key = read_param("sut", "sut_key")

    answer = call_service_for_check(("%s/%s/_mapping" % (base_url, in_sut_key)), session=session)
    if answer.status_code == 404:
        req_url = "%s/%s" % (base_url, in_sut_key)
        request_json = '{ "mappings": { "latency": { "properties": { "creation": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS"}, "sut_version": { "type": "string", "index": "not_analyzed"  } } } } }'
    else:
        req_url = "%s/%s/_mapping/latency" % (base_url, in_sut_key)
        request_json = '{ "properties": { "creation": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS"}, "sut_version": { "type": "string", "index": "not_analyzed" } } }'

    is_update = in_opts["update"]
    ret = call_service(req_url, request_json, force_update=True, session=session, is_update=is_update)
    if ret != 0:
        logger.error("Unable to configure the mappings for latency")

def configure_throughput_mapping(session=None):
    base_url = read_param("database", "url")
    in_sut_key = read_param("sut", "sut_key")

    answer = call_service_for_check(( "%s/%s/_mapping" % (base_url, in_sut_key)), session=session)
    if answer.status_code == 404:
        req_url = "%s/%s" % (base_url, in_sut_key)
        request_json = '{ "mappings": { "throughput": { "properties": { "ts": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss"}, "sut_version": { "type": "string", "index": "not_analyzed" } } } } }'
    else:
        req_url = "%s/%s/_mapping/througput" % (base_url, in_sut_key)
        request_json = '{ "properties": { "ts": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss"}, "sut_version": { "type": "string", "index": "not_analyzed" } } }'

    is_update = in_opts["update"]
    ret = call_service(req_url, request_json, force_update=True, session=session, is_update=is_update)
    if ret != 0:
        logger.error("Unable to configure the mappings for throughput")



def count_lines(datafile):
    i = 0
    for i, l in enumerate(datafile):
      pass

    datafile.seek(0)
    return i + 1

def validate_parameters():
    base_url = read_param("database", "url")
    in_file_name = in_opts["filename"]
    in_sut_name = read_param("sut", "sut_name")
    in_sut_key = read_param("sut", "sut_key")
    in_sut_version = read_param("sut", "sut_version")
    in_test_run = read_param("test", "test_run")
    in_direction = in_opts["msg_direction"]

    if base_url is None:
{'fraction_non_alphanumeric': 0.13417023438066902, 'fraction_numerical': 0.004934329874464843, 'mean_word_length': 3.612449799196787, 'pattern_counts': {'":': 64, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1326396', 'n_tokens_mistral': 4635, 'n_tokens_neox': 4449, 'n_words': 1105}