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

    $extractDir = ( !empty($_POST['extractDir']) ) ? ltrim($_POST['extractDir'],'/') : '';
    $extractDir = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($extractDir);
    if ( preg_match(CKFINDER_REGEX_INVALID_PATH, $extractDir) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }
    $extractPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $extractDir.'/');
    $extractClientPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getClientPath(),$extractDir);
    // acl for upload dir
    $_aclConfig = $this->_config->getAccessControlConfig();
    $aclMask = $_aclConfig->getComputedMask($this->_currentFolder->getResourceTypeName(),$extractDir);

    if ( !(($aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_CREATE ) == CKFINDER_CONNECTOR_ACL_FOLDER_CREATE ) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }
    if ( empty( $_POST['force']) && file_exists($extractPath) && is_dir($extractPath) && !CKFinder_Connector_Utils_FileSystem::isEmptyDir($extractPath) )
    {
      $dirExists = new CKFinder_Connector_Utils_XmlNode("FolderExists");
      $oErrorNode = new CKFinder_Connector_Utils_XmlNode("Folder");
      $oErrorNode->addAttribute("name", $extractDir);
      $dirExists->addChild($oErrorNode);
      $this->_connectorNode->addChild($dirExists);
      return;
    }
    elseif ( !empty( $_POST['force']) && $_POST['force'] =='overwrite' )
    {
      if ( !(($aclMask &  CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_DELETE ) ==  CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_DELETE ) ){
        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
      }
      if ( $extractDir && file_exists($extractPath) && is_dir($extractPath) )
      {
        if ( !(($aclMask &  CKFINDER_CONNECTOR_ACL_FOLDER_CREATE | CKFINDER_CONNECTOR_ACL_FOLDER_DELETE ) ==  CKFINDER_CONNECTOR_ACL_FOLDER_CREATE | CKFINDER_CONNECTOR_ACL_FOLDER_DELETE ) ){
          $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }
        if (!CKFinder_Connector_Utils_FileSystem::unlink($extractPath))
        {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }
      }
    }
    else if ( !empty( $_POST['force']) && $_POST['force'] !== 'merge' )
    {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    for ($i = 0; $i < $this->zip->numFiles; $i++)
    {
      $fileName = $this->zip->getNameIndex($i);
      $filePathInfo = pathinfo($fileName);

      $sFileName = $this->checkOneFile( $filePathInfo, $fileName );
      // security test failed, add to skipped
      if ( $sFileName )
      {
        $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);
    }
  }
27102
def build_xml( result )
      xml = ::Builder::XmlMarkup.new
    
      xml.ProcessResponse do 
        xml.PxPayUserId ::Pxpay::Base.pxpay_user_id
        xml.PxPayKey ::Pxpay::Base.pxpay_key
        xml.Response result
      end
    end
423903
protected function buildXml()
    {
        if (empty($_POST['CKFinderCommand']) || $_POST['CKFinderCommand'] != 'true') {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_RENAME)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        if (!isset($_GET["fileName"])) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
        }
        if (!isset($_GET["newFileName"])) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
        }

        $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
        $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_GET["fileName"]);
        $newFileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_GET["newFileName"]);

        $oRenamedFileNode = new Ckfinder_Connector_Utils_XmlNode("RenamedFile");
        $this->_connectorNode->addChild($oRenamedFileNode);
        $oRenamedFileNode->addAttribute("name", CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($fileName));

        $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();
        if (!$resourceTypeInfo->checkExtension($newFileName)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
        }

        if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName) || $resourceTypeInfo->checkIsHiddenFile($fileName)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if (!CKFinder_Connector_Utils_FileSystem::checkFileName($newFileName) || $resourceTypeInfo->checkIsHiddenFile($newFileName)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
        }

        if (!$resourceTypeInfo->checkExtension($fileName, false)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if ($_config->forceAscii()) {
            $newFileName = CKFinder_Connector_Utils_FileSystem::convertToAscii($newFileName);
        }

        $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $fileName);
        $newFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $newFileName);

        $bMoved = false;

        if (!file_exists($filePath)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
        }

        if (!is_writable(dirname($newFilePath))) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }

        if (!is_writable($filePath)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
        }

        if (file_exists($newFilePath)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ALREADY_EXIST);
        }

        $bMoved = @rename($filePath, $newFilePath);

        if (!$bMoved) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNKNOWN, "File " . CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($fileName) . "has not been renamed");
        } else {
            $oRenamedFileNode->addAttribute("newName", CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($newFileName));

            $thumbPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getThumbsServerPath(), $fileName);
            CKFinder_Connector_Utils_FileSystem::unlink($thumbPath);
        }
    }
806492
public function handleRequest()
    {
        // Create the request very early so the Resource Management has a chance to grab it:
        $this->request = Request::createFromEnvironment();
        $this->response = new Response();

        $this->checkBasicRequirementsAndDisplayLoadingScreen();

        $this->boot();
        $this->resolveDependencies();
        if (isset($this->settings['http']['baseUri'])) {
            $this->request->setBaseUri(new Uri($this->settings['http']['baseUri']));
        }

        $componentContext = new ComponentContext($this->request, $this->response);
        $this->baseComponentChain->handle($componentContext);

        $this->baseComponentChain->getResponse()->send();

        $this->bootstrap->shutdown('Runtime');
        $this->exit->__invoke();
    }
