Handle request and build XML
765221
protected function buildXml()
  {
    parent::buildXml();

   $checkedFiles = array();
   if ( !empty($_POST['files']) && is_array($_POST['files']) ){
     foreach ( $_POST['files'] as $file){
       $checkedFiles[$file['name']] = $file;
     }
   }

   for ($i = 0; $i < $this->zip->numFiles; $i++)
    {
      $fileName = $this->zip->getNameIndex($i);
      if ( !empty($checkedFiles[$fileName]) && $checkedFiles[$fileName]['options'] == 'ok' )
      {
        // file was sucessfully unzipped before
        $this->appendUnzippedNode($this->unzippedNodes,$fileName);
        continue;
      }

      $filePathInfo = pathinfo($fileName);
      $fileType = 'File';
      $fileStat = $this->zip->statName($i);
      if ( empty($filePathInfo['extension']) && empty($fileStat['size']) ){
        $fileType = 'Folder';
        // check if we can create subfolder
        if ( !$this->_currentFolder->checkAcl( CKFINDER_CONNECTOR_ACL_FOLDER_CREATE ) ){
          $this->errorCode = CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED;
          $this->appendErrorNode($this->skippedFilesNode, $this->errorCode, $fileName, $fileType);
          continue;
        }
      }
      $extractPath = $this->_currentFolder->getServerPath();
      $extractClientPath = $this->_currentFolder->getClientPath();

      $sFileName = $this->checkOneFile( $filePathInfo, $fileName );
      // security test failed, add to skipped
      if ( false !== $sFileName )
      {
        if ( file_exists($extractPath.$sFileName) )
        {
          if ( !is_dir($extractPath.$sFileName) )
          {
            // file was checked before
            if ( !empty($checkedFiles[$fileName]['options']) )
            {
              if ( $checkedFiles[$fileName]['options'] == 'autorename')
              {
                $sFileName = CKFinder_Connector_Utils_FileSystem::autoRename($extractPath,$sFileName);
                $this->extractTo($extractPath,$extractClientPath,$filePathInfo,$sFileName,$fileName);
              }
              elseif ( $checkedFiles[$fileName]['options'] == 'overwrite')
              {
                if ( !$this->_currentFolder->checkAcl( CKFINDER_CONNECTOR_ACL_FILE_DELETE ) ){
                  $this->errorCode = CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED;
                  $this->appendErrorNode($this->skippedFilesNode, $this->errorCode, $fileName, $fileType);
                  continue;
                }
                if (!CKFinder_Connector_Utils_FileSystem::unlink($extractPath.$sFileName))
                {
                  $this->errorCode = CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
                  $this->appendErrorNode($this->skippedFilesNode, $this->errorCode, $fileName, $fileType);
                }
                else
                {
                  $this->extractTo($extractPath,$extractClientPath,$filePathInfo,$sFileName,$fileName);
                }
              }
              else
              {
                // add to skipped files
                $this->appendUnzippedNode($this->unzippedNodes,$fileName,'skip');
              }
            }
            else
            {
              $this->errorCode = CKFINDER_CONNECTOR_ERROR_ALREADY_EXIST;
              $this->appendErrorNode($this->skippedFilesNode, $this->errorCode, $fileName, $fileType);
            }
          }
        }
        // file doesn't exist yet
        else
        {
          $this->extractTo($extractPath,$extractClientPath,$filePathInfo,$sFileName,$fileName);
        }
      }
    }
    $this->zip->close();

    $this->_connectorNode->addChild($this->unzippedNodes);

    if ($this->errorCode != CKFINDER_CONNECTOR_ERROR_NONE) {
      $this->_connectorNode->addChild($this->skippedFilesNode);
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ZIP_FAILED);
    }
  }
1316801
def processRequest(cls, ps, **kw):
        
        resource = kw['resource']
        request = kw['request']

        root = _get_element_nsuri_name(ps.body_root)
        for key,method in inspect.getmembers(resource, inspect.ismethod):
            if (getattr(method, 'soapmethod', False) and method.root == root):
                break
        else:
            raise RuntimeError, 'Missing soap callback method for root "%s"' %root

        try:
            req = ps.Parse(method.requesttypecode)
        except Exception, ex:
            raise
        try:
            rsp = method.responsetypecode.pyclass()
        except Exception, ex:
            raise
        
        try:
            req,rsp = method(req, rsp)
        except Exception, ex:
            raise

        return rsp
