def main():
    powma=PowerManagementAndroid()
    powm=PowerManager()
    form=cgi.FieldStorage()
    if 'xml' not in form:
        raise InvalidXMLException('No xml request', InvalidXMLException.CALLED_FROM_BROWSER)
    req=ET.fromstring(form['xml'].value)
    el_authentication_list = req.findall('authentication')
    if len(el_authentication_list) == 0:
        raise InvalidXMLException('Post might be called from browser',\
         InvalidXMLException.AUTH_ERROR)
    el_authentication = el_authentication_list[0]
    sas = SimpleAuthenticationRequest(el_authentication,str(random()).split('.')[1])
    sas.doTransaction()
    el_pair = req.findall('pair')[0]
    req_key=el_pair.find('key')
    req_value=el_pair.find('value')
    if (req_key.text=='def://power_management'):
        if (req_value.text=='default'):
            response = powma.getDefaultView()
        else:
            raise Exception
    elif (req_key.text=='powma://power_list'):
        if (req_value.text=='Restart'):
            response = powma.getSuccessView('Restarting')
            powm.execute_command(power_management.RESTART)
        elif (req_value.text=='Shut down'):
            response = powma.getSuccessView('Shutting down')
            powm.execute_command(power_management.POWEROFF)
        else:
            raise Exception
    else:
        raise Exception
    
    composeXMLDocument(response.getroot())
    req_key=el_pair.find('key')
    req_value=el_pair.find('value')
    if (req_key.text=='def://power_management'):
        if (req_value.text=='default'):
            response = powma.getDefaultView()
        else:
            raise Exception
    elif (req_key.text=='powma://power_list'):
        if (req_value.text=='Restart'):
            response = powma.getSuccessView('Restarting')
            powm.execute_command(power_management.RESTART)
        elif (req_value.text=='Shut down'):
            response = powma.getSuccessView('Shutting down')
            powm.execute_command(power_management.POWEROFF)
        else:
            raise Exception
    else:
        raise Exception
    
    composeXMLDocument(response.getroot())
#testing
if __name__ == '__main__':
    try:
        main()        
    except InvalidXMLException as ixe:
        r=Response(0)
        r.buildResponse(ixe.ex_code)     
        composeXMLDocument(r.xml)