962827
def call(env)
      @request = Rack::Request.new(env)
      xml_response = @xmlrpc_handler.process(request_body)
      [200, {'Content-Type' => 'text/xml'}, [xml_response]]
    end
1193773
def processRequest(cls, ps, **kw):
        
        resource = kw['resource']
        request = kw['request']
        method =  getattr(resource, 'soap_%s' %
                           _get_element_nsuri_name(ps.body_root)[-1])
                                              
        try:
            req,rsp = method(ps, request=request)
        except Exception, ex:
            raise
        
        return rsp
346328
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        if (!isStarted())
            return;
        
        // Only handle GET, HEAD and POST
        if (!HttpRequest.__GET.equals(request.getMethod()) &&
            !HttpRequest.__HEAD.equals(request.getMethod()) &&
            !HttpRequest.__POST.equals(request.getMethod()))
            return;

        log.debug("Dump");
        
        response.setField(HttpFields.__ContentType,
                          HttpFields.__TextHtml);
        OutputStream out = response.getOutputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
        Writer writer = new OutputStreamWriter(buf,StringUtil.__ISO_8859_1);
        writer.write("<HTML><H1>Dump HttpHandler</H1>");
        writer.write("<PRE>\npath="+request.getPath()+
                    "\ncontextPath="+getHttpContext().getContextPath()+
                    "\npathInContext="+pathInContext+
                    "\n</PRE>\n");
        writer.write("<H3>Header:</H3><PRE>");
        writer.write(request.toString());
        writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
        Set names=request.getParameterNames();
        Iterator iter = names.iterator();
        while(iter.hasNext())
        {
            String name=iter.next().toString();
            List values=request.getParameterValues(name);
            if (values==null || values.size()==0)
            {
                writer.write(name);
                writer.write("=\n");
            }
            else if (values.size()==1)
            {
                writer.write(name);
                writer.write("=");
                writer.write((String)values.get(0));
                writer.write("\n");
            }
            else
            {
                for (int i=0; i<values.size(); i++)
                {
                    writer.write(name);
                    writer.write("["+i+"]=");
                    writer.write((String)values.get(i));
                    writer.write("\n");
                }
            }
        }
        
        String cookie_name=request.getParameter("CookieName");
        if (cookie_name!=null && cookie_name.trim().length()>0)
        {
            String cookie_action=request.getParameter("Button");
            try{
                Cookie cookie=
                    new Cookie(cookie_name.trim(),
                               request.getParameter("CookieVal"));
                if ("Clear Cookie".equals(cookie_action))
                    cookie.setMaxAge(0);
                response.addSetCookie(cookie);
            }
            catch(IllegalArgumentException e)
            {
                writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
                writer.write(e.toString());
                LogSupport.ignore(log,e);
            }
        }
        
        writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
        Cookie[] cookies=request.getCookies();
        if (cookies!=null && cookies.length>0)
        {
            for(int c=0;c<cookies.length;c++)
            {
                Cookie cookie=cookies[c];
                writer.write(cookie.getName());
                writer.write("=");
                writer.write(cookie.getValue());
                writer.write("\n");
            }
        }
        
        writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
        Enumeration attributes=request.getAttributeNames();
        if (attributes!=null && attributes.hasMoreElements())
        {
            while(attributes.hasMoreElements())
            {
                String attr=attributes.nextElement().toString();
                writer.write(attr);
                writer.write("=");
                writer.write(request.getAttribute(attr).toString());
                writer.write("\n");
            }
        }
        
        writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
        byte[] content= new byte[4096];
        int len;
        try{
            InputStream in=request.getInputStream();
            while((len=in.read(content))>=0)
                writer.write(new String(content,0,len));
        }
        catch(IOException e)
        {
            LogSupport.ignore(log,e);
            writer.write(e.toString());
        }
        
        // You wouldn't normally set a trailer like this, but
        // we don't want to commit the output to force trailers as
        // it makes test harness messy
        request.getAcceptableTransferCodings();
        
        // commit now
        writer.flush();
        response.setIntField(HttpFields.__ContentLength,buf.size()+1000);
        buf.writeTo(out);
        out.flush();
        
        // Now add the response
        buf.reset();
        writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
        writer.write(response.toString());
        writer.write("</PRE></HTML>");
        writer.flush();
        for (int pad=998-buf.size();pad-->0;)
            writer.write(" ");
        writer.write("\015\012");
        writer.flush();
        buf.writeTo(out);
            
        request.setHandled(true);
    }
