Handles <start_scan> command.

        @return: Response string for <start_scan> command.
196890
def handle_start_scan_command(self, scan_et):
        

        target_str = scan_et.attrib.get('target')
        ports_str = scan_et.attrib.get('ports')
        # For backward compatibility, if target and ports attributes are set,
        # <targets> element is ignored.
        if target_str is None or ports_str is None:
            target_list = scan_et.find('targets')
            if target_list is None or not target_list:
                raise OSPDError('No targets or ports', 'start_scan')
            else:
                scan_targets = self.process_targets_element(target_list)
        else:
            scan_targets = []
            for single_target in target_str_to_list(target_str):
                scan_targets.append([single_target, ports_str, ''])

        scan_id = scan_et.attrib.get('scan_id')
        if scan_id is not None and scan_id != '' and not valid_uuid(scan_id):
            raise OSPDError('Invalid scan_id UUID', 'start_scan')

        try:
            parallel = int(scan_et.attrib.get('parallel', '1'))
            if parallel < 1 or parallel > 20:
                parallel = 1
        except ValueError:
            raise OSPDError('Invalid value for parallel scans. '
                            'It must be a number', 'start_scan')

        scanner_params = scan_et.find('scanner_params')
        if scanner_params is None:
            raise OSPDError('No scanner_params element', 'start_scan')

        params = self._preprocess_scan_params(scanner_params)

        # VTS is an optional element. If present should not be empty.
        vt_selection = {}
        scanner_vts = scan_et.find('vt_selection')
        if scanner_vts is not None:
            if not scanner_vts:
                raise OSPDError('VTs list is empty', 'start_scan')
            else:
                vt_selection = self.process_vts_params(scanner_vts)

        # Dry run case.
        if 'dry_run' in params and int(params['dry_run']):
            scan_func = self.dry_run_scan
            scan_params = None
        else:
            scan_func = self.start_scan
            scan_params = self.process_scan_params(params)

        scan_id = self.create_scan(scan_id, scan_targets,
                                   scan_params, vt_selection)
        scan_process = multiprocessing.Process(target=scan_func,
                                               args=(scan_id,
                                                     scan_targets,
                                                     parallel))
        self.scan_processes[scan_id] = scan_process
        scan_process.start()
        id_ = Element('id')
        id_.text = scan_id
        return simple_response_str('start_scan', 200, 'OK', id_)
575384
def handle_get_scans_command(self, scan_et):
        

        scan_id = scan_et.attrib.get('scan_id')
        details = scan_et.attrib.get('details')
        pop_res = scan_et.attrib.get('pop_results')
        if details and details == '0':
            details = False
        else:
            details = True
            if pop_res and pop_res == '1':
                pop_res = True
            else:
                pop_res = False

        responses = []
        if scan_id and scan_id in self.scan_collection.ids_iterator():
            self.check_scan_process(scan_id)
            scan = self.get_scan_xml(scan_id, details, pop_res)
            responses.append(scan)
        elif scan_id:
            text = "Failed to find scan '{0}'".format(scan_id)
            return simple_response_str('get_scans', 404, text)
        else:
            for scan_id in self.scan_collection.ids_iterator():
                self.check_scan_process(scan_id)
                scan = self.get_scan_xml(scan_id, details, pop_res)
                responses.append(scan)
        return simple_response_str('get_scans', 200, 'OK', responses)
562228
def handler(self, environ, start_response):
        """"""

        if environ['REQUEST_METHOD'] == 'POST':
            return self.handle_POST(environ, start_response)
        else:
            start_response("400 Bad request", [('Content-Type', 'text/plain')])
            return ['']
382758
def start(self):
        
        resp = self.post('start')

        if resp.is_fail():
            return None
        if 'result' not in resp.data:
            return None

        result = resp.data['result']
        return {
            'user': result['user'],
            'ws_host': result['ws_host'],
        }
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
536862
def handle(self, **options):
        """"""
        template = os.path.dirname(os.path.abspath(__file__)) + "/app_template"
        name = options.pop("name")
        call_command("startapp", name, template=template, **options)
563062
def _handle_command(self, buffer):
        "  "
        text = buffer.text

        # First leave command mode. We want to make sure that the working
        # pane is focused again before executing the command handers.
        self.pymux.leave_command_mode(append_to_history=True)

        # Execute command.
        self.pymux.handle_command(text)
1048601
def handle(self, env, start_response):
        
        try:
            req = Request(env)
            if self.auth_prefix:
                req.path_info_pop()
            req.bytes_transferred = '-'
            req.client_disconnect = False
            if 'x-storage-token' in req.headers and \
                    'x-auth-token' not in req.headers:
                req.headers['x-auth-token'] = req.headers['x-storage-token']
            if 'eventlet.posthooks' in env:
                env['eventlet.posthooks'].append(
                    (self.posthooklogger, (req,), {}))
                return self.handle_request(req)(env, start_response)
            else:
                # Lack of posthook support means that we have to log on the
                # start of the response, rather than after all the data has
                # been sent. This prevents logging client disconnects
                # differently than full transmissions.
                response = self.handle_request(req)(env, start_response)
                self.posthooklogger(env, req)
                return response
        except (Exception, TimeoutError):
            print("EXCEPTION IN handle: %s: %s" % (format_exc(), env))
            start_response('500 Server Error',
                           [('Content-Type', 'text/plain')])
            return ['Internal server error.\n']