670573
def post(self):
        '''
        '''
        ## format sql

        data = request.get_json()
        options, sql_raw = data.get('options'), data.get('sql_raw')

        if options == 'format':
            sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True)
            return build_response(dict(data=sql_formmated, code=200))

        elif options in ('all', 'selected'):
            conn = SQL(config.sql_host, config.sql_port, config.sql_user,
                       config.sql_pwd, config.sql_db)

            result = conn.run(sql_raw)
            return build_response(dict(data=result, code=200))
        else:

            pass







        pass
131171
def post(self, uri=''):
        "'"

        # get node...
        (node, rule_kw) = node_from_uri(uri, method=request.method)

        rule_kw.update( node )
        values = rule_kw
        xhr_data = request.get_json()
        if xhr_data:
            values.update( xhr_data )
        values.update( request.form.to_dict(flat=True) )
        values.update( request.args.to_dict(flat=True) )
        values['method'] = request.method

        # Execute the sql query with the data
        _query(node['id'], **values)

        response = make_response('ok', 201)
        return response
1306394
def handle_request(self, request_text=None):
        

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)
503232
private Schema handle( Request.RequestType type, Method meth, int version, Properties parms ) throws Exception {
    Schema S;
    switch( type ) {
    // case html: // These request-types only dictate the response-type;
    case java: // the normal action is always done.
    case json:
    case xml: {
      Class x = meth.getDeclaringClass();
      Class<Handler> clz = (Class<Handler>)x;
      Handler h = clz.newInstance();
      return h.handle(version,meth,parms); // Can throw any Exception the handler throws
    }
    case query:
    case help:
    default:
      throw H2O.unimpl();
    }
  }
1171160
function (url) {
    var req = new XMLHttpRequest();

    // Response handler. Check the console for errors.
    var respond = function () {
        if (req.status !== 200) {
          console.warn(req.responseText);
          return;
        }
        // Show the raw response text on page
        xmlOutput.textContent = req.responseText;
        // convert XML to javascript objects
        var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
        // Convert to json and show on page
        jsonOutput.textContent = JSON.stringify(json, null, 2);
    };

    req.open('GET', url);
    // This will return latest version (SDMX-ML 2.1)
    req.setRequestHeader('Accept', 'application/xml');

    req.onreadystatechange = function () {
      if (req.readyState > 3) respond();
    };

    req.onerror = function (err) {
      console.warn(err);
    };

    req.send(null);
  }
707533
def execute
      request = Net::HTTP::Get.new(@endpoint.path)
      request.add_field('Content-Type', 'application/soap+xml')
      MexResponse.parse(http(@endpoint).request(request).body)
    end
295638
def build_request_xml(checks, check_data = {})
      builder = Nokogiri::XML::Builder.new do |xml|
        xml.callvalidate do
          authentication(xml)
          xml.sessions do
            xml.session("RID" => Time.now.to_f) do
              xml.data do
                personal_data(xml, check_data[:personal_data])
                card_data(xml, check_data[:card_data])
                bank_data(xml, check_data[:bank_data])
                income_data(xml, check_data[:income_data])
                required_checks(xml, checks)
              end
            end
          end
          xml.application @config[:application_name]
        end
      end
      builder.doc
    end
405981
public function handleRequest()
    {
        // Create the request very early so the ResourceManagement has a chance to grab it:
        $request = Request::createFromEnvironment();
        $response = new Response();
        $this->componentContext = new ComponentContext($request, $response);

        $this->boot();
        $this->resolveDependencies();
        $response = $this->addPoweredByHeader($response);
        $this->componentContext->replaceHttpResponse($response);
        $baseUriSetting = $this->bootstrap->getObjectManager()->get(ConfigurationManager::class)->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow.http.baseUri');
        if (!empty($baseUriSetting)) {
            $baseUri = new Uri($baseUriSetting);
            $request = $request->withAttribute(Request::ATTRIBUTE_BASE_URI, $baseUri);
            $this->componentContext->replaceHttpRequest($request);
        }

        $this->baseComponentChain->handle($this->componentContext);
        $response = $this->baseComponentChain->getResponse();

        $response->send();

        $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
        $this->exit->__invoke();
    }
444180
def output_xml(data, code, headers=None):
    """"""
    resp = make_response(dumps({'response' :data}), code)
    resp.headers.extend(headers or {})
    return resp
