Project

General

Profile

1
# TNRS
2

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

    
8
import exc
9
import profiling
10
import streams
11
import strings
12

    
13
# Config
14
initial_pause = 0.35 # sec
15
pause_growth_factor = 1.3
16
max_pause = 30*60 # sec; = 30 min; TNRS sometimes freezes for ~10 min
17
assert initial_pause <= max_pause
18
max_names = 5000 # according to http://tnrs.iplantcollaborative.org/TNRSapp.html
19
max_names = 500 # the maximum above crashes the TNRS server
20

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

    
57
class InvalidResponse(Exception): pass
58

    
59
def gwt_encode(str_):
60
    return strings.esc_quotes(strings.json_encode(str_), '|', quote_esc='\!')
61

    
62
def parse_response(name, pattern, str_, response, response_info):
63
    match = re.match(pattern, str_)
64
    if not match:
65
        raise InvalidResponse('Invalid '+name+' response:\n'+response_info+'\n'
66
            +response)
67
    return match.groups()
68

    
69
def tnrs_request(names, debug=False):
70
    '''
71
    Note that names containing only whitespace characters (after gwt_encode())
72
    are ignored by TNRS and do not receive a response row. Thus, you should
73
    always match up the Name_submitted returned by TNRS with the actual
74
    submitted name to determine the corresponding TNRS response row.
75
    '''
76
    name_ct = len(names)
77
    assert name_ct <= max_names
78
    
79
    # Logging
80
    def debug_log(label, str_=''):
81
        if debug: sys.stderr.write('\n'+label+':\n'+str_+'\n')
82
    
83
    ## HTTP
84
    headers = initial_headers.copy() # don't modify global constant!
85
    
86
    def do_request(request):
87
        debug_log('request', str(request))
88
        response = urllib2.urlopen(urllib2.Request(url, request, headers))
89
        response_str = streams.read_all(response)
90
        response_info = str(response.info())
91
        debug_log('response info', response_info)
92
        debug_log('response str', response_str)
93
        return response_str, response_info
94
    
95
    def do_repeated_request(request):
96
        pause = initial_pause
97
        total_pause = 0
98
        while True:
99
            total_pause += pause
100
            if total_pause > max_pause: raise # error is not temporary
101
            debug_log('total_pause', str(total_pause)+'s')
102
            time.sleep(pause) # wait for job to complete
103
            
104
            try: return do_request(request)
105
            except urllib2.HTTPError: pass # try again
106
            pause *= pause_growth_factor
107
    
108
    profiler = profiling.ItersProfiler(start_now=True, iter_text='name')
109
    try:
110
        debug_log('Submit')
111
        request = submission_request_template.replace('[names]',
112
            r'\\n'.join(map(gwt_encode, names))) # double-escape \n
113
        response, response_info = do_request(request)
114
        key, = parse_response('submission', submission_response_pattern, response,
115
            response, response_info)
116
        debug_log('key', key)
117
        key_enc = gwt_encode(key)
118
        
119
        debug_log('Retrieve')
120
        request = retrieval_request_template.replace('[key]', key_enc)
121
        response, response_info = do_repeated_request(request)
122
        parse_response('retrieval', retrieval_response_pattern, response, response,
123
            response_info)
124
        session_id, = parse_response('retrieval info',
125
            retrieval_response_info_pattern, response_info, response, response_info)
126
        debug_log('session_id', session_id)
127
        headers['Cookie'] = 'JSESSIONID='+session_id
128
        
129
        # The output of the retrieve step is unusable because the array has
130
        # different lengths depending on the taxonomic ranks present in the provided
131
        # taxon name. The extra download step is therefore necessary.
132
        
133
        debug_log('Prepare download')
134
        request = download_request_template.replace('[key]', key_enc)
135
        response, response_info = do_request(request)
136
        csv_url, = parse_response('download', download_response_pattern, response,
137
            response, response_info)
138
        csv_url += download_url_suffix
139
        debug_log('csv_url', csv_url)
140
        
141
        debug_log('Download')
142
        response = urllib2.urlopen(urllib2.Request(csv_url))
143
        debug_log('response info', str(response.info()))
144
        return response
145
    finally:
146
        profiler.stop(name_ct)
147
        sys.stderr.write(profiler.msg()+'\n')
148

    
149
def repeated_tnrs_request(names, debug=False, **kw_args):
150
    for try_num in xrange(2):
151
        try: return tnrs_request(names, debug, **kw_args)
152
        except InvalidResponse, e:
153
            exc.print_ex(e, detail=False)
154
            debug = True
155
            # try again with debug turned on
156
    raise # error is not temporary
(34-34/41)