Beispiel #1
0
    def execute_sql(self, *args, **kwargs):
        """Proxy to Labkey's Python API"""
        try:
            r = labkey.query.execute_sql(self._context, *args, **kwargs)
            self._log.debug('Found %d rows' % r['rowCount'])
            return r

        except ServerNotFoundError as e:
            self._log.debug('Invalid URL %r, username %r, or password' % (self._base_url, self._username))
            raise LabkeyException('Invalid URL, username, or password')

        except (QueryNotFoundError, RequestError) as e:
            self._log.debug('Invalid schema %r, or query %r' % (args[0], args[1]))
            raise LabkeyException('Invalid schema, or query')
Beispiel #2
0
    def download_file(self, destination, file_location, create=False, overwrite=False):
        response = self._session.get(self._construct_url('_webdav', self.project_name, '@files', file_location))
        self._log.debug('status_code %r' % (response.status_code))

        if response.status_code != 200:
            raise LabkeyException('Error HTTP Code %d' % response.status_code)

        if len(response.text) < 150:
            # Labkey Webdav return 200 even on errors
            # So we try to determine if the content represents an error response
            # Error response is JSON, with success, and status keys
            try:
                text = self._get_json(response.text)

                if 'success' in text and 'status' in text:
                    if text['success'] is False:

                        if text['status'] == 401:
                            raise AuthenticationException('Authentication failed')

                        elif text['status'] == 403:
                            raise AuthenticationException('Authorization failed')

                        elif text['status'] == 404:
                            raise LabkeyException('File not found on server')

                        else:
                            self._log.debug(response.text)

            except ValueError:
                pass

        if not os.path.isdir(destination):
            if create:
                os.makedirs(destination)
            else:
                raise LabkeyException(
                    'Destination directory %s does not exist, to create directory set create flag' % os.path.abspath(
                        destination))

        file_path = '%s' % os.path.join(destination, os.path.basename(file_location))
        if os.path.isfile(file_path):
            if not overwrite:
                raise LabkeyException(
                    'File %s already exists, to overwrite the file set overwrite flag' % os.path.abspath(file_path))

        with open(file_path, 'wb') as f:
            f.write(response.text)
Beispiel #3
0
    def _trigger_ms2_analysis(self, input_file, input_location, protocol_name, search_engine, run_search=True):
        params = {
            'path': input_location,
            'file': [os.path.basename(one_input_file) for one_input_file in input_file],
            'protocol': protocol_name,
            'runSearch': run_search,
            'Accept': 'application/json'
        }

        search_engine_map = {
            'xtandem': 'XTandem'
        }

        response = self._session.post(
            self._construct_url('ms2-pipeline', self.project_name, 'search%s.api' % search_engine_map[search_engine]),
            params=params)
        self._log.debug('status_code %s, text %s' % (response.status_code, response.text))

        if response.status_code == 401:
            raise AuthenticationException('Authentication failed')

        elif response.status_code == 403:
            raise AuthenticationException('Authorization failed')

        elif response.status_code == 404:
            raise LabkeyException('Either URL is invalid or the directory does not exist')
Beispiel #4
0
    def upload_file(self, destination, input_file, create=False, overwrite=False):
        # Sanity Checks
        file_exists(input_file)

        params = {
            'Accept': 'application/json',
        }

        file_exist = self.check_location_exists(os.path.join(destination, os.path.basename(input_file)))

        if overwrite is False and file_exist is True:
            raise LabkeyException('File already exists, try setting overwrite flag')

        if create is False and not self.check_location_exists(destination):
            raise LabkeyException('Either URL is invalid or the directory does not exist')

        response = self._session.put(
            self._construct_url('_webdav', self.project_name, '@files', destination, os.path.basename(input_file)),
            data=open(input_file, 'rb'),
            params=params
        )

        self._log.debug('status_code %s, text %s' % (response.status_code, response.text))

        if response.status_code != 207 and response.text:
            text = self._get_json(response.text)

            if text['success'] is False:
                if text['status'] == 208:
                    raise LabkeyException(text['exception'])

                elif text['status'] == 401:
                    raise AuthenticationException('Authentication failed')

                elif text['status'] == 403:
                    raise AuthenticationException('Authorization failed')

                elif text['status'] == 404:
                    if create:
                        self.create_directory(os.path.join('@files', destination))
                        self.upload_file(destination, input_file=input_file, create=False, overwrite=overwrite)

                    else:
                        raise LabkeyException('Either URL is invalid or the directory does not exist')

                else:
                    self._log.error(text)
Beispiel #5
0
    def download_other_file(self, destination, file_location, create=False, overwrite=False):
        response = self._session.get(
            self._construct_url(file_location % {'project-name': self.project_name}))
        self._log.debug('status_code %r' % (response.status_code))

        if response.status_code != 200:
            raise LabkeyException('Error HTTP Code %d' % response.status_code)

        if response.history:
            # Labkey Webdav return 200 even on errors
            # So we try to determine if the content represents an error response
            last = response.history[-1]

            if 300 <= last.status_code < 400 and (
                last.headers.get('location', None) and '/login.view?' in last.headers.get('location')):
                raise AuthenticationException('Authentication failed')

        if not os.path.isdir(destination):
            if create:
                os.makedirs(destination)
            else:
                raise LabkeyException(
                        'Destination directory %s does not exist, to create directory set create flag' % os.path.abspath(
                                destination))

        output_file = os.path.basename(file_location)

        if response.headers.get('content-disposition', None):
            output_file = response.headers['content-disposition'].strip()

            p = re.match('^filename\w*=\w*"(.*)";?.*$', output_file)

            if p:
                output_file = p.group(1)
            else:
                output_file = os.path.basename(file_location)

        file_path = os.path.join(destination, output_file)
        self._log.info('Downloading to filename %s' % file_path)
        if os.path.isfile(file_path):
            if not overwrite:
                raise LabkeyException(
                        'File %s already exists, to overwrite the file set overwrite flag' % os.path.abspath(file_path))

        with open(file_path, 'wb') as f:
            f.write(response.content)
Beispiel #6
0
    def create_directory(self, destination):
        params = {
            'Accept': 'application/json'
        }

        dest = ''
        last_status = False

        for d in destination.split('/'):
            response = self._session.request('MKCOL', self._construct_url('_webdav', self.project_name, dest, d),
                                             params=params)
            self._log.debug('status_code %s, text %s' % (response.status_code, response.text))
            dest = os.path.join(dest, d)

            if response.text:
                text = self._get_json(response.text)

                if text['success'] is False:
                    if text['status'] == 208:
                        raise LabkeyException(text['exception'])

                    elif text['status'] == 401:
                        raise AuthenticationException('Authentication failed')

                    elif text['status'] == 403:
                        raise AuthenticationException('Authorization failed')

                    elif text['status'] == 404:
                        raise LabkeyException(text['exception'])

                    else:
                        self._log.debug(response.text)

            else:
                last_status = True

        if last_status is False:
            raise LabkeyException('Directory creation failed')
Beispiel #7
0
 def decorator(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except MissingSchema as e:
         raise LabkeyException(e)