Project

General

Profile

1
# TNRS
2

    
3
import re
4
import sys
5
import time
6
import urllib2
7

    
8
import streams
9

    
10
# Config
11
initial_pause = 0.35 # sec
12
pause_growth_factor = 1.3
13
max_pause = 600 # sec; = 10 min
14
assert initial_pause <= max_pause
15
max_taxons = 5000# according to http://tnrs.iplantcollaborative.org/TNRSapp.html
16
max_tries = 5
17

    
18
# Protocol params
19
url_base = 'http://tnrs.iplantcollaborative.org/tnrsdemo/'
20
url = url_base+'search'
21
initial_headers = {
22
    'Content-Type': 'text/x-gwt-rpc; charset=utf-8',
23
    'X-GWT-Module-Base': url_base,
24
    'X-GWT-Permutation': '574AA16D15D917C7704646FD92AFF6B3',
25
}
26
submission_request_template = ('7|0|7|'+url_base+
27
'||org.iplantc.tnrs.demo.client.SearchService|doSearch|\
28
java.lang.String/2004016611|{"sources":"gcc,tropicos,usda", "names":"[taxons]"\
29
, "type":"matching", "taxonomic":"true", "classification":"tropicos", \
30
"match_to_rank":"true"}|0.05|1|2|3|4|2|5|5|6|7|')
31
submission_response_pattern = r'^//OK\[1,\["(\w+)"\],0,7\]$'
32
retrieval_request_template = ('7|0|15|'+url_base+
33
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService\
34
|getRemoteData|com.extjs.gxt.ui.client.data.PagingLoadConfig|\
35
java.lang.String/2004016611|com.extjs.gxt.ui.client.data.BasePagingLoadConfig/\
36
2011366567|com.extjs.gxt.ui.client.data.RpcMap/3441186752|sortField|sortDir|\
37
com.extjs.gxt.ui.client.Style$SortDir/640452531|offset|java.lang.Integer/\
38
3438268394|limit|{"email":"tnrs@lka5jjs.orv", "key":"[key]", \
39
"taxonomic_constraint":"false", "source_sorting":"false", "first":"false"}\
40
|1|2|3|4|2|5|6|7|0|1|8|4|9|0|10|11|0|12|13|0|14|13|100|15|')
41
retrieval_response_pattern = '^//OK\[.*?\["com.extjs.gxt.ui.client.data.\
42
BasePagingLoadResult/496878394","java.util.ArrayList/4159755760","org.iplantc.\
43
tnrs.demo.shared.BeanTNRSEntry/1039545748",".*"\],0,7\]$'
44
retrieval_response_info_pattern = r'(?ms).*^Set-Cookie: JSESSIONID=(\w+);'
45
download_request_template = ('7|0|6|'+url_base+
46
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService|\
47
downloadRemoteResults|java.lang.String/2004016611|{"name":"tnrs_results.txt", \
48
"mode":"Best", "type":"Detailed", "encoding":"utf8", "dirty":"false", \
49
"sources":"false", "taxonomic":"false", "email":"tnrs@lka5jjs.orv", \
50
"key":"[key]"}|1|2|3|4|1|5|6|')
51
download_response_pattern = '^//OK\[1,\["(.*)"\],0,7\]$'
52
download_url_suffix = '&name=tnrs_results.txt&encoding=utf8'
53

    
54
class InvalidResponse(Exception): pass
55

    
56
def gwt_encode(str_): return re.sub(r'[^\w.() -]+', r' ', str_)
57

    
58
def parse_response(name, pattern, response):
59
    match = re.match(pattern, response)
60
    if not match: raise InvalidResponse('Invalid '+name+' response:\n'+response)
61
    return match.groups()
62

    
63
def tnrs_request(taxons, debug=False):
64
    assert len(taxons) <= max_taxons
65
    
66
    # Logging
67
    def debug_log(label, str_=''):
68
        if debug: sys.stderr.write('\n'+label+':\n'+str_+'\n')
69
    
70
    ## HTTP
71
    headers = initial_headers
72
    
73
    def do_request(request):
74
        debug_log('request', str(request))
75
        response = urllib2.urlopen(urllib2.Request(url, request, headers))
76
        response_str = streams.read_all(response)
77
        response_info = str(response.info())
78
        debug_log('response info', response_info)
79
        debug_log('response str', response_str)
80
        return response_str, response_info
81
    
82
    def do_repeated_request(request):
83
        pause = initial_pause
84
        total_pause = 0
85
        while True:
86
            total_pause += pause
87
            if total_pause > max_pause: raise # error is not temporary
88
            debug_log('total_pause', str(total_pause)+'s')
89
            time.sleep(pause) # wait for job to complete
90
            
91
            try: return do_request(request)
92
            except urllib2.HTTPError: pass # try again
93
            pause *= pause_growth_factor
94
    
95
    debug_log('Submit')
96
    request = submission_request_template.replace('[taxons]',
97
        r'\\n'.join(map(gwt_encode, taxons))) # double-escape \n
98
    response, response_info = do_request(request)
99
    key, = parse_response('submission', submission_response_pattern, response)
100
    debug_log('key', key)
101
    key_enc = gwt_encode(key)
102
    
103
    debug_log('Retrieve')
104
    request = retrieval_request_template.replace('[key]', key_enc)
105
    response, response_info = do_repeated_request(request)
106
    parse_response('retrieval', retrieval_response_pattern, response)
107
    session_id, = parse_response('retrieval info',
108
        retrieval_response_info_pattern, response_info)
109
    debug_log('session_id', session_id)
110
    headers['Cookie'] = 'JSESSIONID='+session_id
111
    
112
    # The output of the retrieve step is unusable because the array has
113
    # different lengths depending on the taxonomic ranks present in the provided
114
    # taxon name. The extra download step is therefore necessary.
115
    
116
    debug_log('Prepare download')
117
    request = download_request_template.replace('[key]', key_enc)
118
    response, response_info = do_request(request)
119
    csv_url, = parse_response('download', download_response_pattern, response)
120
    csv_url += download_url_suffix
121
    debug_log('csv_url', csv_url)
122
    
123
    debug_log('Download')
124
    response = urllib2.urlopen(urllib2.Request(csv_url))
125
    debug_log('response info', str(response.info()))
126
    return response
127

    
128
def repeated_tnrs_request(taxons, debug=False, **kw_args):
129
    for try_num in xrange(max_tries):
130
        try: return tnrs_request(taxons, debug, **kw_args)
131
        except InvalidResponse:
132
            debug = True # next time, output protocol info for debugging
133
            # try again
134
    raise # error is not temporary
(34-34/41)