Exemplo n.º 1
1
void RequestPrivate::refreshAccessToken() {
    Q_Q(Request);
    
    QUrl tokenUrl(TOKEN_URL);
    QNetworkRequest request(tokenUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QByteArray body("client_id=" + clientId.toUtf8() +
                    "&client_secret=" + clientSecret.toUtf8() +
                    "&refresh_token=" + refreshToken.toUtf8() +
                    "&grant_type=refresh_token");
                    
    if (reply) {
        delete reply;
    }
    
    reply = networkAccessManager()->post(request, body);
    Request::connect(reply, SIGNAL(finished()), q, SLOT(_q_onAccessTokenRefreshed()));
}
Exemplo n.º 2
0
  void Room::deliver(const Message& msg){

///poczatek przykladu udupiania czesci pakietow
    std::cout << "od" << msg.source() << std::endl;
    char tmp[512];
    std::memcpy(tmp,msg.body(),msg.body_length());
    tmp[msg.body_length()]='\0';
    std::string body(tmp);
    if(body=="NIEE") return;
///koniec przykladu udupiania czesci pakietow


    _recent_msgs.push_back(msg);
    while (_recent_msgs.size() > max_recent_msgs)
      _recent_msgs.pop_front();
    std::for_each(_participants.begin(), _participants.end(),
        boost::bind(&Participant::deliver, _1, boost::ref(msg)));
  }
Exemplo n.º 3
0
Arquivo: utils.c Projeto: GeeXboX/enna
static void
md5_update (md5_t *ctx, const uint8_t *src, const int len)
{
    int i, j;

    j = ctx->len & 63;
    ctx->len += len;

    for (i = 0; i < len; i++)
    {
        ctx->block[j++] = src[i];
        if (j == 64)
        {
            body (ctx->ABCD, (uint32_t*) ctx->block);
            j = 0;
        }
    }
}
Exemplo n.º 4
0
main()
{
  printf("MTX starts in main()\n");
  init();
  kfork();
  tswitch();
  body();
  while(1){
    printf("proc 0  running : enter a key : \n");
    getc();
	if (readyQueue){
    	tswitch();
	}
	else{
		printf("proc 0 running: enter a key: \n");
	}
  }
}
void InputConfigFile::process(InputContext &input)
{
	//ファイル一行目のバージョン文字列を取得
	std::string version = input.nextToken();
	input.skipReturn();

	//バージョン文字列に応じたInputProcedureを実行する
	if(version == InputConfigFileEV3Linetracer_1_0::VERSION_STRING)
	{
		InputConfigFileEV3Linetracer_1_0 body(ev3LineTracer);
		body.process(input);
	}
	else
	{
		//バージョンが一致しなかったら例外を投げる
		throw  std::ios::failure("バージョンが不正です");
	}
}
Exemplo n.º 6
0
// ============================================================================
// Calculates aerodynamic force
QPointF ControlSurface::calculateForce( double velocity, double sinAttack ) const
{
	QPointF pos = vec2point( body()->b2body()->GetPosition() );
	
	//double airDensity = parent()->world()->environment()->relativeDensity( pos );
	double airDensity = 1.0;
	
	// lift
	double lift = -airDensity * velocity*velocity * _currentLift * sinAttack;
	
	// drag (negative, becouse backwards)
	double dragH = _currentDragH;
	double drag = -airDensity * velocity*velocity * (dragH +( _currentDragV-dragH) * sinAttack*sinAttack );
	
	//qDebug("Elevator force: lift: %g N, drag: %g N, airspeed: %g m/s, sin(AOA): %g", 
	//	lift, drag, velocity, sinAttack );
	return QPointF( drag, lift );	
}
Exemplo n.º 7
0
/*--------------------------------------------------------------------
  PARSING AND BUILDING PARSE TREE
---------------------------------------------------------------------*/
struct programNode* program()
{	
	struct programNode* prog;

	prog = make_programNode();
	ttype = getToken();
	if (ttype == VAR)
	{	
		ungetToken();  
		prog->decl = decl();
		prog->body = body();
		return prog;
	} 
	else
	{	
		return NULL;
	}
}
Exemplo n.º 8
0
double radix::TBBRadix<T>::operator ()(T* typed_a, size_t len) const
{
    typedef radix::radix_traits<T>::integer_type I;
    I *a = (I*)typed_a;
    I *d = new I[len];
    I* t;

    double time = (double)radix::getTickCount();
    for (I bit = 1; (bit & ~radix::radix_traits<T>::MSB_mask); bit <<= 1, t = a, a = d, d = t)
    {
        TBBRadixScanTask<I, UnsignedOrder<I> > body(a, d, len, bit);
        tbb::parallel_scan( tbb::blocked_range<int>(0, len, 4), body);
    }

    //MSD in inverse opder
    size_t l_bound = 0;
    size_t r_bound = 0;

    //counting loop
    for(size_t i = 0; i < len; ++i)
    {
        if (a[i] & radix::radix_traits<T>::MSB_mask) ++r_bound;
    }

    size_t middle = r_bound - 1;

    //permutation loop
    for(size_t i = 0; i < len; ++i)
    {
        if((a[i] & radix::radix_traits<T>::MSB_mask))
        {
            d[radix_traits<T>::index(l_bound, middle)] = a[i];
            l_bound++;
        }

        else
            d[r_bound++] = a[i];
    }
    time = ((double)radix::getTickCount() - time)/radix::getTickFrequency();
    t = a; a = d; d = t;
    delete[] d;

    return time;
}
Exemplo n.º 9
0
std::string responseToString(LLCore::HttpResponse * response)
{
	static const std::string empty("[Empty]");

	if (! response)
	{
		return empty;
	}

	BufferArray * body(response->getBody());
	if (! body || ! body->size())
	{
		return empty;
	}

	// Attempt to parse as LLSD regardless of content-type
	LLSD body_llsd;
	if (responseToLLSD(response, false, body_llsd))
	{
		std::ostringstream tmp;

		LLSDSerialize::toPrettyNotation(body_llsd, tmp);
		std::size_t temp_len(tmp.tellp());
		
		if (temp_len)
		{
			return tmp.str().substr(0, std::min(temp_len, std::size_t(1024)));
		}
	}
	else
	{
		// *TODO:  More elaborate forms based on Content-Type as needed.
		char content[1024];

		size_t len(body->read(0, content, sizeof(content)));
		if (len)
		{
			return std::string(content, 0, len);
		}
	}

	// Default
	return empty;
}
Exemplo n.º 10
0
Status TLSTransport::sendRequest(const std::string& params, bool compress) {
  if (destination_.find("https://") == std::string::npos) {
    return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
  }

  auto client = getClient();
  http::client::request r(destination_);
  decorateRequest(r);
  if (compress) {
    // Later, when posting/putting, the data will be optionally compressed.
    r << boost::network::header("Content-Encoding", "gzip");
  }

  // Allow request calls to override the default HTTP POST verb.
  HTTPVerb verb = HTTP_POST;
  if (options_.count("verb") > 0) {
    verb = (HTTPVerb)options_.get<int>("verb", HTTP_POST);
  }

  VLOG(1) << "TLS/HTTPS " << ((verb == HTTP_POST) ? "POST" : "PUT")
          << " request to URI: " << destination_;
  if (FLAGS_verbose && FLAGS_tls_dump) {
    fprintf(stdout, "%s\n", params.c_str());
  }

  try {
    if (verb == HTTP_POST) {
      response_ = client.post(r, (compress) ? compressString(params) : params);
    } else {
      response_ = client.put(r, (compress) ? compressString(params) : params);
    }

    const auto& response_body = body(response_);
    if (FLAGS_verbose && FLAGS_tls_dump) {
      fprintf(stdout, "%s\n", std::string(response_body).c_str());
    }
    response_status_ =
        serializer_->deserialize(response_body, response_params_);
  } catch (const std::exception& e) {
    return Status((tlsFailure(e.what())) ? 2 : 1,
                  std::string("Request error: ") + e.what());
  }
  return response_status_;
}
Exemplo n.º 11
0
static void simpleexp (LexState *ls, expdesc *v) {
  /* simpleexp -> NUMBER | STRING | NIL | constructor | FUNCTION body
               | primaryexp */
  switch (ls->t.token) {
    case TK_NUMBER: {
      init_exp(v, VK, luaK_numberK(ls->fs, ls->t.seminfo.r));
      next(ls);  /* must use `seminfo' before `next' */
      break;
    }
    case TK_STRING: {
      codestring(ls, v, ls->t.seminfo.ts);
      next(ls);  /* must use `seminfo' before `next' */
      break;
    }
    case TK_NIL: {
      init_exp(v, VNIL, 0);
      next(ls);
      break;
    }
    case TK_TRUE: {
      init_exp(v, VTRUE, 0);
      next(ls);
      break;
    }
    case TK_FALSE: {
      init_exp(v, VFALSE, 0);
      next(ls);
      break;
    }
    case '{': {  /* constructor */
      constructor(ls, v);
      break;
    }
    case TK_FUNCTION: {
      next(ls);
      body(ls, v, 0, ls->linenumber);
      break;
    }
    default: {
      primaryexp(ls, v);
      break;
    }
  }
}
Exemplo n.º 12
0
bool mail_body::save_relative(const char* html, size_t hlen,
	const char* text, size_t tlen,
	const std::vector<mail_attach*>& attachments,
	string& out) const
{
	if (!html || !hlen || !text || !tlen || attachments.empty())
	{
		logger_error("invalid input!");
		return false;
	}

	mail_message::create_boundary("0002",
		const_cast<mail_body*>(this)->boundary_);
	string ctype;
	ctype.format("multipart/relative;\r\n"
		"\ttype=\"multipart/alternative\";\r\n"
		"\tboundary=\"%s\"", boundary_.c_str());
	const_cast<mail_body*>(this)->set_content_type(ctype);

	out.format_append("Content-Type: %s\r\n\r\n", content_type_.c_str());
	out.append("\r\n");
	out.format_append("--%s\r\n", boundary_.c_str());

	// 递归一层,调用生成 alternative 格式数据
	mail_body body(charset_.c_str(), transfer_encoding_.c_str());
	bool ret = body.save_alternative(html, hlen, text, tlen, out);
	if (ret == false)
		return ret;

	out.append("\r\n");

	std::vector<mail_attach*>::const_iterator cit;
	for (cit = attachments.begin(); cit != attachments.end(); ++cit)
	{
		out.format_append("--%s\r\n", boundary_.c_str());
		if ((*cit)->save_to(coder_, out) == false)
			return false;
		out.append("\r\n");
	}

	out.format_append("\r\n--%s--\r\n", boundary_.c_str());

	return true;
}
Exemplo n.º 13
0
    ~SoapReplier()
    {
        // End of body -- assemble reply
        unsigned int rc = ENOSYS;

        soap::Params result;

        SoapInfo *soap_info = new SoapInfo;
        soap_info->ipe = m_ipe;
        soap_info->access = m_access;
        m_endpoints->reset(soap_info);

        rc = m_service->OnAction(m_action, m_args, &result);

        if (rc)
        {
            m_response->status_line = "HTTP/1.1 801 Error\r\n";

            std::string body(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
                "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""
                " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
                " <s:Body>"
                "  <s:Fault><faultcode>soap:Server</faultcode>"
                "  <faultstring>Service error ");
            body += util::SPrintf("%u", rc);
            body += "</faultstring></s:Fault></s:Body></s:Envelope>\r\n";

            LOG(SOAP) << "Soap response is " << body << "\n";

            m_response->body_source.reset(new util::StringStream(body));
        }
        else
        {
            std::string body = soap::CreateBody(m_service->GetData(),
                                                m_action, true,
                                                m_service->GetServiceType(),
                                                result);

            LOG(SOAP) << "Soap response is " << body << "\n";

            m_response->body_source.reset(new util::StringStream(body));
        }
    }
Exemplo n.º 14
0
int AmB2BSession::relaySip(const AmSipRequest& orig, const AmSipReply& reply)
{
  const string* hdrs = &reply.hdrs;
  string m_hdrs;
  const string method(orig.method);

  if (reply.rseq != 0) {
    m_hdrs = reply.hdrs +
      SIP_HDR_COLSP(SIP_HDR_RSEQ) + int2str(reply.rseq) + CRLF;
    hdrs = &m_hdrs;
  }

  AmMimeBody body(reply.body);
  if ((orig.method == SIP_METH_INVITE ||
       orig.method == SIP_METH_UPDATE ||
       orig.method == SIP_METH_ACK ||
       orig.method == SIP_METH_PRACK))
  {
    updateLocalBody(body);
  }

  DBG("relaying SIP reply %u %s\n", reply.code, reply.reason.c_str());

  int flags = SIP_FLAGS_VERBATIM;
  if(reply.to_tag.empty())
    flags |= SIP_FLAGS_NOTAG;

  int err = dlg->reply(orig,reply.code,reply.reason,
		       &body, *hdrs, flags);

  if(err < 0){
    ERROR("dlg->reply() failed\n");
    return err;
  }

  if ((method == SIP_METH_INVITE ||
       method == SIP_METH_UPDATE) &&
      !reply.body.empty()) {
    saveSessionDescription(reply.body);
  }

  return 0;
}
Exemplo n.º 15
0
/// Generate the winning lines from 4 prototypes.
/// We only need the prototypes and the isomorphisms to generate all 76
/// of the winning lines.  Note that iso::add() removes duplicates,
/// so we can afford to be overzealous in generating them.
void
win::init() {
	win main(0,21,42,63);			// a major diagonal
	win flat(0,1,2,3);				// flat, but cuts 2 major diagonals
	win body(16,17,18,19);			// flat without cutting a major diagonal
	win diag(0,5,10,15);			// "minor" diagonal.  All cut 2 majors.

	nextwin = 0;

	for (int i=0; i<iso::nextiso; i++) {
		win::add(iso::isos[i] * main);
		win::add(iso::isos[i] * flat);
		win::add(iso::isos[i] * diag);
		win::add(iso::isos[i] * body);
	}
#ifndef NDEBUG
	cout << "There are " << nextwin << " winning lines" << endl;
#endif
}
Exemplo n.º 16
0
void GlyphViewer::root (GraphicMaster* root) {
    if (_root != root) {
        Extension ext;
        Allocation a;
        root->transformer(nil);
        root->background(_root->background());
        _root->allocate(nil, a, ext);
        _root = root;
        body(new Target(_root,TargetAlwaysHit));
        initgraphic();
        Canvas* c = canvas();
        if (c != nil) {
            Requisition req;
            //_root->flush();
            _root->request(req);
            _root->allocate(c, _a, ext);
        }
    }
}
Exemplo n.º 17
0
void UE::on_rx_request(pjsip_rx_data *rdata)
{
 pjsip_msg* msg = rdata->msg_info.msg;

  pj_str_t message;
  stra(&message, "MESSAGE");
  pjsip_method msg_method;
  pjsip_method_init(&msg_method, _pool, &message);
  if (pjsip_method_cmp(&msg_method, &msg->line.req.method) == 0)
  {
    std::string body((char*)msg->body->data, msg->body->len);
    pjsip_transaction* tsx;
    pjsip_endpt_respond(get_global_endpoint(), NULL, rdata, 200, NULL, NULL, NULL, &tsx);
  } else {
    pjsip_endpt_respond_stateless(get_global_endpoint(), rdata, 
        500, NULL,
        NULL, NULL);
  }
}
Exemplo n.º 18
0
static void localfunc (LexState *ls)
{
    expdesc v, b;
    FuncState *fs = GetCurrentFuncState( ls );

    new_localvar(ls, str_checkname(ls), 0);

    init_exp(&v, VLOCAL, fs->freereg);

    luaK_reserveregs(fs, 1);
    adjustlocalvars(ls, 1);

    body(ls, &b, 0, ls->linenumber);

    luaK_storevar(fs, &v, &b);

    /* debug information will only see the variable after this point! */
    getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
}
Exemplo n.º 19
0
shared_ptr<ASTNode> Parser::hornclause() {
	shared_ptr<ASTNode> retVal{ new ASTNode{ ASTNode::HORNCLAUSE } };
	string prod = "hornclause -> LEFTPAREN head [body] RIGHTPAREN";
	match(Token::LEFTPAREN, prod);
	if (it != tokens.end() && (**it).type == Token::LEFTPAREN) {
		retVal->children.push_back(head());
		recovery = currentParse;
		if (it != tokens.end() && (**it).type == Token::LEFTPAREN) {
			retVal->children.push_back(body());
		}
	}
	else {
		error(Token::getTokenName(Token::LABEL)
			, ((it == tokens.end()) ? Token::END : (**it).type)
			, prod);
	}
	match(Token::RIGHTPAREN, prod);
	return retVal;
}
Exemplo n.º 20
0
void ApplicationWindow::print()
{
#ifndef QT_NO_PRINTER
    printer->setFullPage( TRUE );
    if ( printer->setup(this) ) {		// printer dialog
	statusBar()->message( "Printing..." );
	QPainter p;
	if( !p.begin( printer ) ) {               // paint on printer
	    statusBar()->message( "Printing aborted", 2000 );
	    return;
	}

	QPaintDeviceMetrics metrics( p.device() );
	int dpiy = metrics.logicalDpiY();
	int margin = (int) ( (2/2.54)*dpiy ); // 2 cm margins
	QRect body( margin, margin, metrics.width() - 2*margin, metrics.height() - 2*margin );
	QSimpleRichText richText( QStyleSheet::convertFromPlainText(e->text()),
				  QFont(),
				  e->context(),
				  e->styleSheet(),
				  e->mimeSourceFactory(),
				  body.height() );
	richText.setWidth( &p, body.width() );
  	QRect view( body );
	int page = 1;
	do {
	    richText.draw( &p, body.left(), body.top(), view, colorGroup() );
	    view.moveBy( 0, body.height() );
	    p.translate( 0 , -body.height() );
	    p.drawText( view.right() - p.fontMetrics().width( QString::number( page ) ),
			view.bottom() + p.fontMetrics().ascent() + 5, QString::number( page ) );
	    if ( view.top()  >= richText.height() )
		break;
	    printer->newPage();
	    page++;
	} while (TRUE);

	statusBar()->message( "Printing completed", 2000 );
    } else {
	statusBar()->message( "Printing aborted", 2000 );
    }
#endif
}
Exemplo n.º 21
0
/*
*Function: Print
*Inputs:none
*Outputs:none
*Returns:none
*/
void GraphPaneData::Print()
{
	IT_IT("GraphPaneData::Print");
	
	QPrinter prt; 
	prt.setDocName(tr("Pen Trace"));
	prt.setCreator(tr(SYSTEM_NAME));
	prt.setOrientation(QPrinter::Landscape);
	prt.setOutputFileName("~out.ps");
	prt.setOutputToFile(false);
	//
	if(prt.setup(this))
	{
		//
		// Handle the case of no printer being selected
		//
		if(!prt.printerName().isEmpty())
		{
			QPainter p;
			p.begin(&prt);
			QPaintDeviceMetrics metrics(p.device());
			//
			int dpix = metrics.logicalDpiX() ; //  inch border
			int dpiy = metrics.logicalDpiY() ;
			//
			QRect body(dpix, dpiy,	metrics.width()  -  dpix*6,	metrics.height() -  dpiy*2);
			TheGraph.Plot(p,body,Qt::white);
			//
			QFont font("times", 8); 
			p.setFont(font);
			//
			p.drawText( body.left() ,body.top(), Title);
			//
			p.end();
			//
		}
		else
		{
			QMessageBox::information(this,tr("Print Graph Error"),tr("No Printer Selected!"));
		};
	};
};
Exemplo n.º 22
0
void
inheritance::visit (t_target_definition &n)
{
  if (done (n))
    return;
  mark (n);

  // this target doesn't inherit anything
  if (!n.derive ())
    return;

  std::string const &name = id (n.derive ()->as<t_inheritance> ().base ());

  // find referenced template
  generic_node_ptr base = lookup (name);

  if (!base)
    {
      errors.add<semantic_error> (n.derive (), "no such template: " + C::quoted (name));
      return;
    }

  // visit inherited templates, first
  base->accept (*this);

  // now copy all information from the base definition
  t_target_definition &b = base->as<t_target_definition> ();

  if (b.cond ())
    {
      assert (!n.cond ());
      n.cond (b.cond ()->clone ());
    }
  if (b.dest ())
    {
      assert (!n.dest ());
      n.dest (b.dest ()->clone ());
    }
  t_target_members &body = n.body ()->as<t_target_members> ();
  foreach (node_ptr const &p, b.body ()->as<t_target_members> ().list)
    body.add (p->clone ());
}
Exemplo n.º 23
0
int
main(int argc, const char *argv[])
{
	boost::asio::io_service service { };
	auto client_ = std::make_shared<net::http::client>(service);
	bool show_request = false;
	bool show_headers = false;
	for(int i = 1; i < argc; ++i) {
		auto v = std::string { argv[i] };
		if(v == "--headers") {
			show_headers = true;
		} else if(v == "--request") {
			show_request = true;
		} else {
			auto req = net::http::request {
				net::http::uri {
					argv[i]
				}
			};
			req << net::http::header("User-agent", "some-user-agent");
			auto res = client_->GET(
				std::move(req)
			);
			res->completion()->on_done([i, show_request, show_headers](const std::shared_ptr<net::http::response> &res) {
				if(show_request) {
					std::cout << res->request().bytes() << "\n";
				}
				if(show_headers) {
					res->each_header([](const net::http::header &h) {
						std::cout << h.key() << ": " << h.value() << "\n";
					});
					std::cout << "\n";
				}
				std::cout << res->body();
			});
		}
	}

	// std::cout << "run\n";
	service.run();
	// std::cout << "done\n";
}
Exemplo n.º 24
0
void BackgroundSubtractorGMGImpl::apply(InputArray _frame, OutputArray _fgmask, double newLearningRate)
{
    Mat frame = _frame.getMat();

    CV_Assert(frame.depth() == CV_8U || frame.depth() == CV_16U || frame.depth() == CV_32F);
    CV_Assert(frame.channels() == 1 || frame.channels() == 3 || frame.channels() == 4);

    if (newLearningRate != -1.0)
    {
        CV_Assert(newLearningRate >= 0.0 && newLearningRate <= 1.0);
        learningRate = newLearningRate;
    }

    if (frame.size() != frameSize_)
    {
        double minval = minVal_;
        double maxval = maxVal_;
        if( minVal_ == 0 && maxVal_ == 0 )
        {
            minval = 0;
            maxval = frame.depth() == CV_8U ? 255.0 : frame.depth() == CV_16U ? std::numeric_limits<ushort>::max() : 1.0;
        }
        initialize(frame.size(), minval, maxval);
    }

    _fgmask.create(frameSize_, CV_8UC1);
    Mat fgmask = _fgmask.getMat();

    GMG_LoopBody body(frame, fgmask, nfeatures_, colors_, weights_,
                      maxFeatures, learningRate, numInitializationFrames, quantizationLevels, backgroundPrior, decisionThreshold,
                      maxVal_, minVal_, frameNum_, updateBackgroundModel);
    parallel_for_(Range(0, frame.rows), body, frame.total()/(double)(1<<16));

    if (smoothingRadius > 0)
    {
        medianBlur(fgmask, buf_, smoothingRadius);
        swap(fgmask, buf_);
    }

    // keep track of how many frames we have processed
    ++frameNum_;
}
Exemplo n.º 25
0
already_AddRefed<Response>
Response::CloneUnfiltered(JSContext* aCx, ErrorResult& aRv)
{
  if (GetBodyUsed(aRv)) {
    aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
    return nullptr;
  }

  RefPtr<FetchStreamReader> streamReader;
  nsCOMPtr<nsIInputStream> inputStream;

  JS::Rooted<JSObject*> body(aCx);
  MaybeTeeReadableStreamBody(aCx, &body,
                             getter_AddRefs(streamReader),
                             getter_AddRefs(inputStream), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  MOZ_ASSERT_IF(body, streamReader);
  MOZ_ASSERT_IF(body, inputStream);

  RefPtr<InternalResponse> clone =
    mInternalResponse->Clone(body
      ? InternalResponse::eDontCloneInputStream
      : InternalResponse::eCloneInputStream);

  RefPtr<InternalResponse> ir = clone->Unfiltered();
  RefPtr<Response> ref = new Response(mOwner, ir, GetSignalImpl());

  if (body) {
    // Maybe we have a body, but we receive null from MaybeTeeReadableStreamBody
    // if this body is a native stream.   In this case the InternalResponse will
    // have a clone of the native body and the ReadableStream will be created
    // lazily if needed.
    ref->SetReadableStreamBody(aCx, body);
    ref->mFetchStreamReader = streamReader;
    ir->SetBody(inputStream, InternalResponse::UNKNOWN_BODY_SIZE);
  }

  return ref.forget();
}
Exemplo n.º 26
0
    void GlobalConstraint::expandHead(Grounder *g, Lit *lit, Lit::ExpansionType type)
    {
            assert(false);
            switch(type)
            {
                    case Lit::RANGE:
                    case Lit::RELATION:
                    {
                            body_.push_back(lit);
                            break;

                    }
                    case Lit::POOL:
                    {
                            LitPtrVec body(body_);
                            g->addInternal(new Rule(loc(), lit, body));
                            break;
                    }
            }
    }
Exemplo n.º 27
0
Status TLSTransport::sendRequest(const std::string& params) {
  if (destination_.find("https://") == std::string::npos) {
    return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
  }

  auto client = getClient();
  http::client::request r(destination_);
  decorateRequest(r);

  try {
    VLOG(1) << "TLS/HTTPS POST request to URI: " << destination_;
    response_ = client.post(r, params);
    response_status_ =
        serializer_->deserialize(body(response_), response_params_);
  } catch (const std::exception& e) {
    return Status(((std::string(e.what()).find("Error") == 0) ? 1 : 2),
                  std::string("Request error: ") + e.what());
  }
  return response_status_;
}
Exemplo n.º 28
0
void BasicHttp::HandleRequst(struct mg_connection *nc, int ev, void* ev_data){
    http_message* hm = (http_message*)ev_data;
    std::string uri(hm->uri.p, hm->uri.len);
    std::string query(hm->query_string.p, hm->query_string.len);
    std::string body(hm->body.p, hm->body.len);

    auto it = _handlers.find(uri);
    if(_handlers.end() == it){
        std::ostringstream oss;
        oss << "HTTP/1.1 404 Not Found\r\n\r\n404 Not Found\r\n";
        mg_send(nc, oss.str().c_str(), oss.str().length());
        nc->flags |= MG_F_SEND_AND_CLOSE;
        LSF_LOG_INF("uri:%s, query:%s,reply:%s", uri.c_str(), query.c_str(), oss.str().c_str());
        return;
    }

    _connections.emplace(uri, nc);
    it->second(query, body);
    LSF_LOG_INF("GetRequest: uri:%s, query:%s, body:%s", uri.c_str(), query.c_str(), body.c_str());
}
Exemplo n.º 29
0
int JabberBotSession::HandleMessageRequest(void *context, const MessageStanza &request, class JabberSession *session) {
  JabberBotSession *bot = static_cast<JabberBotSession *>(context);

  // Sometimes a server will send us a message.  I know it's a server if it doesn't have an "@" in the
  // name.  If I get a message like that, I don't want to use the normal logic because my responses
  // would just confuse it.
  if ((NULL != request.From()) && (std::string::npos != request.From()->find_first_of('@'))) {
    if (NULL != request.Body()) {
      insensitiveString body(request.Body()->c_str());
      CommandHandlerMap::iterator h = bot->m_handlers.find(body);
      if (h != bot->m_handlers.end()) {
	(bot->*h->second.method)(request.From(), request.Type(), request.Id());
      }
      else {
	bot->DefaultCommand(request.From(), request.Type(), request.Id());
      }
    }
  }
  return 0;
}
Exemplo n.º 30
0
void XYView_helper::draw(Canvas* c, const Allocation& a) const {
    current_draw_view_ = v_;
    ((XYView_helper*)this)->t_ = c->transformer();
//print_t("XYView_helper::draw", c->transformer());
    v_->set_damage_area(c);
#if 0
    IfIdraw(pict(t_));
#else
    if (OcIdraw::idraw_stream) {
        Transformer tr(t_);
        tr.translate(3*72, 4*72);
        OcIdraw::pict(tr);
    }
#endif
    c->push_clipping();
    c->clip_rect(v_->left(), v_->bottom(), v_->right(), v_->top());
    body()->draw(c, a);
    c->pop_clipping();
    IfIdraw(end());
}