def db_add_media_xml(config, db_media_xml_doc, username, password):  
    deviceElement = db_media_xml_doc.getElementsByTagName('device')[0]
    session_id = deviceElement.getAttribute('sessionId')
    device_code = deviceElement.getAttribute('code')
    base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
    authheader =  "Basic %s" % base64string
    headers = {'Authorization': authheader}
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
   
    if len(deviceElement.childNodes) == 0:
        print 'Internal Error: No session-media xml nodes generated.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    
    for mediaElem in deviceElement.childNodes:
        if mediaElem.nodeType == xml.dom.Node.ELEMENT_NODE:
            element_xml = str(mediaElem.toxml())
            #Hack to put id as the first attribute
            element_xml = string.replace(element_xml, '_id="', 'id="')
            params = urllib.urlencode({'sessionId': session_id, 'deviceCode': device_code, 'mediaXML': element_xml})
            try:
                conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/import-media-element.xql?'+params, None, headers)
                response = conn.getresponse()
                data = response.read()
                if '<exception>' in data:
                    print ltoUtil.get_xquery_exception_msg(data)
                    print ltoUtil.get_script_name()+' script terminated.'
                    return False
                elif response.status == 401 and response.reason == 'Unauthorized':
                    print 'Authentication Failed.'
                    return False
            except Exception, e:
                print 'Unable to connect to database'
                return False
def session_device_check(config, session_id, device_code):
    if not ltoUtil.valid_chars(session_id):
        print 'Invalid characters used in session id.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    if not ltoUtil.valid_chars(device_code):
        print 'Invalid characters used in device_code.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    media_exists_for_session_device_qry = 'exists(/session[@id="'+session_id+'"]//device[@code="'+device_code+'"]/*)'
    if not db_session_id_exists(config, session_id):
        print 'session id: '+session_id+' does not yet exist.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    if not db_device_code_exists(config, device_code):
        print 'device code: '+device_code+' does not exist.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/data', media_exists_for_session_device_qry)   
    if ltoUtil.get_parsed_xquery_value(xquery_result) == ['true']:
        print 'At least one media item has already been associated with session: '+session_id+' and device: '+device_code
        print
        print 'To see the associated media items for this session open the following link in your browser:'
        print 'http://'+ltoUtil.get_host_port(config)+ltoUtil.get_transcript_url(config)+'/data?_query=/session[@id="'+session_id+'"]//mediaMetadata'
        print
        cont = raw_input('Are you sure you want to continue? [y/n]: ')
        if cont == 'y':
            return 
        else:
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
def create_referenced_items_file(config, session_id, device_code):
    tarMeta = open(os.path.join(ltoUtil.get_tar_build_dir(config), session_id+'-'+device_code+'-referenced-items.xml'),'w')
    params = urllib.urlencode({'sessionIds':session_id, 'deviceCodes':device_code})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-referenced-items.xql?'+params, None, {})
        response = conn.getresponse()
        tarMeta.writelines(response.read())
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def get_session_full_name(config, sessionId):
    params = urllib.urlencode({'sessionId':sessionId})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-session-full-name.xql?'+params, None, {})
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def get_item_vectors(config, items, domain):
    bs = int(ltoUtil.get_blocksize(config))
    ids = string.join(items, ',')
    params = urllib.urlencode({'domain':domain, 'ids':ids})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('POST', ltoUtil.get_lto_url(config)+'/xquery/get-file-lto-vector.xql?'+params, None, {})
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def db_get_next_media_id(session_id, domain, config):
    event_type = session_id[:session_id.find('-')]
    params = urllib.urlencode({'domain': domain, 'eventType': event_type})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-next-media-id.xql?'+params, None, {})
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
        else:
            return data
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def db_import_tape_xml(config, tape_xml_doc):
    tape_xml = str(tape_xml_doc.toxml())
    print '\nImporting tape index to database:\n'
    username = raw_input('username: '******'password: '******'%s:%s' % (username, password)))
    authheader =  "Basic %s" % base64string
    headers = {"Authorization": authheader, "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    params = urllib.urlencode({'tapeXML': tape_xml})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('POST', ltoUtil.get_lto_url(config)+'/xquery/import-tape-element.xql', params, headers)
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print 'Unable to update database.'
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
        elif 'HTTP ERROR: 404' in data:
            print '\nHTTP ERROR: 404'
            print data[data.find('<title>')+7:data.find('</title>')]
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
        elif response.status == 401 and response.reason == 'Unauthorized':
            print 'Authentication Failed.'
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
        else:
            print '\nDatabase updated (tape id: '+data+').'
    except httplib.HTTPException, e:
        print e.msg
        print 'Unable to connect to database'
        print ltoUtil.get_script_name()+' script terminated.'
        conn.close()
        sys.exit(2)