836259
def _handle_POST(self, env, start_response):
        
        input = env['wsgi.input']
        data = input.read( int(env['CONTENT_LENGTH']) )
        mimeType = "text/xml"
        if self.encoding is not None:
            mimeType = 'text/xml; charset="%s"' % self.encoding

        request = None
        resource = self.delegate or self
        chain = self.factory.newInstance()
        try:
            pyobj = chain.processRequest(data, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]

        try:
            soap = chain.processResponse(pyobj, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
        
        start_response("200 OK", [('Content-Type',mimeType)])
        return [soap]
248638
def request(self, url, params={}, headers={}):
        
        # Generate current config. Merge in any given headers
        cur_config = self.config.copy()
        if 'headers' in cur_config:
            cur_config['headers'] = cur_config['headers'].copy()
            cur_config['headers'].update(headers)
        else:
            cur_config['headers'] = headers

        with closing(requests.get(url, params=params, **cur_config)) as response:
            if response.status_code == requests.codes.OK:
                # Prepare the temp file. xml content will be
                # stored in a binary file, json in a textfile.
                if (response.headers.get('Content-Type')
                        and ('json' in response.headers['Content-Type'])):
                    enc, fmode = response.encoding, 'w+t'
                else:
                    enc, fmode = None, 'w+b'
                # Create temp file ensuring 2to3 compatibility
                if str_type == str:  # we are on py3
                    source = STF(
                        max_size=self.max_size, mode=fmode, encoding=enc)
                else:
                    # On py27 we must omit the 'encoding' kwarg
                    source = STF(max_size=self.max_size, mode=fmode)
                for c in response.iter_content(chunk_size=1000000,
                                               decode_unicode=bool(enc)):
                    source.write(c)

            else:
                source = None
            code = int(response.status_code)
            if 400 <= code <= 499:
                raise response.raise_for_status()
            return source, response.url, response.headers, code
466357
private HttpPost buildSoapRequest( String action, String innerXml )
    {
        HttpPost httpPost = new HttpPost( BASE_URL );
        httpPost.setHeader( "soapaction", action );
        httpPost.setHeader( "Content-Type", "text/xml; charset=utf-8" );

        final StringBuilder soap = new StringBuilder();
        soap.append( SOAP_HEADER );
        soap.append( "<" ).append( action ).append( ">" );
        soap.append( innerXml );
        soap.append( "</" ).append( action ).append( ">" );
        soap.append( SOAP_FOOTER );

        HttpEntity entity;

        try {
            entity = new StringEntity( soap.toString(), PcsUtils.UTF8.name() );
        } catch ( UnsupportedEncodingException e ) {
            throw new CStorageException( e.getMessage(), e );
        }

        httpPost.setEntity( entity );

        return httpPost;
    }
427120
def _make_request(self, action, params=None):
        
        ct = 'application/x-www-form-urlencoded; charset=UTF-8'
        headers = {'Content-Type': ct}
        params = params or {}
        params['Action'] = action

        for k, v in params.items():
            if isinstance(v, unicode):  # UTF-8 encode only if it's Unicode
                params[k] = v.encode('utf-8')

        response = super(SESConnection, self).make_request(
            'POST',
            '/',
            headers=headers,
            data=urllib.urlencode(params)
        )
        body = response.read()
        if response.status == 200:
            list_markers = ('VerifiedEmailAddresses', 'SendDataPoints')
            e = boto.jsonresponse.Element(list_marker=list_markers)
            h = boto.jsonresponse.XmlHandler(e, None)
            h.parse(body)
            return e
        else:
            # HTTP codes other than 200 are considered errors. Go through
            # some error handling to determine which exception gets raised,
            self._handle_error(response, body)
1285352
function process($data)
	{
		$using_xml = 0;
		$webspace = 1;

		if (isset($data["webspace"]))
		{
			if ($data["webspace"] == "false") // if explicitly set to false, don't use html output
				$webspace = 0;
		}

		if ( isset($data["debugging"]) || isset($data["debug"]) )
		{
			if ($data["debugging"] == "true" || $data["debug"] == "true"  )
			{
				$this->debugging = 1;

				# print out incoming hash
				if ($webspace)	// use html-friendly output
				{
					echo "at process, incoming data: <br>";

					while (list($key, $value) = each($data))
						 echo htmlspecialchars($key) . " = " . htmlspecialchars($value, ENT_COMPAT, CHARSET, TRUE) . "<BR>\n";
				}
				else      // don't use html output
				{
					echo "at process, incoming data: \n";

					while (list($key, $value) = each($data))
						echo "$key = $value\n";
				}

				reset($data);
			}
		}

		if (isset($data["xml"])) // if XML string is passed in, we'll use it
		{
			$using_xml = 1;
			$xml = $data["xml"];
		}
		else
		{
			//  otherwise convert incoming hash to XML string
			$xml = $this->buildXML($data);
		}

		// then set up transaction variables
		$key	= $data["keyfile"];
		$host	= $data["host"];
    $port	= $data["port"];


		# FOR PERFORMANCE, Use the 'extensions' statement in your php.ini to load
		# this library at PHP startup, then comment out the next seven lines

		// load library
		if (!extension_loaded('liblphp'))
		{
			if (!dl('liblphp.so'))
			{
				exit("cannot load liblphp.so, bye\n");
			}
		}

		if ($this->debugging)
		{
			if ($webspace)
				echo "<br>sending xml string:<br>" . htmlspecialchars($xml, ENT_COMPAT, CHARSET, TRUE) . "<br><br>";
			else
				echo "\nsending xml string:\n$xml\n\n";
		}

		// send transaction to LSGS
		$retstg = send_stg($xml, $key, $host, $port);


		if (strlen($retstg) < 4)
			exit ("cannot connect to lsgs, exiting");

		if ($this->debugging)
		{
			if ($this->webspace)	// we're web space
				echo "<br>server responds:<br>" . htmlspecialchars($retstg, ENT_COMPAT, CHARSET, TRUE) . "<br><br>";
			else						// not html output
				echo "\nserver responds:\n $retstg\n\n";
		}

		if ($using_xml != 1)
		{
			// convert xml response back to hash
			$retarr = $this->decodeXML($retstg);

			// and send it back to caller
			return ($retarr);
		}
		else
		{
			// send server response back
			return $retstg;
		}
	}
25771
def _handle_request(self, request):
        """"""

        # Check if this is a persistent connection.
        if request['version'] == 'HTTP/1.1':
            self.keepalive = not request.get('Connection') == 'close'
        elif request['version'] == 'HTTP/1.0':
            self.keepalive = request.get('Connection') == 'Keep-Alive'

        # Check if we're getting a sane request
        if request['method'] not in ('GET'):
            raise InvalidRequestError(501, 'Method not implemented')
        if request['version'] not in ('HTTP/1.0', 'HTTP/1.1'):
            raise InvalidRequestError(
                505, 'Version not supported. Supported versions are: {}, {}'
                .format('HTTP/1.0', 'HTTP/1.1'))

        host, location = self._get_request_uri(request)

        # We must ignore the Host header if a host is specified in GET
        if host is None:
            host = request.get('Host')

        # Check if this request is intended for this webserver
        if host is not None and not host == self.host:
            self.logger.info('Got a request for unknown host %s', host)
            raise InvalidRequestError(404, "We don't serve this host")

        filename = os.path.join(self.folder, unquote(location))
        self.logger.debug('trying to serve %s', filename)

        if os.path.isdir(filename):
            filename = os.path.join(filename, 'index.html')

        if not os.path.isfile(filename):
            raise InvalidRequestError(404, 'Not Found')

        # Start response with version
        response = _get_response(version=request['version'])

        # timeout negotiation
        match = re.match(r'timeout=(\d+)', request.get('Keep-Alive', ''))
        if match is not None:
            requested_timeout = int(match.group(1))
            if requested_timeout < self._timeout:
                self._timeout = requested_timeout

        # tell the client our timeout
        if self.keepalive:
            response['headers'][
                'Keep-Alive'] = 'timeout={}'.format(self._timeout)

        # Set Content-Type
        response['headers']['Content-Type'] = mimetypes.guess_type(
            filename)[0] or 'text/plain'

        # Generate E-tag
        sha1 = hashlib.sha1()
        with open(filename, 'rb') as fp:
            response['body'] = fp.read()
            sha1.update(response['body'])
        etag = sha1.hexdigest()

        # Create 304 response if if-none-match matches etag
        if request.get('If-None-Match') == '"{}"'.format(etag):
            # 304 responses shouldn't contain many headers we might already
            # have added.
            response = _get_response(code=304)

        response['headers']['Etag'] = '"{}"'.format(etag)

        self._write_response(response)