Beispiel #1
0
 void initServerTime() {
     // timeDiff is client current time minus server current time.
     QString url = serverUrl + Urls::TIMESTAMP;
     HttpClient(url).manager(networkManager).debug(true).get([this](const QString &response) {
         timeDiff = QDateTime::currentMSecsSinceEpoch() - response.toLongLong();
     });
 }
Beispiel #2
0
void pimpl<PortalsImporterJob>::run()
{
    m_result.reset();

    m_status = String::EMPTY;

    if(m_stream != nullptr)
    {
        shared_ptr<Portal> portal = m_portal.lock();
        if(portal == nullptr || m_stream == nullptr)
            return;

        m_status = "importing";

        m_serializer->setStopped(false);
        m_result = m_serializer->importStream(portal, m_stream);
        m_stream->close();
        m_stream.reset();
    }
    else
    {
        m_status = "download";

        shared_ptr<boost::asio::io_service> service = createAsioService();
        shared_ptr<TCPSocket> socket = Engine::instance()->createTCPSocket(service, true, true);
        shared_ptr<HttpClient> httpClient(OS_NEW HttpClient(service, socket));

        HttpUrl url(m_url.to_ascii());
        bool result = httpClient->perform(url);

        if(result)
        {
            shared_ptr<HttpResponse> response = httpClient->getResponse();

            //shared_ptr<HttpContent> responseContent = response->getContent();

            if(response->getStatusCode() == 200)
            {
                m_status = "importing";

                shared_ptr<MemFile> content(OS_NEW MemFile(response->getContent()->getContentPtr()));

                shared_ptr<Portal> portal = m_portal.lock();
                if(portal == nullptr)
                    return;

                m_serializer->setStopped(false);
                m_result = m_serializer->importStream(portal, content);
            }

            m_status = "completed";
        }
        else
        {
            m_status = "failed";
        }
    }

    //Engine::instance()->addBackgroundJob(shared_ptr<PortalsOptimizerJob>(OS_NEW PortalsOptimizerJob(Engine::instance()->peekBackgroundJobID(), portal)));
}
Beispiel #3
0
// 下载预览 url 的图片
void UiUtil::previewImage(const QString &url, const QString &dir) {
    // 1. 计算缓存封面图片的路径: dir/${url-md5}.${image-suffix}
    // 2. 预览图片
    //    2.1 如果图片已经缓存,则使用缓存的图片
    //    2.2 如果没有缓存过,则从网络下载缓存到本地,缩放到适合的大小,然后显示

    // [1] 计算缓存封面图片的路径: temp/${url-md5}.${image-suffix}
    QByteArray hex = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5).toHex();
    QString    md5(hex.constData());
    QFileInfo  info(QUrl(url).fileName());
    QString    previewImagePath = QString("%1/%2.%3").arg(dir).arg(md5).arg(info.suffix());
    QFile      previewImage(previewImagePath);

    if (previewImage.exists()) {
        // [2.1] 如果预览图片已经缓存就用缓存的,否则下载最新的
        MessageBox::message(QString("<img src='%1'>").arg(previewImagePath));
    } else {
        HttpClient(url).debug(true).download(previewImagePath, [=] (const QString &) {
            // [2.2] 如果没有缓存过,则从网络下载缓存到本地,缩放到适合的大小,然后显示
            QImage image = QImage(previewImagePath).scaledToWidth(256, Qt::SmoothTransformation);
            image.save(previewImagePath);

            MessageBox::message(QString("<img src='%1'>").arg(previewImagePath));
        }, [] (const QString &error) {
            // 显示下载错误
            MessageBox::message(error);
        });
    }
}
void PowerpointGenerator::execute() {
  std::shared_ptr<SearchClient> searchClient = SearchClientFactory::createSearchClient(configuration.searchEngine);
  searchClient->executeSearch(configuration.topic);
  auto resultLinks = searchClient->getResultLinks();

  std::vector<std::string> resultHtmlContent;

  HttpClient client;
  for (auto url : resultLinks) {
    client = HttpClient(url);
    resultHtmlContent.push_back(client.getHtmlOrEmptyString());
  }
  // TO BE REMOVED
  //resultHtmlContent = std::vector<std::string>(resultHtmlContent.begin(), resultHtmlContent.begin() + 2);

  HTMLFilter filter;
  std::vector<std::string> resultHtmlContent_filtered;
  for (std::string content : resultHtmlContent) {
    resultHtmlContent_filtered.push_back(filter.execute(content));
  }
 
  ISpreadRankStrategy iSRStrategy(0.7, 100, configuration.topic, resultHtmlContent_filtered);
  std::vector<Sentence> summarySentences = iSRStrategy.execute();

  auto package = PowerpointPackageBuilder().buildFromTemplate("templates/template1.pptx");
  SlidePartBuilder builder;
  auto titleSlide = builder.buildTitleSlide(configuration.topic, "");
  package->addSlide(titleSlide, 0);
  int summarySize(5);
  std::vector<Sentence> subSummary;
  if (summarySentences.size() >= summarySize) {
    subSummary = std::vector<Sentence>(summarySentences.begin(), summarySentences.begin() + summarySize);
  } else {
    subSummary = std::vector<Sentence>(summarySentences.begin(), summarySentences.end());
  }
  std::vector<std::string> subSummaryStrings;
  for (Sentence sentence : subSummary) subSummaryStrings.push_back(sentence.content);
  auto listSlide = builder.buildBulletListSlide(configuration.topic, subSummaryStrings);
  package->addSlide(listSlide, 1);
  package->writePackage(configuration.outputFolder + "/" + configuration.topic + ".pptx");
}
bool AdminRequestHandler::handleStatsRequest(const std::string &cmd,
                                             Transport *transport) {
  if (cmd == "stats-on") {
    RuntimeOption::EnableStats = true;
    transport->sendString("OK\n");
    return true;
  }
  if (cmd == "stats-off") {
    RuntimeOption::EnableStats = false;
    transport->sendString("OK\n");
    return true;
  }
  if (cmd == "stats-clear") {
    ServerStats::Clear();
    transport->sendString("OK\n");
    return true;
  }

  if (cmd == "stats-web") {
    return toggle_switch(transport, RuntimeOption::EnableWebStats);
  }
  if (cmd == "stats-mem") {
    toggle_switch(transport, RuntimeOption::EnableMemoryStats);
    return true;
  }
  if (cmd == "stats-malloc") {
    toggle_switch(transport, RuntimeOption::EnableMallocStats);
    LeakDetectable::EnableMallocStats(RuntimeOption::EnableMallocStats);
    return true;
  }
  if (cmd == "stats-apc") {
    return toggle_switch(transport, RuntimeOption::EnableAPCStats);
  }
  if (cmd == "stats-apc-key") {
    return toggle_switch(transport, RuntimeOption::EnableAPCKeyStats);
  }
  if (cmd == "stats-mcc") {
    return toggle_switch(transport, RuntimeOption::EnableMemcacheStats);
  }
  if (cmd == "stats-sql") {
    return toggle_switch(transport, RuntimeOption::EnableSQLStats);
  }
  if (cmd == "stats-mutex") {
    int sampling = transport->getIntParam("sampling");
    if (sampling > 0) {
      LockProfiler::s_profile_sampling = sampling;
    }
    return toggle_switch(transport, LockProfiler::s_profile);
  }

  if (cmd == "stats.keys") {
    int64 from = transport->getInt64Param("from");
    int64 to = transport->getInt64Param("to");
    string out;
    ServerStats::GetKeys(out, from, to);
    transport->sendString(out);
    return true;
  }
  if (cmd == "stats.xml") {
    return send_report(transport, ServerStats::XML, "application/xml");
  }
  if (cmd == "stats.json") {
    return send_report(transport, ServerStats::JSON, "application/json");
  }
  if (cmd == "stats.kvp") {
    return send_report(transport, ServerStats::KVP, "text/plain");
  }
  if (cmd == "stats.html" || cmd == "stats.htm") {
    return send_report(transport, ServerStats::HTML, "text/html");
  }

  if (cmd == "stats.xsl") {
    string xsl;
    if (!RuntimeOption::StatsXSLProxy.empty()) {
      StringBuffer response;
      if (HttpClient().get(RuntimeOption::StatsXSLProxy.c_str(), response) ==
          200) {
        xsl = response.data();
        if (!xsl.empty()) {
          transport->addHeader("Content-Type", "application/xml");
          transport->sendString(xsl);
          return true;
        }
      }
    }
    transport->sendString("Not Found\n", 404);
    return true;
  }

  return false;
}
Beispiel #6
0
ServerCommunication::ServerCommunication(void)
{
	client = gcnew HttpClient();
}
Beispiel #7
0
void TwitterUser::GetProfileImage()
{
	if (GetProfileImageUrl() == _T("")) return;
	HttpClient().GetToFile(wxURL(GetProfileImageUrl()), GetProfileImageFilename());
}
Beispiel #8
0
Datei: main.cpp Projekt: xtuer/Qt
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    // 在代码块里执行网络访问,是为了测试 HttpClient 对象在被析构后,网络访问的回调函数仍然能正常执行
    {
        QString url("http://localhost:8080/rest");

        // [[1]] GET 请求无参数
        HttpClient(url).get([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[2]] GET 请求有参数,有自定义 header
        HttpClient(url).debug(true).param("name", "诸葛亮").header("token", "md5sum").get([](const QString &response) {
            qDebug().noquote() << response;
        });
        // 提示: 多个参数也可以传入 map: HttpClient(url).params({{"name", "诸葛亮"}, {"attackDamage", "99"}}).get(...);

        // [[3]] POST 请求,使用 param 添加参数,请求的参数使用 Form 格式
        HttpClient(url).debug(true).param("name", "卧龙")
                .post([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[4]] PUT 请求,使用 json 添加参数,请求的参数使用 Json 格式
        HttpClient(url).debug(true).json("{\"name\": \"孔明\"}").put([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[5]] DELETE 请求
        HttpClient(url).debug(true).remove([](const QString &response) {
            qDebug().noquote() << response;
        });
    }

    {
        // [[6]] 下载: 直接保存到文件
        HttpClient("http://xtuer.github.io/img/dog.png").debug(true).download("/Users/Biao/Desktop/dog-1.png");

        // [[7]] 下载: 自己处理下载得到的字节数据
        QFile *file = new QFile("/Users/Biao/Desktop/dog-2.png");
        if (file->open(QIODevice::WriteOnly)) {
            HttpClient("http://xtuer.github.io/img/dog.png").debug(true).download([=](const QByteArray &data) {
                file->write(data);
            }, [=](const QString &) {
                file->flush();
                file->close();
                file->deleteLater();

                qDebug().noquote() << "下载完成";
            });
        } else {
            file->deleteLater();
            file = nullptr;
        }
    }

    {
        // [[8]] 上传文件
        HttpClient("http://localhost:8080/upload").debug(true).upload(QString("/Users/Biao/Pictures/ade.jpg"));

        // [[9]] 上传文件: 也能同时传参数
        HttpClient("http://localhost:8080/upload").debug(true)
                .param("username", "Alice").param("password", "Passw0rd")
                .upload(QString("/Users/Biao/Pictures/ade.jpg"));

        // [[10]] 上传数据: 例如使用摄像头拍照后直接把图片数据传到服务器
        QFile dataFile("/Users/Biao/Pictures/ade.jpg");
        dataFile.open(QIODevice::ReadOnly);
        QByteArray data = dataFile.readAll();
        HttpClient("http://localhost:8080/upload").debug(true).upload(data);

        // [[11]] 上传多个文件文件
        QStringList paths;
        paths << "/Users/Biao/Desktop/photo.jpg" << "/Users/Biao/Desktop/project.numbers";
        HttpClient("http://localhost:8080/uploads").debug(true).upload(paths);
    }

    {
        // [[12]] 共享 QNetworkAccessManager
        // 每创建一个 QNetworkAccessManager 对象都会创建一个线程,当频繁的访问网络时,为了节省线程资源,调用 manager()
        // 使用共享的 QNetworkAccessManager,它不会被 HttpClient 删除,需要我们自己不用的时候删除它。
        // 如果下面的代码不传入 QNetworkAccessManager,从任务管理器里可以看到创建了几千个线程。
        QNetworkAccessManager *manager = new QNetworkAccessManager();
        for (int i = 0; i < 5000; ++i) {
            HttpClient("http://localhost:8080/rest").manager(manager).get([=](const QString &response) {
                qDebug().noquote() << response << ", " << i;
            });
        }
    }

    return a.exec();
}