357781
function request(options) {
    // Prepare options
    var opts = extend({}, options);
    opts.method = opts.method.toUpperCase();
    opts.uri = opts.uri.toString();

    // Instantiate request
    var xhr = new XMLHttpRequest();

    // Request finished handler
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status !== 0 && opts.onComplete) {
            var err = null;
            if (xhr.status >= 400) {
                err = new Error('HTTP ' + xhr.status + ' ' + xhr.statusText);
                err.statusCode = xhr.status;
            }

            opts.onComplete(
                err,
                normalizeResponse(xhr),
                opts.json ? JSON.parse(xhr.responseText) : xhr.responseText
            );
        }
    };

    // Request failure handler
    xhr.onerror = function() {
        opts.onComplete(new Error('XHR error - CORS denied?'), normalizeResponse(xhr));
    };

    // Request progress handler
    if (opts.onProgress) {
        xhr.upload.addEventListener('progress', opts.onProgress, false);
    }

    // Open the request
    xhr.open(opts.method, opts.uri, true);

    // Apply request headers
    for (var key in opts.headers) {
        // We're not allowed to set certain headers in browsers
        if (disallowedHeaders.indexOf(key) > -1) {
            continue;
        }

        xhr.setRequestHeader(key, opts.headers[key]);
    }

    // Is this a JSON-request?
    if (opts.json) {
        xhr.setRequestHeader('Accept', 'application/json');

        // Do we have a payload to deliver as JSON?
        if (typeof opts.json !== 'boolean') {
            xhr.setRequestHeader('Content-Type', 'application/json');
            opts.body = JSON.stringify(opts.json);
        }
    }

    // Send the request
    xhr.send(opts.body);
}
281668
def build_request(options = {})

				src_creds_name = SRC_CREDS

				options = options.dup #Don't clobber the original hash
				#NOTE: Could extend this to read WSDL document or using Savon client to tell which nodes are allowed in the request
				#performing the same type of test against passed in variables on each and replacing with the appropriate value

				final_opts = options.dup

				options.keys.each do |key|
					orig_key = key
					new_key = orig_key.to_s.gsub("_", "").downcase
					if (new_key == src_creds_name.downcase)
						final_opts[src_creds_name] = final_opts[key] #Set "SourceCredentials" to hash referenced by similarly named
						final_opts.delete(orig_key)
					end
				end
				
				opts = {};
				final_opts.each  do |key, value|
					new_val = value
					if value.kind_of?(Array)
						tranformed = {}	
						if item[0].kind_of? Integer
							transformed[:int] = value
						elsif item[0].kind_of? String
							transformed[:string] = value
						else
							break #Don't know how to deal with it, return regular
						end
						 new_val = transformed
					end
					opts[key] = new_val
				end
		
				request_body = 
				{
					"PageSize" => 10, 
					"CurrentPageIndex" => 0
				}

				request_body["XMLDetail"] = "Bare" unless opts["Fields"]


				request_body[src_creds_name] = @src_creds.to_hash if @src_creds
				request_body["UserCredentials"] = @usr_creds.to_hash if @usr_creds	

				return request_body.merge!(opts)
		end
939578
function build(xmlStream, model) {
  xmlStream.openNode(model.tag, model.$);
  if (model.c) {
    model.c.forEach(function(child) {
      build(xmlStream, child);
    });
  }
  if (model.t) {
    xmlStream.writeText(model.t);
  }
  xmlStream.closeNode();
}
1051782
def create
      request = Request.post_xml('authorizations/request', api_version, credentials, xml)
      response = Response.new(request)
      update_attributes(response.serialize)

      response.success?
    end
135302
def _doRequest(self, request=None, is_file=False, file_xml_uri=''):
		""""""
		if request is None:
			request = []

		if is_file and file_xml_uri:
			url = self._buildFileUrl(file_xml_uri)
		else:
			request = '&'.join(request)
			url = "%s?%s" % (self._buildUrl(), request)

		if self._debug:
			print '[PyFileMaker DEBUG] ', url

		resp = requests.get(
			url = url,
			auth = (self._login, self._password)
		)
		resp.raise_for_status()

		return resp.content
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)
1247501
function processXML(name, uri, processor, resp, callback) {
  var parser = new xml2js.Parser();

  parser.parseString(resp, function (err, xml) {
    if (err) {
      GLOBAL.error(name, err);
      return;
    } else {
      processor.getAnnotations(name, uri, xml, function(err, annoRows) {
        callback(err, {name: name, uri: uri, annoRows: annoRows});
      });
    }
  });
}
72785
def build(xml, start_index = 0)
    super do |xml|
      [:url, :name, :email, :position, :organization, :additional, :phone, :address].each do |key|
        if @vcard.has_key?(key)
          xml.tag!(key, @vcard[key])
        end
      end
    end
  end
593766
public function compile()
    {
        $requestHandler = $this->getRequestHandler();

        $encodedData = $this->encodeData($this->getParams());
        $requestHandler->setRawBody($encodedData);

        $response = $requestHandler->send();
        $xml = new \SimpleXMLElement($response->getBody());
        $data = $this->parseXml($xml);

        return $this->buildResponse($data);
    }
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)