# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# def readpar(parameter, alt=False, version=0, queuename=None):
#     """ Read 'parameter' from queuedata via SiteInformation class """
# 
#     from SiteInformation import SiteInformation
#     si = SiteInformation()
# 
#     return si.readpar(parameter, alt=alt, version=version, queuename=queuename)
# 
# Path: FileHandling.py
# def readJSON(file_name):
#     """ Read a dictionary from a JSON file """
# 
#     dictionary = {}
#     from json import load
#     f = openFile(file_name, 'r')
#     if f:
#         # Read the dictionary
#         try:
#             dictionary = load(f)
#         except Exception, e:
#             tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e))
#         else:
#             f.close()
# 
#     return dictionary
# 
# def writeJSON(file_name, dictionary):
#     """ Write the dictionary to a JSON file """
# 
#     status = False
# 
#     from json import dump
#     try:
#         fp = open(file_name, "w")
#     except Exception, e:
#         tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e))
#     else:
#         # Write the dictionary
#         try:
#             dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': '))
#         except Exception, e:
#             tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e))
#         else:
#             tolog("Wrote dictionary to file %s" % (file_name))
#             status = True
#         fp.close()
# 
#     return status


import os
import commands
from pUtil import tolog, readpar
from FileHandling import readJSON, writeJSON
            from json import loads
        redirector = "root://" + redirector
        tolog("Updated redirector for missing protocol: %s" % (redirector))
    if not redirector.endswith("/"):
        redirector = redirector + "/"
        tolog("Updated redirector for missing trailing /: %s" % (redirector))

    # Protect against triple slashes
    redirector = redirector.replace('///','//')

    return redirector

def _getFAXRedirectors(computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'):
    """ Get the FAX redirectors via curl or JSON """

    fax_redirectors_dictionary = {}
    file_name = "fax_redirectors.json"
    if os.path.exists(file_name):
        # Read back the FAX redirectors from file
        fax_redirectors_dictionary = readJSON(file_name)

    if fax_redirectors_dictionary == {}:
        # Attempt to get fax redirectors from Ilija Vukotic's google server
        cmd = "curl --silent --connect-timeout 100 --max-time 120 -X POST --data \'computingsite=%s&sourcesite=%s&pandaID=%s\' %s" % (computingSite, sourceSite, pandaID, url)
        tolog("Trying to get FAX redirectors: %s" % (cmd))
        dictionary_string = commands.getoutput(cmd)
        if dictionary_string != "":
            # try to convert to a python dictionary
            try:
                fax_redirectors_dictionary = loads(dictionary_string)
            except Exception, e:

# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# def readpar(parameter, alt=False, version=0, queuename=None):
#     """ Read 'parameter' from queuedata via SiteInformation class """
# 
#     from SiteInformation import SiteInformation
#     si = SiteInformation()
# 
#     return si.readpar(parameter, alt=alt, version=version, queuename=queuename)
# 
# Path: FileHandling.py
# def readJSON(file_name):
#     """ Read a dictionary from a JSON file """
# 
#     dictionary = {}
#     from json import load
#     f = openFile(file_name, 'r')
#     if f:
#         # Read the dictionary
#         try:
#             dictionary = load(f)
#         except Exception, e:
#             tolog("!!WARNING!!2332!! Failed to read dictionary from file %s: %s" % (file_name, e))
#         else:
#             f.close()
# 
#     return dictionary
# 
# def writeJSON(file_name, dictionary):
#     """ Write the dictionary to a JSON file """
# 
#     status = False
# 
#     from json import dump
#     try:
#         fp = open(file_name, "w")
#     except Exception, e:
#         tolog("!!WARNING!!2323!! Failed to open file %s: %s" % (file_name, e))
#     else:
#         # Write the dictionary
#         try:
#             dump(dictionary, fp, sort_keys=True, indent=4, separators=(',', ': '))
#         except Exception, e:
#             tolog("!!WARNING!!2324!! Failed to write dictionary to file %s: %s" % (file_name, e))
#         else:
#             tolog("Wrote dictionary to file %s" % (file_name))
#             status = True
#         fp.close()
# 
#     return status


# Path: FAXTools.py
import os
import commands
from pUtil import tolog, readpar
from FileHandling import readJSON, writeJSON
            from json import loads

        redirector = "root://" + redirector
        tolog("Updated redirector for missing protocol: %s" % (redirector))
    if not redirector.endswith("/"):
        redirector = redirector + "/"
        tolog("Updated redirector for missing trailing /: %s" % (redirector))

    # Protect against triple slashes
    redirector = redirector.replace('///','//')

    return redirector

def _getFAXRedirectors(computingSite, sourceSite, pandaID, url='http://waniotest.appspot.com/SiteToFaxEndpointTranslator'):
    """ Get the FAX redirectors via curl or JSON """

    fax_redirectors_dictionary = {}
    file_name = "fax_redirectors.json"
    if os.path.exists(file_name):
        # Read back the FAX redirectors from file
        fax_redirectors_dictionary = readJSON(file_name)

    if fax_redirectors_dictionary == {}:
        # Attempt to get fax redirectors from Ilija Vukotic's google server
        cmd = "curl --silent --connect-timeout 100 --max-time 120 -X POST --data \'computingsite=%s&sourcesite=%s&pandaID=%s\' %s" % (computingSite, sourceSite, pandaID, url)
        tolog("Trying to get FAX redirectors: %s" % (cmd))
        dictionary_string = commands.getoutput(cmd)
        if dictionary_string != "":
            # try to convert to a python dictionary
            try:
                fax_redirectors_dictionary = loads(dictionary_string)
            except Exception, e:

                tolog("!!WARNING!!4444!! Failed to parse fax redirector json: %s" % (e))