1090893
private void initiateSnapshotScan() {
        m_lastSysprocInvocation = System.currentTimeMillis();
        Object params[] = new Object[1];
        params[0] = m_path;
        setState(State.SCANNING);
        long handle = m_nextCallbackHandle++;
        m_procedureCallbacks.put(handle, new ProcedureCallback() {

            @Override
            public void clientCallback(final ClientResponse clientResponse)
                    throws Exception {
                processClientResponsePrivate(clientResponse);
            }

        });
        SNAP_LOG.info("Initiating snapshot scan of " + m_path);
        m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
    }
1262450
def _process_commands(self):
        

        try:
            # poll for data, so we don't block forever
            if self._cmd_pipe.poll(1):  # 1 sec timeout
                payload = self._cmd_pipe.recv_bytes()

                if payload:
                    # segment payload
                    parts = payload.split('\x80', 2)
                    _op = parts[0]

                    # terminate operation
                    if _op == 'TRM':
                        raise EOFError

                    # shell command operation
                    elif _op == 'SHL' and len(parts) == 2:
                        command = parts[1]

                        if command:
                            # run command and return success or fail
                            res = common.shell_process(command)

                            if res is not None:
                                self._cmd_pipe.send_bytes('OK')
                                return True

                    # everything else, should reply with "FAIL"
                    self._cmd_pipe.send_bytes('FAIL')

        except (EOFError, IOError):
            return False

        else:
            return True
112211
def poll_command_request(self):
        
        try:
            message = self.rpc.recv(zmq.NOBLOCK)
        except zmq.ZMQError as exc:
            if exc.errno == zmq.EAGAIN:
                return
            else:
                raise

        _logger.debug("Received command %s", message)
        segments = _unpack(message)
        action, params = segments[0], segments[1:]
        _logger.debug("Adding %s, %s to the request queue", action, params)
        self._command = _Command(action, params)
1302858
def handle(self, *args, **opt):
        
        d1_gmn.app.management.commands.util.util.log_setup(opt["debug"])
        logging.info(
            "Running management command: {}".format(
                __name__
            )  # util.get_command_name())
        )
        d1_gmn.app.management.commands.util.util.exit_if_other_instance_is_running(
            __name__
        )
        self._opt = opt
        try:
            # profiler = profile.Profile()
            # profiler.runcall(self._handle)
            # profiler.print_stats()
            self._handle()
        except d1_common.types.exceptions.DataONEException as e:
            logging.error(str(e))
            raise django.core.management.base.CommandError(str(e))
        self._events.dump_to_log()
1179702
def end_scan(self):
        
        # TODO check states before/after
        self._set_state(self._STATE_GAP_END)
        self.api.ble_cmd_gap_end_procedure()
        self._wait_for_state(self._STATE_GAP_END)

        logger.debug('scanning completed')
        return self.scan_responses
761837
def handle_exec(args):
    
    session_file = get_db_name(args.get('<session-file>'))
    cosmic_ray.commands.execute(session_file)

    return ExitCode.OK
260245
def handle(): # pragma: no cover
    

    try:
        cli = ZappaCLI()
        sys.exit(cli.handle())
    except SystemExit as e: # pragma: no cover
        cli.on_exit()
        sys.exit(e.code)

    except KeyboardInterrupt: # pragma: no cover
        cli.on_exit()
        sys.exit(130)
    except Exception as e:
        cli.on_exit()

        click.echo("Oh no! An " + click.style("error occurred", fg='red', bold=True) + "! :(")
        click.echo("\n==============\n")
        import traceback
        traceback.print_exc()
        click.echo("\n==============\n")
        shamelessly_promote()

        sys.exit(-1)
883270
def handle
      @start = env["merb.request_start"] = Time.now
      Merb.logger.info { "Started request handling: #{start.to_s}" }
      
      find_route!
      return rack_response if handled?
      
      klass = controller
      Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" }
      
      unless klass < Controller
        raise NotFound, 
          "Controller '#{klass}' not found.\n" \
          "If Merb tries to find a controller for static files, " \
          "you may need to check your Rackup file, see the Problems " \
          "section at: http://wiki.merbivore.com/pages/rack-middleware"
      end
      
      if klass.abstract?
        raise NotFound, "The '#{klass}' controller has no public actions"
      end
      
      dispatch_action(klass, params[:action])
    rescue Object => exception
      dispatch_exception(exception)
    end
1150254
def start_scan(self, source_id):
        
        target_url = self.client.get_url('SCAN', 'POST', 'create', {'source_id': source_id})
        r = self.client.request('POST', target_url, json={})
        return self.client.get_manager(Scan).create_from_result(r.json())